diff options
author | Michele Calgaro <michele.calgaro@yahoo.it> | 2022-09-18 20:19:47 +0900 |
---|---|---|
committer | Michele Calgaro <michele.calgaro@yahoo.it> | 2022-09-18 20:39:48 +0900 |
commit | a80a494efee7979c28ab1090734270e5c0515352 (patch) | |
tree | 1cdaee39e3e5a2b32c171f8389b29b15c519c607 /src/__TODO | |
parent | 14f7e49438caa24af81a0d7d7864ce71d96791e4 (diff) | |
download | universal-indent-gui-tqt-a80a494efee7979c28ab1090734270e5c0515352.tar.gz universal-indent-gui-tqt-a80a494efee7979c28ab1090734270e5c0515352.zip |
Added main window menubar GUI. The logic of each action has not been implemented yet.
Signed-off-by: Michele Calgaro <michele.calgaro@yahoo.it>
Diffstat (limited to 'src/__TODO')
32 files changed, 7925 insertions, 0 deletions
diff --git a/src/__TODO/AboutDialog.cpp b/src/__TODO/AboutDialog.cpp new file mode 100644 index 0000000..3cbdf4f --- /dev/null +++ b/src/__TODO/AboutDialog.cpp @@ -0,0 +1,169 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "AboutDialog.h" +#include "ui_AboutDialog.h" + +#include "UiGuiVersion.h" + +#include <tntqurl.h> +#include <tqdesktopservices.h> +#include <tntqscrollbar.h> +#include <tntqtimer.h> +#include <tntqlocale.h> + +/*! + \class AboutDialog + \brief Displays a dialog window with information about UniversalIndentGUI +*/ + +/*! + \brief The constructor calls the setup function for the ui created by uic and adds + the GPL text to the text edit. + */ +AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) : + TQDialog(parent, flags), _dialogForm(NULL), _timer(NULL) +{ + _dialogForm = new Ui::AboutDialog(); + _dialogForm->setupUi(this); + + _dialogForm->authorTextBrowser->setOpenExternalLinks(true); + _dialogForm->creditsTextBrowser->setOpenExternalLinks(true); + + TQString versionString = _dialogForm->versionTextBrowser->toHtml(); + versionString = + versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg( + UiGuiVersion::getBuildDate()); + _dialogForm->versionTextBrowser->setHtml(versionString); + + _dialogForm->creditsTextBrowser->setHtml("<html><head></head><body>" + "<pre> </br></pre>" + "<h3 align='center'>Thanks go out to</h3>" + "<p align='center'><a href=\"http://www.csie.nctu.edu.tw/~chtai/\"><b>Nelson Tai</b></a> for Chinese translation, good ideas and always fast answers.</p></br>" + "<p align='center'><a href=\"http://www.hartwork.org/\"><b>Sebastian Pipping</b></a> for helping me bring UiGUI into the Debian repository and other good ideas.</p></br>" + "<p align='center'><a href=\"http://korytskyy.lviv.ua/\"><b>Oleksandr</b></a> for Ukrainian and Russian translation.</p></br>" + "<p align='center'><b>Erwan "leg"</b> for French translation and the icon logo.</p></br>" + "<p align='center'>The <a href=\"http://www.scintilla.org/\"><b>Scintilla</b></a> project for their great text editing component.</p></br>" + "<p align='center'><a href=\"http://www.riverbankcomputing.co.uk/software/qscintilla/\"><b>Riverbank</b></a> for their Scintilla TQt wrapper TQScintilla.</p></br>" + "<p align='center'>The <a href=\"http://astyle.sourceforge.net/\"><b>Artistic Style</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://invisible-island.net/bcpp/\"><b>BCPP</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.siber.com/sct/tools/cbl-beau.html\"><b>Cobol Beautifier</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://csstidy.sourceforge.net/\"><b>CSSTidy</b></a> project.</p></br>" + "<p align='center'>The <a href=\"ftp://ftp.ifremer.fr/ifremer/ditigo/fortran90/\"><b>Fortran 90 PPR</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.gnu.org/software/indent/\"><b>GNU Indent</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://sourceforge.net/projects/gcgreatcode/\"><b>GreatCode</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://linux.com.hk/penguin/man/1/hindent.html\"><b>hindent</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.digital-mines.com/htb/\"><b>HTB</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://tidy.sourceforge.net/\"><b>HTML Tidy</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://code.gosu.pl/\"><b>JsDecoder</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://jsppp.sourceforge.net/\"><b>JSPPP</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://perltidy.sourceforge.net/\"><b>Perltidy</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://beautifyphp.sourceforge.net/\"><b>PHP_Beautifier</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.waterproof.fr/products/phpCodeBeautifier/\"><b>phpCB</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://sourceforge.net/projects/phpstylist/\"><b>PHP Stylist</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://coverage.livinglogic.de/Tools/scripts/pindent.py.html\"><b>pindent</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://psti.etquinoxbase.com/\"><b>Pl/Sql tidy</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.arachnoid.com/ruby/rubyBeautifier.html\"><b>Ruby Beautifier</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://raa.ruby-lang.org/project/ruby_formatter/\"><b>Ruby Formatter</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://www.bolthole.com/AWK.html\"><b>Shell Indent</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://uncrustify.sourceforge.net/\"><b>Uncrustify</b></a> project, specially <b>Ben Gardner</b>.</p></br>" + "<p align='center'>The <a href=\"http://www.daansystems.com/vbsbeaut/\"><b>VBSBeautifier</b></a> project.</p></br>" + "<p align='center'>The <a href=\"http://xmlindent.sourceforge.net/\"><b>XML Indent</b></a> project.</p></br>" + "<p align='center'><b>Nirvash</b> for the initial Japanese translation.</p></br>" + "<p align='center'>The <a href=\"http://tango.freedesktop.org/Tango_Desktop_Project/\"><b>Tango Project</b></a> for their icons.</p></br>" + "<p align='center'><a href=\"http://www.famfamfam.com/\"><b>famfamfam</b></a> for the flag icons.</p></br>" + "<p align='center'><a href=\"http://trolltech.com/\"><b>Trolltech</b></a> for their really great GUI framework <img src=\":/aboutDialog/qt_logo.png\"/>.</p></br>" + "<h3 align='center'>My girlfriend (meanwhile also wife) for putting my head right and not sit all the time in front of my computer ;-)</h3>" + "</body></html>"); + + _scrollDirection = 1; + _scrollSpeed = 100; + _timer = new TQTimer(this); + connect(_timer, SIGNAL(timeout()), this, SLOT(scroll())); + connect(this, SIGNAL(accepted()), _timer, SLOT(stop())); +} + +/*! + \brief Catches language change events and retranslates all needed widgets. + */ +void AboutDialog::changeEvent(TQEvent *event) +{ + if (event->type() == TQEvent::LanguageChange) + { + _dialogForm->retranslateUi(this); + + TQString versionString = _dialogForm->versionTextBrowser->toHtml(); + versionString = + versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg( + UiGuiVersion::getBuildDate()); + _dialogForm->versionTextBrowser->setHtml(versionString); + } + else + { + TQWidget::changeEvent(event); + } +} + +/*! + \brief Reimplements the dialog execution function to init the credits scroller. + */ +int AboutDialog::exec() +{ + //creditsTextBrowser->verticalScrollBar()->setValue(0); + _timer->start(_scrollSpeed); + return TQDialog::exec(); +} + +/*! + \brief This slot is called each _timer timeout to scroll the credits textbrowser. + Also changes the scroll direction and speed when reaching the start or end. + */ +void AboutDialog::scroll() +{ + TQScrollBar *scrollBar = _dialogForm->creditsTextBrowser->verticalScrollBar(); + scrollBar->setValue(scrollBar->value() + _scrollDirection); + + if (scrollBar->value() == scrollBar->maximum()) + { + // Toggle scroll direction and change scroll speed; + _scrollDirection = -1; + _scrollSpeed = 5; + _timer->stop(); + _timer->start(_scrollSpeed); + } + else if (scrollBar->value() == scrollBar->minimum()) + { + // Toggle scroll direction and change scroll speed; + _scrollDirection = 1; + _scrollSpeed = 100; + _timer->stop(); + _timer->start(_scrollSpeed); + } + + _dialogForm->creditsTextBrowser->update(); +} + +/*! + \brief Shows the about dialog and also starts the credits scroller. + */ +void AboutDialog::show() +{ + _timer->start(_scrollSpeed); + TQDialog::show(); +} diff --git a/src/__TODO/AboutDialog.h b/src/__TODO/AboutDialog.h new file mode 100644 index 0000000..c849f7b --- /dev/null +++ b/src/__TODO/AboutDialog.h @@ -0,0 +1,54 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef ABOUTDIALOG_H +#define ABOUTDIALOG_H + +#include <tntqdialog.h> + +namespace Ui +{ + class AboutDialog; +} + + +class AboutDialog : public TQDialog +{ + Q_OBJECT + + public: + AboutDialog(TQWidget *parent = NULL, TQt::WindowFlags flags = 0); + + public slots: + int exec(); + void show(); + + private slots: + void scroll(); + + private: + void changeEvent(TQEvent *event); + + Ui::AboutDialog *_dialogForm; + int _scrollDirection; + int _scrollSpeed; + TQTimer *_timer; +}; + +#endif // ABOUTDIALOG_H diff --git a/src/__TODO/AboutDialog.ui b/src/__TODO/AboutDialog.ui new file mode 100755 index 0000000..dbc2b8c --- /dev/null +++ b/src/__TODO/AboutDialog.ui @@ -0,0 +1,218 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>AboutDialog</class> + <widget class="TQDialog" name="AboutDialog"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>588</width> + <height>512</height> + </rect> + </property> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Preferred"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>588</width> + <height>333</height> + </size> + </property> + <property name="windowTitle"> + <string>About UniversalIndentGUI</string> + </property> + <property name="windowIcon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/info.png</normaloff>:/mainWindow/info.png</iconset> + </property> + <layout class="TQVBoxLayout"> + <property name="margin"> + <number>0</number> + </property> + <item> + <widget class="TQFrame" name="frame"> + <property name="styleSheet"> + <string notr="true">TQFrame#frame { background-color: qlineargradient( x1:0, y1:0, x2:0, y2:1, stop:0 #FFFF60, stop:0.5 #D8C304, stop:1 #FFFF60 ); border: 2px solid #A89C57; border-radius: 4px;}</string> + </property> + <property name="frameShape"> + <enum>TQFrame::StyledPanel</enum> + </property> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQLabel" name="bannerLabel"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>570</width> + <height>87</height> + </size> + </property> + <property name="maximumSize"> + <size> + <width>570</width> + <height>87</height> + </size> + </property> + <property name="text"> + <string/> + </property> + <property name="pixmap"> + <pixmap resource="../resources/Icons.qrc">:/aboutDialog/banner.png</pixmap> + </property> + </widget> + </item> + <item> + <widget class="TQTextBrowser" name="versionTextBrowser"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Preferred"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="maximumSize"> + <size> + <width>16777215</width> + <height>25</height> + </size> + </property> + <property name="styleSheet"> + <string notr="true">TQTextBrowser{background-color:transparent}</string> + </property> + <property name="frameShape"> + <enum>TQFrame::NoFrame</enum> + </property> + <property name="verticalScrollBarPolicy"> + <enum>TQt::ScrollBarAlwaysOff</enum> + </property> + <property name="html"> + <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Lucida Grande'; font-size:13pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'sans-serif'; font-size:large;">Version %1 rev.%2, %3</span></p></body></html></string> + </property> + </widget> + </item> + <item> + <widget class="TQTextBrowser" name="authorTextBrowser"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="MinimumExpanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="acceptDrops"> + <bool>false</bool> + </property> + <property name="styleSheet"> + <string notr="true">TQTextBrowser{background-color:transparent}</string> + </property> + <property name="frameShape"> + <enum>TQFrame::NoFrame</enum> + </property> + <property name="verticalScrollBarPolicy"> + <enum>TQt::ScrollBarAlwaysOff</enum> + </property> + <property name="html"> + <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Lucida Grande'; font-size:13pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;">... is a cross platform compatible GUI for several code formatter, beautifier and indenter like GreatCode, AStyle (Artistic Styler), GNU Indent, BCPP and so on. Main feature is a live preview to directly see how the selected formatting option affects the source code.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;"><br />Written by : </span><a href="http://www.thomas-schweitzer.de"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium; text-decoration: underline; color:#0000ff;">Thomas Schweitzer</span></a></p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;">Project Homepage : </span><a href="http://universalindent.sourceforge.net"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium; text-decoration: underline; color:#0000ff;">http://universalindent.sourceforge.net</span></a></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;">License: UniversalIndentGui is released under the GPL 2. For details read the included file LICENSE.GPL visit </span><a href="http://www.gnu.org/licenses/gpl.html"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium; text-decoration: underline; color:#0000ff;">http://www.gnu.org/licenses/gpl.html</span></a><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;">.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Trebuchet MS,Helvetica,sans-serif'; font-size:medium;">Credits:</span></p></body></html></string> + </property> + </widget> + </item> + <item> + <widget class="TQTextBrowser" name="creditsTextBrowser"> + <property name="styleSheet"> + <string notr="true">TQTextBrowser#creditsTextBrowser{border:2px solid rgba(0,0,0,10%); background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0,0,0,80%), stop:0.1 rgba(0,0,0,15%), stop:0.9 rgba(0,0,0,15%), stop:1 rgba(0,0,0,80%) )}</string> + </property> + <property name="frameShape"> + <enum>TQFrame::NoFrame</enum> + </property> + <property name="verticalScrollBarPolicy"> + <enum>TQt::ScrollBarAlwaysOff</enum> + </property> + </widget> + </item> + <item> + <layout class="TQHBoxLayout"> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>131</width> + <height>31</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="TQPushButton" name="okButton"> + <property name="styleSheet"> + <string notr="true">TQPushButton#okButton { background-color: qlineargradient( x1:0, y1:0, x2:0, y2:1, stop:0 #DCB28A, stop:0.5 #B8784B, stop:1 #DCB28A ); border: 2px solid #A89C57; border-radius: 4px;} TQPushButton:hover#okButton { background-color: qlineargradient( x1:0, y1:0, x2:0, y2:1, stop:0 #B8784B, stop:0.5 #DCB28A, stop:1 #B8784B ); } TQPushButton:pressed#okButton{ border: 2px solid #D8CB75 }</string> + </property> + <property name="text"> + <string> OK </string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <resources> + <include location="../resources/Icons.qrc"/> + </resources> + <connections> + <connection> + <sender>okButton</sender> + <signal>clicked()</signal> + <receiver>AboutDialog</receiver> + <slot>accept()</slot> + <hints> + <hint type="sourcelabel"> + <x>278</x> + <y>253</y> + </hint> + <hint type="destinationlabel"> + <x>96</x> + <y>254</y> + </hint> + </hints> + </connection> + </connections> +</ui> diff --git a/src/__TODO/AboutDialogGraphicsView.cpp b/src/__TODO/AboutDialogGraphicsView.cpp new file mode 100644 index 0000000..3c031f2 --- /dev/null +++ b/src/__TODO/AboutDialogGraphicsView.cpp @@ -0,0 +1,220 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ + +#include "AboutDialogGraphicsView.h" + +#include "AboutDialog.h" + +#include <tqtgui.h> +#include <tntqdesktopwidget.h> +#include <tqdate.h> +#include <tqtimeline.h> +#include <tntqsplashscreen.h> + +/*! + \class AboutDialogGraphicsView + \brief A container for the real \a AboutDialog. Makes the 3D animation possible. + + The 3D animation shall suggest the user, that he is looking at his desktop, while + this animation is done. Since this is not directly possible, \a AboutDialogGraphicsView + when shown starts in frameless fullscreen mode with a screenshot of the desktop as background. +*/ + +/*! + \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) +{ + _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()); +#else + TQRect newGeometry = TQRect(-1, -1, + TQApplication::desktop()->rect().width() + 2, + TQApplication::desktop()->rect().height() + 2); +#endif + setGeometry(newGeometry); + + _aboutDialog = aboutDialog; + + _windowTitleBarWidth = 0; + _windowPosOffset = 0; + + TQGraphicsScene *scene = new TQGraphicsScene(this); + setSceneRect(newGeometry); + _aboutDialogAsSplashScreen = new TQSplashScreen(this); + _graphicsProxyWidget = scene->addWidget(_aboutDialogAsSplashScreen); + _graphicsProxyWidget->setWindowFlags(TQt::ToolTip); + + setScene(scene); + setRenderHint(TQPainter::Antialiasing); + + setCacheMode(TQGraphicsView::CacheBackground); + setViewportUpdateMode(TQGraphicsView::BoundingRectViewportUpdate); + + connect(_aboutDialog, SIGNAL(finished(int)), this, SLOT(hide())); + + //setWindowOpacity(0.9); + + setVerticalScrollBarPolicy(TQt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(TQt::ScrollBarAlwaysOff); + setStyleSheet("AboutDialogGraphicsView { border: 0px; }"); + + _timeLine = new TQTimeLine(1000, this); + _timeLine->setFrameRange(270, 0); + //_timeLine->setUpdateInterval(10); + //_timeLine->setCurveShape(TQTimeLine::EaseInCurve); + connect(_timeLine, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int))); +} + +AboutDialogGraphicsView::~AboutDialogGraphicsView(void) +{ +} + +/*! + \brief Grabs a screenshot of the full desktop and shows that as background. Above that background the + AboutDialog 3D animation is shown. Also grabs the content of the AboutDialog itself. + */ +void AboutDialogGraphicsView::show() +{ + // Because on X11 system the window decoration is only available after a widget has been shown + // once, + // we can detect _windowTitleBarWidth here for the first time. + _windowTitleBarWidth = _parentWindow->geometry().y() - _parentWindow->y(); + // If the _windowTitleBarWidth could not be determined, try it a second way. Even the chances are + // low to get good results. + if (_windowTitleBarWidth == 0) + { + _windowTitleBarWidth = _parentWindow->frameGeometry().height() - + _parentWindow->geometry().height(); + } +#ifdef Q_OS_LINUX + if (_windowTitleBarWidth == 0) + { + //TODO: 27 pixel is a fix value for the Ubuntu 10.4 default window theme and so just a + // workaround for that specific case. + _windowPosOffset = 27; + _windowTitleBarWidth = 27; + } +#endif + TQPixmap originalPixmap = TQPixmap::grabWindow( + TQApplication::desktop()->winId(), + TQApplication::desktop()->availableGeometry().x(), + TQApplication::desktop()->availableGeometry().y(), geometry().width(), + geometry().height()); + TQBrush brush(originalPixmap); + TQTransform transform; + transform.translate(0, TQApplication::desktop()->availableGeometry().y()); + brush.setTransform(transform); + + setBackgroundBrush(brush); + + _aboutDialogAsSplashScreen->setPixmap(TQPixmap::grabWidget(_aboutDialog)); + _graphicsProxyWidget->setGeometry(_aboutDialog->geometry()); + _aboutDialog->hide(); + _graphicsProxyWidget->setPos(_parentWindow->geometry().x() + + (_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2, + _parentWindow->y() + _windowTitleBarWidth - _windowPosOffset); + + TQRectF r = _graphicsProxyWidget->boundingRect(); + _graphicsProxyWidget->setTransform(TQTransform().translate( + r.width() / 2, -_windowTitleBarWidth).rotate(270, TQt::XAxis) + //.rotate(90, TQt::YAxis) + //.rotate(5, TQt::ZAxis) + //.scale(1 + 1.5 * step, 1 + 1.5 * step) + .translate(-r.width() / 2, _windowTitleBarWidth)); + + _graphicsProxyWidget->show(); + //_aboutDialogAsSplashScreen->show(); + TQGraphicsView::show(); + + connect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog())); + _timeLine->setDirection(TQTimeLine::Forward); + _timeLine->start(); +} + +/*! + \brief Does the next calculation/transformation step. + */ +void AboutDialogGraphicsView::updateStep(int step) +{ + TQRectF r = _graphicsProxyWidget->boundingRect(); + _graphicsProxyWidget->setTransform(TQTransform().translate( + r.width() / 2, -_windowTitleBarWidth).rotate(step, TQt::XAxis) + //.rotate(step, TQt::YAxis) + //.rotate(step * 5, TQt::ZAxis) + //.scale(1 + 1.5 * step, 1 + 1.5 * step) + .translate(-r.width() / 2, _windowTitleBarWidth)); + //update(); +} + +/*! + \brief Stops the 3D animation, moves the AboutDialog to the correct place and really shows it. + */ +void AboutDialogGraphicsView::showAboutDialog() +{ + //hide(); + disconnect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog())); + _aboutDialog->move(int(_parentWindow->geometry().x() + + (_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2), + _parentWindow->y() + _windowTitleBarWidth - _windowPosOffset); + _aboutDialog->exec(); +} + +/*! + \brief Does not directly hide the AboutDialog but instead starts the "fade out" 3D animation. + */ +void AboutDialogGraphicsView::hide() +{ + _graphicsProxyWidget->setPos(_parentWindow->geometry().x() + + (_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2, + _parentWindow->y() + _windowTitleBarWidth - _windowPosOffset); + + TQRectF r = _graphicsProxyWidget->boundingRect(); + _graphicsProxyWidget->setTransform(TQTransform().translate( + r.width() / 2, -_windowTitleBarWidth).rotate(0, TQt::XAxis) + //.rotate(90, TQt::YAxis) + //.rotate(5, TQt::ZAxis) + //.scale(1 + 1.5 * step, 1 + 1.5 * step) + .translate(-r.width() / 2, _windowTitleBarWidth)); + + _graphicsProxyWidget->show(); + //_aboutDialogAsSplashScreen->show(); + TQGraphicsView::show(); + + connect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally())); + _timeLine->setDirection(TQTimeLine::Backward); + _timeLine->start(); +} + +/*! + \brief This slot really hides this AboutDialog container. + */ +void AboutDialogGraphicsView::hideReally() +{ + disconnect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally())); + TQGraphicsView::hide(); + _parentWindow->activateWindow(); +} diff --git a/src/__TODO/AboutDialogGraphicsView.h b/src/__TODO/AboutDialogGraphicsView.h new file mode 100644 index 0000000..4554e36 --- /dev/null +++ b/src/__TODO/AboutDialogGraphicsView.h @@ -0,0 +1,57 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ +#ifndef ABOUTDIALOGGRAPHICSVIEW_H +#define ABOUTDIALOGGRAPHICSVIEW_H + +#include <tqgraphicsview.h> + +class AboutDialog; + +class TQTimeLine; +class TQSplashScreen; + + +class AboutDialogGraphicsView : public TQGraphicsView +{ + Q_OBJECT + + public: + AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow = NULL); + ~AboutDialogGraphicsView(void); + + public slots: + void show(); + void hide(); + + private slots: + void updateStep(int step); + void showAboutDialog(); + void hideReally(); + + private: + AboutDialog *_aboutDialog; + TQGraphicsProxyWidget *_graphicsProxyWidget; + TQWidget *_parentWindow; + TQTimeLine *_timeLine; + TQSplashScreen *_aboutDialogAsSplashScreen; + int _windowTitleBarWidth; + int _windowPosOffset; +}; + +#endif // ABOUTDIALOGGRAPHICSVIEW_H diff --git a/src/__TODO/FindDialog.ui b/src/__TODO/FindDialog.ui new file mode 100755 index 0000000..00cc527 --- /dev/null +++ b/src/__TODO/FindDialog.ui @@ -0,0 +1,121 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>FindDialog</class> + <widget class="TQDialog" name="FindDialog"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>347</width> + <height>227</height> + </rect> + </property> + <property name="windowTitle"> + <string>Find</string> + </property> + <layout class="TQVBoxLayout" name="verticalLayout"> + <item> + <widget class="TQLabel" name="label"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Maximum"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Find what:</string> + </property> + </widget> + </item> + <item> + <widget class="TQComboBox" name="comboBox"> + <property name="editable"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="TQGroupBox" name="groupBox"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="title"> + <string>Find options</string> + </property> + <layout class="TQVBoxLayout" name="verticalLayout_2"> + <item> + <widget class="TQCheckBox" name="checkBox"> + <property name="text"> + <string>Match case</string> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="checkBox_2"> + <property name="text"> + <string>Match whole word</string> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="checkBox_3"> + <property name="text"> + <string>Search forward</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="checkBox_4"> + <property name="text"> + <string>Use Regular Expressions</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>TQt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item> + <layout class="TQHBoxLayout" name="horizontalLayout"> + <property name="sizeConstraint"> + <enum>TQLayout::SetMaximumSize</enum> + </property> + <item> + <widget class="TQPushButton" name="pushButton"> + <property name="text"> + <string>Find Next</string> + </property> + </widget> + </item> + <item> + <widget class="TQPushButton" name="pushButton_2"> + <property name="text"> + <string>Close</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/src/__TODO/IndentHandler.cpp b/src/__TODO/IndentHandler.cpp new file mode 100644 index 0000000..b0378a8 --- /dev/null +++ b/src/__TODO/IndentHandler.cpp @@ -0,0 +1,2044 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "IndentHandler.h" + +#include "UiGuiSettings.h" +#include "UiGuiErrorMessage.h" +#include "TemplateBatchScript.h" +#include "UiGuiIniFileParser.h" +#include "SettingsPaths.h" + +#include <tntqtoolbox.h> +#include <tqvboxlayout.h> +#include <tntqapplication.h> +#include <tntqcheckbox.h> +#include <tntqcombobox.h> +#include <tntqtoolbutton.h> +#include <tntqfile.h> +#include <tntqprocess.h> +#include <tntqsettings.h> +#include <tntqstringlist.h> +#include <tntqlineedit.h> +#include <tntqspinbox.h> +#include <tntqlabel.h> +#include <tqbytearray.h> +#include <tntqdir.h> +#include <tntqmessagebox.h> +#include <tntqmainwindow.h> +#include <tntqtextstream.h> +#include <tntqtextcodec.h> +#include <tqtscript.h> +#include <tqdesktopservices.h> +#include <tqmenu.h> +#include <tntqaction.h> +#include <tqcontextmenuevent.h> +#include <tntqfiledialog.h> +#include <tqtdebug.h> + +#ifdef Q_OS_WIN32 + #include <Windows.h> +#endif + +// Avoid unused parameter warnings by this template +template<typename T> +inline void UNUSED_PARAMETER_WARNING_AVOID(T) +{ +} + +//! \defgroup grp_Indenter All concerning handling of the indenter. + +/*! + \class IndentHandler + \ingroup grp_Indenter + \brief A widget for handling many indenters that are configured by an ini file. + + This is a widget that is used by the main window. It handles access to the + indenter config file and calls the chosen indenter to reformat the source text. + Calls the indenter each time a setting has been changed and informs + the main window about the reformatted source code. +*/ + + +/*! + \brief Constructor of the indent handler. + + By calling this constructor the indenter to be loaded, can be selected by setting + its \a indenterID, which is the number of found indenter ini files in alphabetic + order starting at index 0. + */ +IndentHandler::IndentHandler(int indenterID, TQWidget *mainWindow, TQWidget *parent) : + TQWidget(parent), _indenterSelectionCombobox(NULL), _indenterParameterHelpButton(NULL), + _toolBoxContainerLayout(NULL), _indenterParameterCategoriesToolBox(NULL), _indenterSettings( + NULL), _mainWindow(NULL), _errorMessageDialog(NULL), _menuIndenter(NULL), + _actionLoadIndenterConfigFile(NULL), _actionSaveIndenterConfigFile(NULL), + _actionCreateShellScript(NULL), _actionResetIndenterParameters(NULL), + _parameterChangedCallback(NULL), _windowClosedCallback(NULL) +{ + Q_ASSERT_X(indenterID >= 0, "IndentHandler", "the selected indenterID is < 0"); + + setObjectName(TQString::fromUtf8("indentHandler")); + + _mainWindow = mainWindow; + + initIndenterMenu(); + + connect(_actionLoadIndenterConfigFile, SIGNAL(triggered()), this, SLOT(openConfigFileDialog())); + connect(_actionSaveIndenterConfigFile, SIGNAL(triggered()), this, SLOT( + saveasIndentCfgFileDialog())); + connect(_actionCreateShellScript, SIGNAL(triggered()), this, + SLOT(createIndenterCallShellScript())); + connect(_actionResetIndenterParameters, SIGNAL(triggered()), this, + SLOT(resetIndenterParameter())); + + // define this widgets resize behavior + setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Expanding); + + // create vertical layout box, into which the toolbox will be added + _toolBoxContainerLayout = new TQVBoxLayout(this); + _toolBoxContainerLayout->setMargin(2); + + // Create horizontal layout for indenter selector and help button. + TQHBoxLayout *hboxLayout = new TQHBoxLayout(); + //hboxLayout->setMargin(2); + _toolBoxContainerLayout->addLayout(hboxLayout); + + // Create the indenter selection combo box. + _indenterSelectionCombobox = new TQComboBox(this); + _indenterSelectionCombobox->setSizeAdjustPolicy(TQComboBox::AdjustToMinimumContentsLengthWithIcon); + _indenterSelectionCombobox->setMinimumContentsLength(20); + connect(_indenterSelectionCombobox, SIGNAL(activated(int)), this, SLOT(setIndenter(int))); + UiGuiSettings::getInstance()->registerObjectProperty(_indenterSelectionCombobox, "currentIndex", + "selectedIndenter"); + hboxLayout->addWidget(_indenterSelectionCombobox); + + // Create the indenter parameter help button. + _indenterParameterHelpButton = new TQToolButton(this); + _indenterParameterHelpButton->setObjectName(TQString::fromUtf8("indenterParameterHelpButton")); + _indenterParameterHelpButton->setIcon(TQIcon(TQString::fromUtf8(":/mainWindow/help.png"))); + hboxLayout->addWidget(_indenterParameterHelpButton); + // Handle if the indenter parameter help button is pressed. + connect(_indenterParameterHelpButton, SIGNAL(clicked()), this, SLOT(showIndenterManual())); + + // create a toolbox and set its resize behavior + _indenterParameterCategoriesToolBox = new TQToolBox(this); + _indenterParameterCategoriesToolBox->setObjectName(TQString::fromUtf8( + "_indenterParameterCategoriesToolBox")); + +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + connect(_indenterParameterCategoriesToolBox, SIGNAL(currentChanged(int)), this, + SLOT(updateDrawing())); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS + + //_indenterParameterCategoriesToolBox->setSizePolicy( TQSizePolicy::Expanding, + // TQSizePolicy::Expanding ); + //_indenterParameterCategoriesToolBox->setMaximumSize(TQSize(16777215, 16777215)); + // insert the toolbox into the vlayout + _toolBoxContainerLayout->addWidget(_indenterParameterCategoriesToolBox); + + _indenterExecutableCallString = ""; + _indenterExecutableSuffix = ""; + + _indenterDirctoryStr = SettingsPaths::getIndenterPath(); + _tempDirctoryStr = SettingsPaths::getTempPath(); + _settingsDirctoryStr = SettingsPaths::getSettingsPath(); + TQDir indenterDirctory = TQDir(_indenterDirctoryStr); + + if (_mainWindow != NULL) + { + _errorMessageDialog = new UiGuiErrorMessage(_mainWindow); + } + else + { + _errorMessageDialog = new UiGuiErrorMessage(this); + } + + _indenterIniFileList = indenterDirctory.entryList(TQStringList("uigui_*.ini")); + if (_indenterIniFileList.count() > 0) + { + // Take care if the selected indenterID is smaller or greater than the number of existing + // indenters + if (indenterID < 0) + { + indenterID = 0; + } + if (indenterID >= _indenterIniFileList.count()) + { + indenterID = _indenterIniFileList.count() - 1; + } + + // Reads and parses the by indenterID defined indent ini file and creates toolbox entries + readIndentIniFile(_indenterDirctoryStr + "/" + _indenterIniFileList.at(indenterID)); + + // Find out how the indenter can be executed. + createIndenterCallString(); + + // Load the users last settings made for this indenter. + loadConfigFile(_settingsDirctoryStr + "/" + _indenterFileName + ".cfg"); + + // Fill the indenter selection combo box with the list of available indenters. + if (!getAvailableIndenters().isEmpty()) + { + _indenterSelectionCombobox->addItems(getAvailableIndenters()); + _indenterSelectionCombobox->setCurrentIndex(indenterID); + connect(_indenterSelectionCombobox, SIGNAL(currentIndexChanged(int)), this, + SIGNAL(selectedIndenterIndexChanged(int))); + } + } + else + { + _errorMessageDialog->showMessage(tr("No indenter ini files"), + tr("There exists no indenter ini files in the directory \"") + + TQDir(_indenterDirctoryStr).absolutePath() + "\"."); + } + + retranslateUi(); +} + +/*! + \brief Implicitly writes the current indenter parameters to the indenters config file. + */ +IndentHandler::~IndentHandler() +{ + // Generate the parameter string that will be saved to the indenters config file. + TQString parameterString = getParameterString(); + if (!_indenterFileName.isEmpty()) + { + saveConfigFile(_settingsDirctoryStr + "/" + _indenterFileName + ".cfg", parameterString); + } + + delete _errorMessageDialog; +} + +/*! + \brief Initializes the context menu used for some actions like saving the indenter config file. + */ +void IndentHandler::initIndenterMenu() +{ + if (_menuIndenter == NULL) + { + _actionLoadIndenterConfigFile = new TQAction(this); + _actionLoadIndenterConfigFile->setObjectName(TQString::fromUtf8("_actionLoadIndenterConfigFile")); + _actionLoadIndenterConfigFile->setIcon(TQIcon(TQString::fromUtf8( + ":/mainWindow/load_indent_cfg.png"))); + + _actionSaveIndenterConfigFile = new TQAction(this); + _actionSaveIndenterConfigFile->setObjectName(TQString::fromUtf8("_actionSaveIndenterConfigFile")); + _actionSaveIndenterConfigFile->setIcon(TQIcon(TQString::fromUtf8( + ":/mainWindow/save_indent_cfg.png"))); + + _actionCreateShellScript = new TQAction(this); + _actionCreateShellScript->setObjectName(TQString::fromUtf8("_actionCreateShellScript")); + _actionCreateShellScript->setIcon(TQIcon(TQString::fromUtf8(":/mainWindow/shell.png"))); + + _actionResetIndenterParameters = new TQAction(this); + _actionResetIndenterParameters->setObjectName(TQString::fromUtf8( + "_actionResetIndenterParameters")); + _actionResetIndenterParameters->setIcon(TQIcon(TQString::fromUtf8( + ":/mainWindow/view-refresh.png"))); + + _menuIndenter = new TQMenu(this); + _menuIndenter->setObjectName(TQString::fromUtf8("_menuIndenter")); + _menuIndenter->addAction(_actionLoadIndenterConfigFile); + _menuIndenter->addAction(_actionSaveIndenterConfigFile); + _menuIndenter->addAction(_actionCreateShellScript); + _menuIndenter->addAction(_actionResetIndenterParameters); + } +} + +/*! + \brief Returns the context menu used for some actions like saving the indenter config file. + */ +TQMenu* IndentHandler::getIndenterMenu() +{ + return _menuIndenter; +} + +/*! + \brief Returns the actions of the context menu used for some actions like saving the indenter config file. + */ +TQList<TQAction*> IndentHandler::getIndenterMenuActions() +{ + TQList<TQAction*> actionList; + actionList << _actionLoadIndenterConfigFile << _actionSaveIndenterConfigFile << + _actionCreateShellScript << _actionResetIndenterParameters; + return actionList; +} + +/*! + \brief Opens the context menu, used for some actions like saving the indenter config file, at the event position. + */ +void IndentHandler::contextMenuEvent(TQContextMenuEvent *event) +{ + getIndenterMenu()->exec(event->globalPos()); +} + +/*! + \brief Creates the content for a shell script that can be used as a external tool call + to indent an as parameter defined file. + */ +TQString IndentHandler::generateShellScript(const TQString &configFilename) +{ + TQString indenterCompleteCallString; + TQString parameterInputFile; + TQString parameterOuputFile; + TQString parameterParameterFile; + TQString replaceInputFileCommand; + + // Define the placeholder for parameter variables either in batch or bash programming. +#if defined (Q_OS_WIN32) + TQString shellParameterPlaceholder = "%1"; +#else + TQString shellParameterPlaceholder = "$1"; +#endif + + parameterInputFile = " " + _inputFileParameter + "\"" + shellParameterPlaceholder + "\""; + + if (_outputFileParameter != "none" && _outputFileParameter != "stdout") + { + if (_outputFileName == _inputFileName) + { + parameterOuputFile = " " + _outputFileParameter + "\"" + shellParameterPlaceholder + "\""; + } + else + { + parameterOuputFile = " " + _outputFileParameter + _outputFileName + ".tmp"; + } + } + + // If the config file name is empty it is assumed that all parameters are sent via command line + // call + if (_globalConfigFilename.isEmpty()) + { + parameterParameterFile = " " + getParameterString(); + } + // else if needed add the parameter to the indenter call string where the config file can be + // found. + else if (_useCfgFileParameter != "none") + { + parameterParameterFile = " " + _useCfgFileParameter + "\"./" + configFilename + "\""; + } + + // Assemble indenter call string for parameters according to the set order. + if (_parameterOrder == "ipo") + { + indenterCompleteCallString = parameterInputFile + parameterParameterFile + parameterOuputFile; + } + else if (_parameterOrder == "pio") + { + indenterCompleteCallString = parameterParameterFile + parameterInputFile + parameterOuputFile; + } + else if (_parameterOrder == "poi") + { + indenterCompleteCallString = parameterParameterFile + parameterOuputFile + parameterInputFile; + } + else + { + indenterCompleteCallString = parameterInputFile + parameterOuputFile + parameterParameterFile; + } + + // Generate the indenter call string either for win32 or other systems. +#if defined (Q_OS_WIN32) + indenterCompleteCallString = _indenterExecutableCallString + indenterCompleteCallString; +#else + indenterCompleteCallString = "#!/bin/bash\n" + _indenterExecutableCallString + + indenterCompleteCallString; +#endif + + // If the indenter writes to stdout pipe the output into a file + if (_outputFileParameter == "stdout") + { + indenterCompleteCallString = indenterCompleteCallString + " >" + _outputFileName + ".tmp"; + } + + // If the output filename is not the same as the input filename copy the output over the input. + if (_outputFileName != _inputFileName) + { +#if defined (Q_OS_WIN32) + replaceInputFileCommand = "move /Y " + _outputFileName + ".tmp \"" + shellParameterPlaceholder + + "\"\n"; +#else + replaceInputFileCommand = "mv " + _outputFileName + ".tmp \"" + shellParameterPlaceholder + + "\"\n"; +#endif + } + +#if defined (Q_OS_WIN32) + TQString shellScript(TemplateBatchScript::getTemplateBatchScript()); + shellScript = shellScript.replace("__INDENTERCALLSTRING2__", + indenterCompleteCallString + "\n" + replaceInputFileCommand); + indenterCompleteCallString = indenterCompleteCallString.replace("%1", "%%G"); + replaceInputFileCommand = replaceInputFileCommand.replace("%1", "%%G"); + shellScript = shellScript.replace("__INDENTERCALLSTRING1__", + indenterCompleteCallString + "\n" + replaceInputFileCommand); +#else + TQString shellScript(TemplateBatchScript::getTemplateBatchScript()); + shellScript = shellScript.replace("__INDENTERCALLSTRING2__", + indenterCompleteCallString + "\n" + replaceInputFileCommand); + indenterCompleteCallString = indenterCompleteCallString.replace("$1", "$file2indent"); + replaceInputFileCommand = replaceInputFileCommand.replace("$1", "$file2indent"); + shellScript = shellScript.replace("__INDENTERCALLSTRING1__", + indenterCompleteCallString + "\n" + replaceInputFileCommand); +#endif + + return shellScript; +} + +/*! + \brief Format \a sourceCode by calling the indenter. + + The \a inputFileExtension has to be given as parameter so the called indenter + can identify the programming language if needed. + */ +TQString IndentHandler::callIndenter(TQString sourceCode, TQString inputFileExtension) +{ + if (_indenterExecutableSuffix == ".js") + { + return callJavaScriptIndenter(sourceCode); + } + else + { + return callExecutableIndenter(sourceCode, inputFileExtension); + } +} + +/*! + \brief Format \a sourceCode by calling the interpreted JavaScript code of the indenter. + + The \a inputFileExtension has to be given as parameter so the called indenter + can identify the programming language if needed. + */ +TQString IndentHandler::callJavaScriptIndenter(TQString sourceCode) +{ + TQScriptEngine engine; + + engine.globalObject().setProperty("unformattedCode", sourceCode); + + TQFile jsDecoderFile(_indenterExecutableCallString); + TQString jsDecoderCode; + if (jsDecoderFile.open(TQFile::ReadOnly)) + { + jsDecoderCode = jsDecoderFile.readAll(); + } + jsDecoderFile.close(); + + TQScriptValue value = engine.evaluate(jsDecoderCode); + return value.toString(); +} + +/*! + \brief Format \a sourceCode by calling the binary executable of the indenter. + + The \a inputFileExtension has to be given as parameter so the called indenter + can identify the programming language if needed. + */ +TQString IndentHandler::callExecutableIndenter(TQString sourceCode, TQString inputFileExtension) +{ + Q_ASSERT_X(!_inputFileName.isEmpty(), "callIndenter", "_inputFileName is empty"); + // Q_ASSERT_X( !_outputFileName.isEmpty(), "callIndenter", "_outputFileName is empty" ); + Q_ASSERT_X(!_indenterFileName.isEmpty(), "callIndenter", "_indenterFileName is empty"); + + if (_indenterFileName.isEmpty()) + { + return ""; + } + + TQString formattedSourceCode; + TQString indenterCompleteCallString; + TQString parameterInputFile; + TQString parameterOuputFile; + TQString parameterParameterFile; + TQProcess indentProcess; + TQString processReturnString; + + // Generate the parameter string that will be saved to the indenters config file + TQString parameterString = getParameterString(); + + if (!_globalConfigFilename.isEmpty()) + { + saveConfigFile(_tempDirctoryStr + "/" + _globalConfigFilename, parameterString); + } + + // Only add a dot to file extension if the string is not empty + if (!inputFileExtension.isEmpty()) + { + inputFileExtension = "." + inputFileExtension; + } + + // Delete any previously used input src file and create a new input src file. + TQFile::remove(_tempDirctoryStr + "/" + _inputFileName + inputFileExtension); + TQFile inputSrcFile(_tempDirctoryStr + "/" + _inputFileName + inputFileExtension); + // Write the source code to the input file for the indenter + if (inputSrcFile.open(TQFile::ReadWrite | TQFile::Text)) + { + inputSrcFile.write(sourceCode.toUtf8()); + inputSrcFile.close(); + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Wrote to be indented source code to file " << + inputSrcFile.fileName(); + } + else + { + qCritical() << __LINE__ << " " << __FUNCTION__ << + ": Couldn't write to be indented source code to file " << inputSrcFile.fileName(); + } + + // Set the input file for the to be called indenter. + if (_inputFileParameter.trimmed() == "<" || _inputFileParameter == "stdin") + { + parameterInputFile = ""; + indentProcess.setStandardInputFile(inputSrcFile.fileName()); + } + else + { + parameterInputFile = " " + _inputFileParameter + _inputFileName + inputFileExtension; + } + + // Set the output file for the to be called indenter. + if (_outputFileParameter != "none" && _outputFileParameter != "stdout") + { + parameterOuputFile = " " + _outputFileParameter + _outputFileName + inputFileExtension; + } + +#ifdef Q_OS_WIN32 + // Paths may contain Unicode or other foreign characters. Windows commands line tools will + // receive als falsely encoded path string by TQProcess or they connot correctly handle + // the Unicode path on their own. + // Because of this the path gets converted to Windows short paths using the 8.3 notation. + + tqDebug() << __LINE__ << " " << __FUNCTION__ << + ": Temp dir before trying to convert it to short Windows path is" << _tempDirctoryStr; + + // At first convert the temp path to Windows like separators. + TQString tempDirctoryStrHelper = + TQDir::toNativeSeparators(_tempDirctoryStr).replace("\\", "\\\\"); + // Then convert the TQString to a WCHAR array and NULL terminate it. + WCHAR *tempDirctoryWindowsStr = new WCHAR[tempDirctoryStrHelper.length() + 1]; + tempDirctoryStrHelper.toWCharArray(tempDirctoryWindowsStr); + tempDirctoryWindowsStr[tempDirctoryStrHelper.length()] = (WCHAR)NULL; + + // Get the length of the resulting short path. + long length = 0; + TCHAR *buffer = NULL; + length = GetShortPathName((LPCTSTR)tempDirctoryWindowsStr, NULL, 0); + + // If the short path could be retrieved, create a correct sized buffer, store the + // short path in it and convert all back to TQString. + if (length != 0) + { + #ifdef UNICODE + buffer = new WCHAR[length]; + length = GetShortPathName((LPCTSTR)tempDirctoryWindowsStr, buffer, length); + tempDirctoryStrHelper = TQString::fromWCharArray(buffer); + #else + buffer = new TCHAR[length]; + length = GetShortPathName((LPCTSTR)tempDirctoryWindowsStr, buffer, length); + tempDirctoryStrHelper = buffer; + #endif + _tempDirctoryStr = TQDir::fromNativeSeparators(tempDirctoryStrHelper).replace("//", "/"); + delete[] buffer; + + // Check whether the short path still contains some kind of non ascii characters. + if (_tempDirctoryStr.length() != _tempDirctoryStr.toAscii().length()) + { + tqWarning() << __LINE__ << " " << __FUNCTION__ << + ": Shortened path still contains non ascii characters. Could cause some indenters not to work properly!"; + } + } + else + { + tqWarning() << __LINE__ << " " << __FUNCTION__ << + ": Couldn't retrieve a short version of the temporary path!"; + } + + tqDebug() << __LINE__ << " " << __FUNCTION__ << + ": Temp dir after trying to convert it to short Windows path is " << _tempDirctoryStr; + + delete[] tempDirctoryWindowsStr; +#endif + + // If the config file name is empty it is assumed that all parameters are sent via command line + // call + if (_globalConfigFilename.isEmpty()) + { + parameterParameterFile = " " + parameterString; + } + // if needed add the parameter to the indenter call string where the config file can be found + else if (_useCfgFileParameter != "none") + { + parameterParameterFile = " " + _useCfgFileParameter + "\"" + _tempDirctoryStr + "/" + + _globalConfigFilename + "\""; + } + + // Assemble indenter call string for parameters according to the set order. + if (_parameterOrder == "ipo") + { + indenterCompleteCallString = parameterInputFile + parameterParameterFile + parameterOuputFile; + } + else if (_parameterOrder == "pio") + { + indenterCompleteCallString = parameterParameterFile + parameterInputFile + parameterOuputFile; + } + else if (_parameterOrder == "poi") + { + indenterCompleteCallString = parameterParameterFile + parameterOuputFile + parameterInputFile; + } + else + { + indenterCompleteCallString = parameterInputFile + parameterOuputFile + parameterParameterFile; + } + + // If no indenter executable call string could be created before, show an error message. + if (_indenterExecutableCallString.isEmpty()) + { + _errorMessageDialog->showMessage(tr("No indenter executable"), tr( + "There exists no indenter executable with the name \"%1\" in the directory \"%2\" nor in the global environment.").arg( + _indenterFileName).arg(_indenterDirctoryStr)); + return sourceCode; + } + + // Generate the indenter call string either for win32 or other systems. + indenterCompleteCallString = _indenterExecutableCallString + indenterCompleteCallString; + + // errors and standard outputs from the process call are merged together + //indentProcess.setReadChannelMode(TQProcess::MergedChannels); + + // Set the directory where the indenter will be executed for the process' environment as PWD. + TQStringList env = indentProcess.environment(); + env << "PWD=" + TQFileInfo(_tempDirctoryStr).absoluteFilePath(); + indentProcess.setEnvironment(env); + + // Set the directory for the indenter execution + indentProcess.setWorkingDirectory(TQFileInfo(_tempDirctoryStr).absoluteFilePath()); + + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Will call the indenter in the directory " << + indentProcess.workingDirectory() << " using this commandline call: " << + indenterCompleteCallString; + + indentProcess.start(indenterCompleteCallString); + + processReturnString = ""; + bool calledProcessSuccessfully = indentProcess.waitForFinished(10000); + // test if there was an error during starting the process of the indenter + if (!calledProcessSuccessfully) + { + processReturnString = "<html><body>"; + processReturnString += tr("<b>Returned error message:</b> ") + indentProcess.errorString() + + "<br>"; + + switch (indentProcess.error()) + { + case TQProcess::FailedToStart: + { + processReturnString += tr("<b>Reason could be:</b> ") + + "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.<br>"; + break; + } + + case TQProcess::Crashed: + { + processReturnString += "The process crashed some time after starting successfully.<br>"; + break; + } + + case TQProcess::Timedout: + { + processReturnString += + "The called indenter did not response for over 10 seconds, so aborted its execution.<br>"; + break; + } + + case TQProcess::WriteError: + { + processReturnString += + "An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel.<br>"; + break; + } + + case TQProcess::ReadError: + { + processReturnString += + "An error occurred when attempting to read from the process. For example, the process may not be running.<br>"; + break; + } + + case TQProcess::UnknownError: + { + processReturnString += + "An unknown error occurred. This is the default return value of error().<br>"; + break; + } + + default: + { + break; + } + } + processReturnString += tr("<br><b>Callstring was:</b> ") + encodeToHTML( + indenterCompleteCallString); + processReturnString += tr("<br><br><b>Indenter output was:</b><pre>") + "<br>" + "(STDOUT):" + + encodeToHTML(indentProcess.readAllStandardOutput()) + "<br>" + "(STDERR):" + + encodeToHTML(indentProcess.readAllStandardError()) + "<br>" + "</pre></html></body>"; + tqWarning() << __LINE__ << " " << __FUNCTION__ << processReturnString; + TQApplication::restoreOverrideCursor(); + _errorMessageDialog->showMessage(tr("Error calling Indenter"), processReturnString); + } + + // If the indenter returned an error code != 0 show its output. + if (indentProcess.exitCode() != 0) + { + TQString exitCode; + exitCode.setNum(indentProcess.exitCode()); + processReturnString = tr("<b>Indenter returned with exit code:</b> ") + exitCode + "<br>" + tr( + "<b>Indent console output was:</b> ") + "<br>" + "(STDOUT):" + encodeToHTML( + indentProcess.readAllStandardOutput()) + "<br>" + "(STDERR):" + encodeToHTML( + indentProcess.readAllStandardError()) + "<br>" + tr("<br><b>Callstring was:</b> ") + + encodeToHTML(indenterCompleteCallString) + "</html></body>"; + tqWarning() << __LINE__ << " " << __FUNCTION__ << processReturnString; + TQApplication::restoreOverrideCursor(); + _errorMessageDialog->showMessage(tr("Indenter returned error"), processReturnString); + } + + // Only get the formatted source code, if calling the indenter did succeed. + if (calledProcessSuccessfully) + { + // If the indenter results are written to stdout, read them from there... + if (indentProcess.exitCode() == 0 && _outputFileParameter == "stdout") + { + formattedSourceCode = indentProcess.readAllStandardOutput(); + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Read indenter output from StdOut."; + } + // ... else read the output file generated by the indenter call. + else + { + TQFile outSrcFile(_tempDirctoryStr + "/" + _outputFileName + inputFileExtension); + if (outSrcFile.open(TQFile::ReadOnly | TQFile::Text)) + { + TQTextStream outSrcStrm(&outSrcFile); + outSrcStrm.setCodec(TQTextCodec::codecForName("UTF-8")); + formattedSourceCode = outSrcStrm.readAll(); + outSrcFile.close(); + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Read indenter output from file " << + outSrcFile.fileName(); + } + else + { + qCritical() << __LINE__ << " " << __FUNCTION__ << + ": Couldn't read indenter output from file " << outSrcFile.fileName(); + } + } + } + else + { + return sourceCode; + } + + // Delete the temporary input and output files. + TQFile::remove(_tempDirctoryStr + "/" + _outputFileName + inputFileExtension); + TQFile::remove(_tempDirctoryStr + "/" + _inputFileName + inputFileExtension); + + return formattedSourceCode; +} + +/*! + \brief Generates and returns a string with all parameters needed to call the indenter. + */ +TQString IndentHandler::getParameterString() +{ + TQString parameterString = ""; + + // generate parameter string for all boolean values + foreach(ParamBoolean pBoolean, _paramBooleans) + { + if (pBoolean.checkBox->isChecked()) + { + if (!pBoolean.trueString.isEmpty()) + { + parameterString += pBoolean.trueString + _cfgFileParameterEnding; + } + } + else + { + if (!pBoolean.falseString.isEmpty()) + { + parameterString += pBoolean.falseString + _cfgFileParameterEnding; + } + } + } + + // generate parameter string for all numeric values + foreach(ParamNumeric pNumeric, _paramNumerics) + { + if (pNumeric.valueEnabledChkBox->isChecked()) + { + parameterString += pNumeric.paramCallName + TQString::number(pNumeric.spinBox->value()) + + _cfgFileParameterEnding; + } + } + + // generate parameter string for all string values + foreach(ParamString pString, _paramStrings) + { + if (!pString.lineEdit->text().isEmpty() && pString.valueEnabledChkBox->isChecked()) + { + // Create parameter definition for each value devided by a | sign. + foreach(TQString paramValue, pString.lineEdit->text().split("|")) + { + parameterString += pString.paramCallName + paramValue + _cfgFileParameterEnding; + } + } + } + + // generate parameter string for all multiple choice values + foreach(ParamMultiple pMultiple, _paramMultiples) + { + if (pMultiple.valueEnabledChkBox->isChecked()) + { + parameterString += pMultiple.choicesStrings.at(pMultiple.comboBox->currentIndex()) + + _cfgFileParameterEnding; + } + } + + return parameterString; +} + +/*! + \brief Write settings for the indenter to a config file. + */ +void IndentHandler::saveConfigFile(TQString filePathName, TQString paramString) +{ + TQFile::remove(filePathName); + TQFile cfgFile(filePathName); + + cfgFile.open(TQFile::ReadWrite | TQFile::Text); + cfgFile.write(paramString.toAscii()); + cfgFile.close(); +} + +/*! + \brief Load the config file for the indenter and apply the settings made there. + */ +bool IndentHandler::loadConfigFile(TQString filePathName) +{ + TQFile cfgFile(filePathName); + int index; + int crPos; + int paramValue = 0; + TQString paramValueStr = ""; + TQString cfgFileData = ""; + + // If the to be loaded config file does not exist leave all values as they are and return false. + if (!cfgFile.exists()) + { + return false; + } + // else if the to be read config file exists, retrieve its whole content. + else + { + // Open the config file and read all data + cfgFile.open(TQFile::ReadOnly | TQFile::Text); + cfgFileData = cfgFile.readAll(); + cfgFile.close(); + } + + // Search for name of each boolean parameter and set its value if found. + foreach(ParamBoolean pBoolean, _paramBooleans) + { + // boolean value that will be assigned to the checkbox + bool paramValue = false; + + // first search for the longer parameter string + // the true parameter string is longer than the false string + if (pBoolean.trueString.length() > pBoolean.falseString.length()) + { + // search for the true string + index = cfgFileData.indexOf(pBoolean.trueString, 0, TQt::CaseInsensitive); + // if true string found set the parameter value to true + if (index != -1) + { + paramValue = true; + } + // if true string not found, search for false string + else + { + index = cfgFileData.indexOf(pBoolean.falseString, 0, TQt::CaseInsensitive); + // if false string found set the parameter value to false + if (index != -1) + { + paramValue = false; + } + // neither true nor false parameter found so use default value + else + { + paramValue = _indenterSettings->value(pBoolean.paramName + "/ValueDefault").toBool(); + } + } + } + // the false parameter string is longer than the true string + else + { + // search for the false string + index = cfgFileData.indexOf(pBoolean.falseString, 0, TQt::CaseInsensitive); + // if false string found set the parameter value to false + if (index != -1) + { + paramValue = false; + } + // if false string not found, search for true string + else + { + index = cfgFileData.indexOf(pBoolean.trueString, 0, TQt::CaseInsensitive); + // if true string found set the parameter value to true + if (index != -1) + { + paramValue = true; + } + // neither true nor false parameter found so use default value + else + { + paramValue = _indenterSettings->value(pBoolean.paramName + "/ValueDefault").toBool(); + } + } + } + pBoolean.checkBox->setChecked(paramValue); + } + + // Search for name of each numeric parameter and set the value found behind it. + foreach(ParamNumeric pNumeric, _paramNumerics) + { + index = cfgFileData.indexOf(pNumeric.paramCallName, 0, TQt::CaseInsensitive); + // parameter was found in config file + if (index != -1) + { + // set index after the parameter name, so in front of the number + index += pNumeric.paramCallName.length(); + + // Find the end of the parameter by searching for set config file parameter ending. Most of + // time this is a carriage return. + crPos = cfgFileData.indexOf(_cfgFileParameterEnding, index + 1); + + // get the number and convert it to int + TQString test = cfgFileData.mid(index, crPos - index); + paramValue = cfgFileData.mid(index, crPos - index).toInt(NULL); + + // disable the signal-slot connection. Otherwise signal is emmitted each time when value is + // set + TQObject::disconnect(pNumeric.spinBox, SIGNAL(valueChanged(int)), this, + SLOT(handleChangedIndenterSettings())); + pNumeric.spinBox->setValue(paramValue); + pNumeric.valueEnabledChkBox->setChecked(true); + TQObject::connect(pNumeric.spinBox, SIGNAL(valueChanged(int)), this, + SLOT(handleChangedIndenterSettings())); + } + // parameter was not found in config file + else + { + int defaultValue = _indenterSettings->value(pNumeric.paramName + "/ValueDefault").toInt(); + pNumeric.spinBox->setValue(defaultValue); + pNumeric.valueEnabledChkBox->setChecked(false); + } + } + + // Search for name of each string parameter and set it. + foreach(ParamString pString, _paramStrings) + { + paramValueStr = ""; + // The number of the found values for this parameter name. + int numberOfValues = 0; + index = cfgFileData.indexOf(pString.paramCallName, 0, TQt::CaseInsensitive); + // If parameter was found in config file + if (index != -1) + { + while (index != -1) + { + numberOfValues++; + + // Set index after the parameter name, so it points to the front of the string value. + index += pString.paramCallName.length(); + + // Find the end of the parameter by searching for set config file parameter ending. Most of + // time this is a carriage return. + crPos = cfgFileData.indexOf(_cfgFileParameterEnding, index + 1); + + // Get the string and remember it. + if (numberOfValues < 2) + { + paramValueStr = TQString(cfgFileData.mid(index, crPos - index)); + } + // If the same parameter has been set multiple times, concatenate the strings dvivided by a + // |. + else + { + paramValueStr = paramValueStr + "|" + TQString(cfgFileData.mid(index, crPos - index)); + } + + // Get next value for this setting, if one exists. + index = cfgFileData.indexOf(pString.paramCallName, crPos + 1, TQt::CaseInsensitive); + } + // Set the text for the line edit. + pString.lineEdit->setText(paramValueStr); + pString.valueEnabledChkBox->setChecked(true); + } + // Parameter was not found in config file + else + { + paramValueStr = _indenterSettings->value(pString.paramName + "/ValueDefault").toString(); + pString.lineEdit->setText(paramValueStr); + pString.valueEnabledChkBox->setChecked(false); + } + } + + // search for name of each multiple choice parameter and set it + foreach(ParamMultiple pMultiple, _paramMultiples) + { + int i = 0; + index = -1; + + // search for all parameter names of the multiple choice list + // if one is found, set it and leave the while loop + while (i < pMultiple.choicesStrings.count() && index == -1) + { + index = cfgFileData.indexOf(pMultiple.choicesStrings.at(i), 0, TQt::CaseInsensitive); + if (index != -1) + { + pMultiple.comboBox->setCurrentIndex(i); + pMultiple.valueEnabledChkBox->setChecked(true); + } + i++; + } + + // parameter was not set in config file, so use default value + if (index == -1) + { + int defaultValue = _indenterSettings->value(pMultiple.paramName + "/ValueDefault").toInt(); + pMultiple.comboBox->setCurrentIndex(defaultValue); + pMultiple.valueEnabledChkBox->setChecked(false); + } + } + + return true; +} + +/*! + \brief Sets all indenter parameters to their default values defined in the ini file. + */ +void IndentHandler::resetToDefaultValues() +{ + // Search for name of each boolean parameter and set its value if found. + foreach(ParamBoolean pBoolean, _paramBooleans) + { + // Boolean value that will be assigned to the checkbox. + bool defaultValue = _indenterSettings->value(pBoolean.paramName + "/ValueDefault").toBool(); + pBoolean.checkBox->setChecked(defaultValue); + } + + // Search for name of each numeric parameter and set the value found behind it. + foreach(ParamNumeric pNumeric, _paramNumerics) + { + int defaultValue = _indenterSettings->value(pNumeric.paramName + "/ValueDefault").toInt(); + pNumeric.spinBox->setValue(defaultValue); + pNumeric.valueEnabledChkBox->setChecked(_indenterSettings->value( + pNumeric.paramName + "/Enabled").toBool()); + } + + // Search for name of each string parameter and set it. + foreach(ParamString pString, _paramStrings) + { + TQString defaultValue = + _indenterSettings->value(pString.paramName + "/ValueDefault").toString(); + pString.lineEdit->setText(defaultValue); + pString.valueEnabledChkBox->setChecked(_indenterSettings->value( + pString.paramName + "/Enabled").toBool()); + } + + // Search for name of each multiple choice parameter and set it. + foreach(ParamMultiple pMultiple, _paramMultiples) + { + int defaultValue = _indenterSettings->value(pMultiple.paramName + "/ValueDefault").toInt(); + pMultiple.comboBox->setCurrentIndex(defaultValue); + pMultiple.valueEnabledChkBox->setChecked(_indenterSettings->value(pMultiple.paramName + + "/Enabled").toBool()); + } +} + +/*! + \brief Opens and parses the indenter ini file that is declared by \a iniFilePath. + */ +void IndentHandler::readIndentIniFile(TQString iniFilePath) +{ + Q_ASSERT_X(!iniFilePath.isEmpty(), "readIndentIniFile", "iniFilePath is empty"); + + // open the ini-file that contains all available indenter settings with their additional infos + _indenterSettings = new UiGuiIniFileParser(iniFilePath); + + TQStringList categories; + //TQString indenterGroupString = ""; + TQString paramToolTip = ""; + + // + // parse ini file indenter header + // + + _indenterName = _indenterSettings->value("header/indenterName").toString(); + _indenterFileName = _indenterSettings->value("header/indenterFileName").toString(); + _globalConfigFilename = _indenterSettings->value("header/configFilename").toString(); + _useCfgFileParameter = _indenterSettings->value("header/useCfgFileParameter").toString(); + _cfgFileParameterEnding = _indenterSettings->value("header/cfgFileParameterEnding").toString(); + if (_cfgFileParameterEnding == "cr") + { + _cfgFileParameterEnding = "\n"; + } + _indenterShowHelpParameter = _indenterSettings->value("header/showHelpParameter").toString(); + + if (_indenterFileName.isEmpty()) + { + _errorMessageDialog->showMessage(tr("Indenter ini file header error"), tr( + "The loaded indenter ini file \"%1\"has a faulty header. At least the indenters file name is not set.").arg( + iniFilePath)); + } + + // Read the parameter order. Possible values are (p=parameter[file] i=inputfile o=outputfile) + // pio, ipo, iop + _parameterOrder = _indenterSettings->value("header/parameterOrder", "pio").toString(); + _inputFileParameter = _indenterSettings->value("header/inputFileParameter").toString(); + _inputFileName = _indenterSettings->value("header/inputFileName").toString(); + _outputFileParameter = _indenterSettings->value("header/outputFileParameter").toString(); + _outputFileName = _indenterSettings->value("header/outputFileName").toString(); + _fileTypes = _indenterSettings->value("header/fileTypes").toString(); + _fileTypes.replace('|', " "); + + // read the categories names which are separated by "|" + TQString categoriesStr = _indenterSettings->value("header/categories").toString(); + categories = categoriesStr.split("|"); + // Assure that the category list is never empty. At least contain a "general" section. + if (categories.isEmpty()) + { + categories.append("General"); + } + + IndenterParameterCategoryPage categoryPage; + + // create a page for each category and store its references in a toolboxpage-array + foreach(TQString category, categories) + { + categoryPage.widget = new TQWidget(); + categoryPage.widget->setObjectName(category); + categoryPage.widget->setSizePolicy(TQSizePolicy::MinimumExpanding, + TQSizePolicy::MinimumExpanding); + categoryPage.vboxLayout = new TQVBoxLayout(categoryPage.widget); + categoryPage.vboxLayout->setSpacing(6); + categoryPage.vboxLayout->setMargin(9); + categoryPage.vboxLayout->setObjectName(category); + _indenterParameterCategoryPages.append(categoryPage); + _indenterParameterCategoriesToolBox->addItem(categoryPage.widget, category); + } + + // + // parse ini file indenter parameters + // + + // read all possible parameters written in brackets [] + _indenterParameters = _indenterSettings->childGroups(); + + // read each parameter to create the corresponding input field + foreach(TQString indenterParameter, _indenterParameters) + { + // if it is not the indent header definition read the parameter and add it to + // the corresponding category toolbox page + if (indenterParameter != "header") + { + // read to which category the parameter belongs + int category = _indenterSettings->value(indenterParameter + "/Category").toInt(); + // Assure that the category number is never greater than the available categories. + if (category > _indenterParameterCategoryPages.size() - 1) + { + category = _indenterParameterCategoryPages.size() - 1; + } + // read which type of input field the parameter needs + TQString editType = _indenterSettings->value(indenterParameter + "/EditorType").toString(); + + // edit type is numeric so create a spinbox with label + if (editType == "numeric") + { + // read the parameter name as it is used at the command line or in its config file + TQString parameterCallName = + _indenterSettings->value(indenterParameter + "/CallName").toString(); + + // create checkbox which enables or disables the parameter + TQCheckBox *chkBox = new TQCheckBox(_indenterParameterCategoryPages.at(category).widget); + chkBox->setChecked(_indenterSettings->value(indenterParameter + "/Enabled").toBool()); + chkBox->setToolTip( + "Enables/disables the parameter. If disabled the indenters default value will be used."); + chkBox->setSizePolicy(TQSizePolicy::Fixed, TQSizePolicy::Fixed); + int left, top, right, bottom; + chkBox->getContentsMargins(&left, &top, &right, &bottom); + chkBox->setContentsMargins(left, top, 0, bottom); + + // create the spinbox + TQSpinBox *spinBox = new TQSpinBox(_indenterParameterCategoryPages.at(category).widget); + paramToolTip = _indenterSettings->value(indenterParameter + "/Description").toString(); + spinBox->setToolTip(paramToolTip); + spinBox->setMaximumWidth(50); + spinBox->setMinimumWidth(50); + if (_mainWindow != NULL) + { + spinBox->installEventFilter(_mainWindow); + } + if (_indenterSettings->value(indenterParameter + "/MinVal").toString() != "") + { + spinBox->setMinimum(_indenterSettings->value(indenterParameter + "/MinVal").toInt()); + } + else + { + spinBox->setMinimum(0); + } + if (_indenterSettings->value(indenterParameter + "/MaxVal").toString() != "") + { + spinBox->setMaximum(_indenterSettings->value(indenterParameter + "/MaxVal").toInt()); + } + else + { + spinBox->setMaximum(2000); + } + + // create the label + TQLabel *label = new TQLabel(_indenterParameterCategoryPages.at(category).widget); + label->setText(indenterParameter); + label->setBuddy(spinBox); + label->setToolTip(paramToolTip); + if (_mainWindow != NULL) + { + label->installEventFilter(_mainWindow); + } + + // put all into a layout and add it to the toolbox page + TQHBoxLayout *hboxLayout = new TQHBoxLayout(); + hboxLayout->addWidget(chkBox); + hboxLayout->addWidget(spinBox); + hboxLayout->addWidget(label); + _indenterParameterCategoryPages.at(category).vboxLayout->addLayout(hboxLayout); + + // remember parameter name and reference to its spinbox + ParamNumeric paramNumeric; + paramNumeric.paramName = indenterParameter; + paramNumeric.paramCallName = parameterCallName; + paramNumeric.spinBox = spinBox; + paramNumeric.label = label; + paramNumeric.valueEnabledChkBox = chkBox; + paramNumeric.spinBox->setValue(_indenterSettings->value(paramNumeric.paramName + + "/ValueDefault").toInt()); + _paramNumerics.append(paramNumeric); + + TQObject::connect(spinBox, SIGNAL(valueChanged(int)), this, + SLOT(handleChangedIndenterSettings())); + TQObject::connect(chkBox, SIGNAL(clicked()), this, SLOT(handleChangedIndenterSettings())); +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + connect(spinBox, SIGNAL(valueChanged(int)), this, SLOT(updateDrawing())); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS + } + // edit type is boolean so create a checkbox + else if (editType == "boolean") + { + // create the checkbox, make its settings and add it to the toolbox page + TQCheckBox *chkBox = new TQCheckBox(_indenterParameterCategoryPages.at(category).widget); + chkBox->setText(indenterParameter); + paramToolTip = _indenterSettings->value(indenterParameter + "/Description").toString(); + chkBox->setToolTip(paramToolTip); + if (_mainWindow != NULL) + { + chkBox->installEventFilter(_mainWindow); + } + _indenterParameterCategoryPages.at(category).vboxLayout->addWidget(chkBox); + + // remember parameter name and reference to its checkbox + ParamBoolean paramBoolean; + paramBoolean.paramName = indenterParameter; + paramBoolean.checkBox = chkBox; + TQStringList trueFalseStrings = + _indenterSettings->value(indenterParameter + "/TrueFalse").toString().split("|"); + paramBoolean.trueString = trueFalseStrings.at(0); + paramBoolean.falseString = trueFalseStrings.at(1); + paramBoolean.checkBox->setChecked(_indenterSettings->value(paramBoolean.paramName + + "/ValueDefault").toBool()); + _paramBooleans.append(paramBoolean); + + TQObject::connect(chkBox, SIGNAL(clicked()), this, SLOT(handleChangedIndenterSettings())); + } + // edit type is numeric so create a line edit with label + else if (editType == "string") + { + // read the parameter name as it is used at the command line or in its config file + TQString parameterCallName = + _indenterSettings->value(indenterParameter + "/CallName").toString(); + + // create check box which enables or disables the parameter + TQCheckBox *chkBox = new TQCheckBox(_indenterParameterCategoryPages.at(category).widget); + chkBox->setChecked(_indenterSettings->value(indenterParameter + "/Enabled").toBool()); + chkBox->setToolTip( + "Enables/disables the parameter. If disabled the indenters default value will be used."); + chkBox->setSizePolicy(TQSizePolicy::Fixed, TQSizePolicy::Fixed); + int left, top, right, bottom; + chkBox->getContentsMargins(&left, &top, &right, &bottom); + chkBox->setContentsMargins(left, top, 0, bottom); + + // create the line edit + TQLineEdit *lineEdit = new TQLineEdit(_indenterParameterCategoryPages.at(category).widget); + paramToolTip = _indenterSettings->value(indenterParameter + "/Description").toString(); + lineEdit->setToolTip(paramToolTip); + lineEdit->setMaximumWidth(50); + lineEdit->setMinimumWidth(50); + if (_mainWindow != NULL) + { + lineEdit->installEventFilter(_mainWindow); + } + + // create the label + TQLabel *label = new TQLabel(_indenterParameterCategoryPages.at(category).widget); + label->setText(indenterParameter); + label->setBuddy(lineEdit); + label->setSizePolicy(TQSizePolicy::MinimumExpanding, TQSizePolicy::Preferred); + label->setToolTip(paramToolTip); + if (_mainWindow != NULL) + { + label->installEventFilter(_mainWindow); + } + + // put all into a layout and add it to the toolbox page + TQHBoxLayout *hboxLayout = new TQHBoxLayout(); + hboxLayout->addWidget(chkBox); + hboxLayout->addWidget(lineEdit); + hboxLayout->addWidget(label); + _indenterParameterCategoryPages.at(category).vboxLayout->addLayout(hboxLayout); + + // remember parameter name and reference to its line edit + ParamString paramString; + paramString.paramName = indenterParameter; + paramString.paramCallName = parameterCallName; + paramString.lineEdit = lineEdit; + paramString.label = label; + paramString.valueEnabledChkBox = chkBox; + paramString.lineEdit->setText(_indenterSettings->value(paramString.paramName + + "/ValueDefault").toString()); + _paramStrings.append(paramString); + + TQObject::connect(lineEdit, SIGNAL(editingFinished()), this, + SLOT(handleChangedIndenterSettings())); + TQObject::connect(chkBox, SIGNAL(clicked()), this, SLOT(handleChangedIndenterSettings())); +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + connect(lineEdit, SIGNAL(textChanged(const TQString)), this, SLOT(updateDrawing())); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS + } + // edit type is multiple so create a combobox with label + else if (editType == "multiple") + { + // read the parameter name as it is used at the command line or in its config file + TQString parameterCallName = + _indenterSettings->value(indenterParameter + "/CallName").toString(); + + // create checkbox which enables or disables the parameter + TQCheckBox *chkBox = new TQCheckBox(_indenterParameterCategoryPages.at(category).widget); + chkBox->setChecked(_indenterSettings->value(indenterParameter + "/Enabled").toBool()); + chkBox->setToolTip( + "Enables/disables the parameter. If disabled the indenters default value will be used."); + chkBox->setSizePolicy(TQSizePolicy::Fixed, TQSizePolicy::Fixed); + int left, top, right, bottom; + chkBox->getContentsMargins(&left, &top, &right, &bottom); + chkBox->setContentsMargins(left, top, 0, bottom); + + // create the combo box + TQComboBox *comboBox = new TQComboBox(_indenterParameterCategoryPages.at( + category).widget); + TQStringList choicesStrings = + _indenterSettings->value(indenterParameter + "/Choices").toString().split("|"); + TQStringList choicesStringsReadable = _indenterSettings->value( + indenterParameter + "/ChoicesReadable").toString().split("|", TQString::SkipEmptyParts); + if (choicesStringsReadable.isEmpty()) + { + comboBox->addItems(choicesStrings); + } + else + { + comboBox->addItems(choicesStringsReadable); + } + paramToolTip = _indenterSettings->value(indenterParameter + "/Description").toString(); + comboBox->setToolTip(paramToolTip); + if (_mainWindow != NULL) + { + comboBox->installEventFilter(_mainWindow); + } + + // put all into a layout and add it to the toolbox page + TQHBoxLayout *hboxLayout = new TQHBoxLayout(); + hboxLayout->addWidget(chkBox); + hboxLayout->addWidget(comboBox); + _indenterParameterCategoryPages.at(category).vboxLayout->addLayout(hboxLayout); + + // remember parameter name and reference to its lineedit + ParamMultiple paramMultiple; + paramMultiple.paramName = indenterParameter; + paramMultiple.paramCallName = parameterCallName; + paramMultiple.comboBox = comboBox; + paramMultiple.choicesStrings = choicesStrings; + paramMultiple.choicesStringsReadable = choicesStringsReadable; + paramMultiple.valueEnabledChkBox = chkBox; + paramMultiple.comboBox->setCurrentIndex(_indenterSettings->value(paramMultiple.paramName + + "/ValueDefault").toInt()); + _paramMultiples.append(paramMultiple); + + TQObject::connect(comboBox, SIGNAL(activated(int)), this, + SLOT(handleChangedIndenterSettings())); + TQObject::connect(chkBox, SIGNAL(clicked()), this, SLOT(handleChangedIndenterSettings())); +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + connect(comboBox, SIGNAL(activated(int)), this, SLOT(updateDrawing())); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS + } + } + } + + // put a spacer at each page end + foreach(IndenterParameterCategoryPage categoryPage, _indenterParameterCategoryPages) + { + categoryPage.vboxLayout->addStretch(); + } +} + +/*! + \brief Searches and returns all indenters a configuration file is found for. + + Opens all uigui ini files found in the list \a _indenterIniFileList, opens each ini file + and reads the there defined real name of the indenter. These names are being returned as TQStringList. + */ +TQStringList IndentHandler::getAvailableIndenters() +{ + TQStringList indenterNamesList; + + // Loop for every existing uigui ini file + foreach(TQString indenterIniFile, _indenterIniFileList) + { + // Open the ini file and search for the indenter name + TQFile file(_indenterDirctoryStr + "/" + indenterIniFile); + if (file.open(TQIODevice::ReadOnly | TQIODevice::Text)) + { + int index = -1; + TQByteArray line; + // Search for the string "indenterName=" and get the following string until line end. + while (index == -1 && !file.atEnd()) + { + line = file.readLine(); + index = line.indexOf("indenterName=", 0); + } + + if (index == 0) + { + line = line.remove(0, 13); + indenterNamesList << line.trimmed(); + } + } + } + return indenterNamesList; +} + +/*! + \brief Deletes all elements in the toolbox and initializes the indenter selected by \a indenterID. + */ +void IndentHandler::setIndenter(int indenterID) +{ + TQApplication::setOverrideCursor(TQt::WaitCursor); + +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + disconnect(_indenterParameterCategoriesToolBox, SIGNAL(currentChanged(int)), this, + SLOT(updateDrawing())); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS + + // Generate the parameter string that will be saved to the indenters config file. + TQString parameterString = getParameterString(); + if (!_indenterFileName.isEmpty()) + { + saveConfigFile(_settingsDirctoryStr + "/" + _indenterFileName + ".cfg", parameterString); + } + + // Take care if the selected indenterID is smaller or greater than the number of existing + // indenters + if (indenterID < 0) + { + indenterID = 0; + } + if (indenterID >= _indenterIniFileList.count()) + { + indenterID = _indenterIniFileList.count() - 1; + } + + // remove all pages from the toolbox + for (int i = 0; i < _indenterParameterCategoriesToolBox->count(); i++) + { + _indenterParameterCategoriesToolBox->removeItem(i); + } + + // delete all toolbox pages and by this its children + foreach(IndenterParameterCategoryPage categoryPage, _indenterParameterCategoryPages) + { + delete categoryPage.widget; + } + + // empty all lists, which stored infos for the toolbox pages and its widgets + _indenterParameterCategoryPages.clear(); + _paramStrings.clear(); + _paramNumerics.clear(); + _paramBooleans.clear(); + _paramMultiples.clear(); + delete _indenterSettings; + +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + TQWidget dummyWidget; + _indenterParameterCategoriesToolBox->addItem(&dummyWidget, "dummyText"); +#endif + + readIndentIniFile(_indenterDirctoryStr + "/" + _indenterIniFileList.at(indenterID)); + + // Find out how the indenter can be executed. + createIndenterCallString(); + + // Load the users last settings made for this indenter. + loadConfigFile(_settingsDirctoryStr + "/" + _indenterFileName + ".cfg"); + + handleChangedIndenterSettings(); + + TQApplication::restoreOverrideCursor(); + +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + connect(_indenterParameterCategoriesToolBox, SIGNAL(currentChanged(int)), this, + SLOT(updateDrawing())); + _indenterParameterCategoriesToolBox->removeItem(_indenterParameterCategoriesToolBox->indexOf(& + dummyWidget)); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS +} + +/*! + \brief Returns a string containing by the indenter supported file types/extensions divided by a space. + */ +TQString IndentHandler::getPossibleIndenterFileExtensions() +{ + return _fileTypes; +} + +/*! + \brief Returns the path and filename of the current indenter config file. + */ +TQString IndentHandler::getIndenterCfgFile() +{ + TQFileInfo fileInfo(_indenterDirctoryStr + "/" + _globalConfigFilename); + return fileInfo.absoluteFilePath(); +} + +/*! + \brief Tries to create a call path string for the indenter executable. If successful returns true. + */ +bool IndentHandler::createIndenterCallString() +{ + TQProcess indentProcess; + + if (_indenterFileName.isEmpty()) + { + return false; + } + + // First try to call the indenter inside of the data dir, using some suffix + // ------------------------------------------------------------------------ + + // Set the directory for the indenter execution + indentProcess.setWorkingDirectory(TQFileInfo(_indenterDirctoryStr).absoluteFilePath()); + + foreach(TQString suffix, TQStringList() << "" << ".exe" << ".bat" << ".com" << ".sh") + { + _indenterExecutableSuffix = suffix; + _indenterExecutableCallString = TQFileInfo(_indenterDirctoryStr).absoluteFilePath() + "/" + + _indenterFileName; + _indenterExecutableCallString += suffix; + + // Only try to call the indenter, if the file exists. + if (TQFile::exists(_indenterExecutableCallString)) + { + // Only try to call the indenter directly if it is no php file + if (TQFileInfo(_indenterExecutableCallString).suffix().toLower() != "php") + { + indentProcess.start( + "\"" + _indenterExecutableCallString + +"\" " + _indenterShowHelpParameter); + if (indentProcess.waitForFinished(2000)) + { + _indenterExecutableCallString = "\"" + _indenterExecutableCallString + "\""; + return true; + } + else if (indentProcess.error() == TQProcess::Timedout) + { + _indenterExecutableCallString = "\"" + _indenterExecutableCallString + "\""; + return true; + } + } + + // Test for needed interpreters + // ---------------------------- + // If the file could not be executed, try to find a shebang at its start or test if its a php + // file. + TQString interpreterName = ""; + TQFile indenterExecutable(_indenterExecutableCallString); + + // If indenter executable file has .php as suffix, use php as default interpreter + if (TQFileInfo(_indenterExecutableCallString).suffix().toLower() == "php") + { + interpreterName = "php -f"; + } + // Else try to open the file and read the shebang. + else if (indenterExecutable.open(TQFile::ReadOnly)) + { + // Read the first line of the file. + TQTextStream indenterExecutableContent(&indenterExecutable); + TQString firstLineOfIndenterExe = indenterExecutableContent.readLine(75); + indenterExecutable.close(); + + // If the initial shebang is found, read the named intepreter. e.g. perl + if (firstLineOfIndenterExe.startsWith("#!")) + { + // Get the rightmost word. by splitting the string into only full words. + interpreterName = firstLineOfIndenterExe.split("/").last(); + } + } + + // Try to call the interpreter, if it exists. + if (!interpreterName.isEmpty()) + { + _indenterExecutableCallString = interpreterName + " \"" + _indenterExecutableCallString + + "\""; + indentProcess.start(interpreterName + " -h"); + if (indentProcess.waitForFinished(2000)) + { + return true; + } + else if (indentProcess.error() == TQProcess::Timedout) + { + return true; + } + // now we know an interpreter is needed but it could not be called, so inform the user. + else + { + _errorMessageDialog->showMessage(tr("Interpreter needed"), tr( + "To use the selected indenter the program \"%1\" needs to be available in the global environment. You should add an entry to your path settings.").arg( + interpreterName)); + return true; + } + } + } + } + + // If unsuccessful try if the indenter executable is a JavaScript file + // ------------------------------------------------------------------- + _indenterExecutableSuffix = ".js"; + _indenterExecutableCallString = TQFileInfo(_indenterDirctoryStr).absoluteFilePath() + "/" + + _indenterFileName; + _indenterExecutableCallString += _indenterExecutableSuffix; + if (TQFile::exists(_indenterExecutableCallString)) + { + return true; + } + + // If unsuccessful try to call the indenter global, using some suffix + // ------------------------------------------------------------------ + foreach(TQString suffix, TQStringList() << "" << ".exe" << ".bat" << ".com" << ".sh") + { + _indenterExecutableSuffix = suffix; + _indenterExecutableCallString = _indenterFileName + suffix; + indentProcess.start(_indenterExecutableCallString + " " + _indenterShowHelpParameter); + if (indentProcess.waitForFinished(2000)) + { + return true; + } + else if (indentProcess.error() == TQProcess::Timedout) + { + return true; + } + } + + // If even globally calling the indenter fails, try calling .com and .exe via wine + // ------------------------------------------------------------------------------- + _indenterExecutableCallString = "\"" + TQFileInfo(_indenterDirctoryStr).absoluteFilePath() + "/" + + _indenterFileName; + + foreach(TQString suffix, TQStringList() << ".exe" << ".com") + { + _indenterExecutableSuffix = suffix; + if (TQFile::exists(_indenterDirctoryStr + "/" + _indenterFileName + suffix)) + { + TQProcess wineTestProcess; + wineTestProcess.start("wine --version"); + // if the process of wine was not callable assume that wine is not installed + if (!wineTestProcess.waitForFinished(2000)) + { + _errorMessageDialog->showMessage(tr("wine not installed"), tr( + "There exists only a win32 executable of the indenter and wine does not seem to be installed. Please install wine to be able to run the indenter.")); + _indenterExecutableCallString = ""; + return false; + } + else + { + _indenterExecutableCallString = "\"" + + TQFileInfo(_indenterDirctoryStr).absoluteFilePath() + "/"; + _indenterExecutableCallString += _indenterFileName + suffix + "\""; + _indenterExecutableCallString = "wine " + _indenterExecutableCallString; + + return true; + } + } + } + + _indenterExecutableCallString = ""; + _indenterExecutableSuffix = ""; + return false; +} + +/*! + \brief Returns a string that points to where the indenters manual can be found. + */ +TQString IndentHandler::getManual() +{ + if (_indenterSettings != NULL) + { + return _indenterSettings->value("header/manual").toString(); + } + else + { + return ""; + } +} + +/*! + \brief This slot gets the reference to the indenters manual and opens it. + */ +void IndentHandler::showIndenterManual() +{ + TQString manualReference = getManual(); + TQDesktopServices::openUrl(manualReference); +} + +/*! + \brief Can be called to update all widgets text to the currently selected language. + */ +void IndentHandler::retranslateUi() +{ + _indenterSelectionCombobox->setToolTip(tr( + "<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\" white-space: pre-wrap; font-family:MS Shell Dlg; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;\"><p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Shows the currently chosen indenters name and lets you choose other available indenters</p></body></html>")); + _indenterParameterHelpButton->setToolTip(tr( + "Brings you to the online manual of the currently selected indenter, where you can get further help on the possible parameters.")); + + _actionLoadIndenterConfigFile->setText(TQApplication::translate("IndentHandler", + "Load Indenter Config File", 0, TQApplication::UnicodeUTF8)); + _actionLoadIndenterConfigFile->setStatusTip(TQApplication::translate("IndentHandler", + "Opens a file dialog to load the original config file of the indenter.", 0, + TQApplication::UnicodeUTF8)); + _actionLoadIndenterConfigFile->setShortcut(TQApplication::translate("IndentHandler", "Alt+O", 0, + TQApplication::UnicodeUTF8)); + + _actionSaveIndenterConfigFile->setText(TQApplication::translate("IndentHandler", + "Save Indenter Config File", 0, TQApplication::UnicodeUTF8)); + _actionSaveIndenterConfigFile->setStatusTip(TQApplication::translate("IndentHandler", + "Opens a dialog to save the current indenter configuration to a file.", 0, + TQApplication::UnicodeUTF8)); + _actionSaveIndenterConfigFile->setShortcut(TQApplication::translate("IndentHandler", "Alt+S", 0, + TQApplication::UnicodeUTF8)); + + _actionCreateShellScript->setText(TQApplication::translate("IndentHandler", + "Create Indenter Call Shell Script", 0, TQApplication::UnicodeUTF8)); + _actionCreateShellScript->setToolTip(TQApplication::translate("IndentHandler", + "Create a shell script that calls the current selected indenter for formatting an as parameter given file with the current indent settings.", + 0, TQApplication::UnicodeUTF8)); + _actionCreateShellScript->setStatusTip(TQApplication::translate("IndentHandler", + "Create a shell script that calls the current selected indenter for formatting an as parameter given file with the current indent settings.", + 0, TQApplication::UnicodeUTF8)); + + _actionResetIndenterParameters->setText(TQApplication::translate("IndentHandler", + "Reset indenter parameters", 0, TQApplication::UnicodeUTF8)); + _actionResetIndenterParameters->setToolTip(TQApplication::translate("IndentHandler", + "Resets all indenter parameters to the default values.", 0, TQApplication::UnicodeUTF8)); + _actionResetIndenterParameters->setStatusTip(TQApplication::translate("IndentHandler", + "Resets all indenter parameters to the default values.", 0, TQApplication::UnicodeUTF8)); +} + +/*! + \brief Returns the name of the currently selected indenter. + */ +TQString IndentHandler::getCurrentIndenterName() +{ + TQString currentIndenterName = _indenterSelectionCombobox->currentText(); + + // Remove the supported programming languages from indenters name, which are set in braces. + if (currentIndenterName.indexOf("(") > 0) + { + // Using index-1 to also leave out the blank before the brace. + currentIndenterName = currentIndenterName.left(currentIndenterName.indexOf("(") - 1); + } + + return currentIndenterName; +} + +/*! + \brief Shows a file open dialog to open an existing config file for the currently selected indenter. + + If the file was successfully opened the indent handler is called to load the settings and update itself. +*/ +void IndentHandler::openConfigFileDialog() +{ + TQString configFilePath; + + configFilePath = TQFileDialog::getOpenFileName(NULL, tr( + "Choose indenter config file"), getIndenterCfgFile(), "All files (*.*)"); + + if (configFilePath != "") + { + // If the config file was loaded successfully, inform any who is interested about it. + if (loadConfigFile(configFilePath)) + { + handleChangedIndenterSettings(); + } + } +} + +/*! + \brief Calls the indenter config file save as dialog to save the config file under a chosen name. + + If the file already exists and it should be overwritten, a warning is shown before. +*/ +void IndentHandler::saveasIndentCfgFileDialog() +{ + TQString fileExtensions = tr("All files") + " (*.*)"; + + //TQString openedSourceFileContent = openFileDialog( tr("Choose source code file"), "./", + // fileExtensions ); + TQString fileName = TQFileDialog::getSaveFileName(this, tr( + "Save indent config file"), getIndenterCfgFile(), fileExtensions); + + if (fileName != "") + { + TQFile::remove(fileName); + TQFile outCfgFile(fileName); + outCfgFile.open(TQFile::ReadWrite | TQFile::Text); + outCfgFile.write(getParameterString().toAscii()); + outCfgFile.close(); + } +} + +/*! + \brief Invokes the indenter to create a shell script. + + Lets the indenter create a shell script for calling the indenter out of any + other application and open a save dialog for saving the shell script. +*/ +void IndentHandler::createIndenterCallShellScript() +{ + TQString shellScriptExtension; +#if defined (Q_OS_WIN32) + shellScriptExtension = "bat"; +#else + shellScriptExtension = "sh"; +#endif + + TQString fileExtensions = tr("Shell Script") + " (*." + shellScriptExtension + ");;" + tr( + "All files") + " (*.*)"; + + TQString currentIndenterName = getCurrentIndenterName(); + currentIndenterName = currentIndenterName.replace(" ", "_"); + + TQString shellScriptFileName = TQFileDialog::getSaveFileName(this, tr( + "Save shell script"), "call_" + currentIndenterName + "." + shellScriptExtension, + fileExtensions); + + // Saving has been canceled if the filename is empty + if (shellScriptFileName.isEmpty()) + { + return; + } + + // Delete any old file, write the new contents and set executable permissions. + TQFile::remove(shellScriptFileName); + TQFile outSrcFile(shellScriptFileName); + if (outSrcFile.open(TQFile::ReadWrite | TQFile::Text)) + { + TQString shellScriptConfigFilename = TQFileInfo(shellScriptFileName).baseName() + "." + + TQFileInfo(_globalConfigFilename).suffix(); + + // Get the content of the shell/batch script. + TQString indenterCallShellScript = generateShellScript(shellScriptConfigFilename); + + // Replace placeholder for script name in script template. + indenterCallShellScript = indenterCallShellScript.replace("__INDENTERCALLSTRINGSCRIPTNAME__", TQFileInfo( + shellScriptFileName).fileName()); + + outSrcFile.write(indenterCallShellScript.toAscii()); +#if !defined (Q_OS_WIN32) + // For none Windows systems set the files executable flag + outSrcFile.setPermissions( + outSrcFile.permissions() | TQFile::ExeOwner | TQFile::ExeUser | TQFile::ExeGroup); +#endif + outSrcFile.close(); + + // Save the indenter config file to the same directory, where the shell srcipt was saved to, + // because the script will reference it there via "./". + if (!_globalConfigFilename.isEmpty()) + { + saveConfigFile(TQFileInfo( + shellScriptFileName).path() + "/" + shellScriptConfigFilename, + getParameterString()); + } + } +} + +/*! + \brief Resets all parameters to the indenters default values as they are specified in the uigui ini file + but asks the user whether to do it really. + */ +void IndentHandler::resetIndenterParameter() +{ + int messageBoxAnswer = TQMessageBox::question(this, tr("Really reset parameters?"), tr( + "Do you really want to reset the indenter parameters to the default values?"), + TQMessageBox::Yes | TQMessageBox::Abort); + if (messageBoxAnswer == TQMessageBox::Yes) + { + resetToDefaultValues(); + } +} + +/*! + \brief Catch some events and let some other be handled by the super class. + + Is needed for use as Notepad++ plugin. + */ +bool IndentHandler::event(TQEvent *event) +{ + if (event->type() == TQEvent::WindowActivate) + { + event->accept(); + return true; + } + else if (event->type() == TQEvent::WindowDeactivate) + { + event->accept(); + return true; + } + else + { + event->ignore(); + return TQWidget::event(event); + } +} + +/*! + \brief Sets the function pointer \a _parameterChangedCallback to the given callback + function \a paramChangedCallback. + + Is needed for use as Notepad++ plugin. + */ +void IndentHandler::setParameterChangedCallback(void (*paramChangedCallback)(void)) +{ + _parameterChangedCallback = paramChangedCallback; +} + +/*! + \brief Emits the \a indenterSettingsChanged signal and if set executes the \a _parameterChangedCallback function. + + Is needed for use as Notepad++ plugin. + */ +void IndentHandler::handleChangedIndenterSettings() +{ + emit(indenterSettingsChanged()); + + if (_parameterChangedCallback != NULL) + { + _parameterChangedCallback(); + } +} + +/*! + \brief Sets a callback function that shall be called, when the this indenter parameter window gets closed. + + Is needed for use as Notepad++ plugin. + */ +void IndentHandler::setWindowClosedCallback(void (*winClosedCallback)(void)) +{ + _windowClosedCallback = winClosedCallback; +} + +/*! + \brief Is called on this indenter parameter window close and if set calls the function \a _windowClosedCallback. + + Is needed for use as Notepad++ plugin. + */ +void IndentHandler::closeEvent(TQCloseEvent *event) +{ + if (_windowClosedCallback != NULL) + { + _windowClosedCallback(); + } + event->accept(); +} + +/*! + \brief Returns the id (list index) of the currently selected indenter. + */ +int IndentHandler::getIndenterId() +{ + return _indenterSelectionCombobox->currentIndex(); +} + +void IndentHandler::updateDrawing() +{ +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + if (isVisible()) + { + TQRect savedGeometry = geometry(); + setGeometry(savedGeometry.adjusted(0, 0, 0, 1)); + repaint(); + setGeometry(savedGeometry); + } +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS +} + +void IndentHandler::wheelEvent(TQWheelEvent *event) +{ + UNUSED_PARAMETER_WARNING_AVOID(event); +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + TQWidget::wheelEvent(event); + updateDrawing(); +#endif // UNIVERSALINDENTGUI_NPP_EXPORTS +} + +/*! + \brief Converts characters < > and & in the \a text to HTML codes < > and &. + */ + +//TODO: This function should go into a string helper/tool class/file. +TQString IndentHandler::encodeToHTML(const TQString &text) +{ + TQString htmlText = text; + htmlText.replace("&", "&"); + htmlText.replace("<", "<"); + htmlText.replace(">", ">"); + htmlText.replace('"', """); + htmlText.replace("'", "'"); + htmlText.replace("^", "ˆ"); + htmlText.replace("~", "˜"); + htmlText.replace("€", "€"); + htmlText.replace("©", "©"); + return htmlText; +} diff --git a/src/__TODO/IndentHandler.h b/src/__TODO/IndentHandler.h new file mode 100644 index 0000000..f576518 --- /dev/null +++ b/src/__TODO/IndentHandler.h @@ -0,0 +1,195 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef INDENTHANDLER_H +#define INDENTHANDLER_H + +#include <tntqwidget.h> + +class UiGuiErrorMessage; +class UiGuiIniFileParser; + +class TQMenu; +class TQVBoxLayout; +class TQLabel; +class TQSpinBox; +class TQComboBox; +class TQCheckBox; +class TQLineEdit; +class TQToolButton; +class TQToolBox; + + +class IndentHandler : public TQWidget +{ + Q_OBJECT + + public: + IndentHandler(int indenterID, TQWidget *mainWindow = NULL, TQWidget *parent = NULL); + ~IndentHandler(); + + TQString generateShellScript(const TQString &configFilename); + TQString callIndenter(TQString sourceCode, TQString inputFileExtension); + bool loadConfigFile(TQString filePathName); + void resetToDefaultValues(); + TQStringList getAvailableIndenters(); + TQString getPossibleIndenterFileExtensions(); + TQString getParameterString(); + TQString getIndenterCfgFile(); + TQString getManual(); + void retranslateUi(); + TQString getCurrentIndenterName(); + TQMenu* getIndenterMenu(); + TQList<TQAction*> getIndenterMenuActions(); + void contextMenuEvent(TQContextMenuEvent *event); + void setParameterChangedCallback(void (*paramChangedCallback)(void)); + void setWindowClosedCallback(void (*winClosedCallback)(void)); + int getIndenterId(); + + signals: + void indenterSettingsChanged(); + void selectedIndenterIndexChanged(int index); + + protected: + bool event(TQEvent *event); + void closeEvent(TQCloseEvent *event); + void wheelEvent(TQWheelEvent *event); + + private slots: + void setIndenter(int indenterID); + void showIndenterManual(); + void openConfigFileDialog(); + void saveasIndentCfgFileDialog(); + void createIndenterCallShellScript(); + void resetIndenterParameter(); + void handleChangedIndenterSettings(); + void updateDrawing(); + + private: + TQString callExecutableIndenter(TQString sourceCode, TQString inputFileExtension); + TQString callJavaScriptIndenter(TQString sourceCode); + void saveConfigFile(TQString filePathName, TQString parameterString); + void readIndentIniFile(TQString iniFilePath); + bool createIndenterCallString(); + void initIndenterMenu(); + + //! Holds a reference to all created pages of the parameter categories toolbox and the pages + // boxlayout + struct IndenterParameterCategoryPage + { + TQWidget *widget; + TQVBoxLayout *vboxLayout; + }; + + TQVector<IndenterParameterCategoryPage> _indenterParameterCategoryPages; + + //! Holds a reference to all checkboxes needed for boolean parameter setting and the parameters + // name + struct ParamBoolean + { + TQString paramName; + TQString trueString; + TQString falseString; + TQCheckBox *checkBox; + }; + + TQVector<ParamBoolean> _paramBooleans; + + //! Holds a reference to all line edits needed for parameter setting and the parameters name + struct ParamString + { + TQString paramName; + TQString paramCallName; + TQCheckBox *valueEnabledChkBox; + TQLineEdit *lineEdit; + TQLabel *label; + }; + + TQVector<ParamString> _paramStrings; + + //! Hold a reference to all spin boxes needed for parameter setting and the parameters name + struct ParamNumeric + { + TQString paramName; + TQString paramCallName; + TQCheckBox *valueEnabledChkBox; + TQSpinBox *spinBox; + TQLabel *label; + }; + + TQVector<ParamNumeric> _paramNumerics; + + //! Hold a reference to all combo boxes needed for parameter setting and the parameters name + struct ParamMultiple + { + TQString paramName; + TQString paramCallName; + TQCheckBox *valueEnabledChkBox; + TQComboBox *comboBox; + TQStringList choicesStrings; + TQStringList choicesStringsReadable; + }; + + TQVector<ParamMultiple> _paramMultiples; + + TQComboBox *_indenterSelectionCombobox; + TQToolButton *_indenterParameterHelpButton; + //! Vertical layout box, into which the toolbox will be added + TQVBoxLayout *_toolBoxContainerLayout; + TQToolBox *_indenterParameterCategoriesToolBox; + UiGuiIniFileParser *_indenterSettings; + TQStringList _indenterParameters; + //! The indenters name in a descriptive form + TQString _indenterName; + //! The indenters file name (w/o extension), that is being called + TQString _indenterFileName; + TQString _indenterDirctoryStr; + TQString _tempDirctoryStr; + TQString _settingsDirctoryStr; + TQStringList _indenterIniFileList; + TQString _parameterOrder; + TQString _globalConfigFilename; + TQString _cfgFileParameterEnding; + TQString _inputFileParameter; + TQString _inputFileName; + TQString _outputFileParameter; + TQString _outputFileName; + TQString _fileTypes; + TQString _useCfgFileParameter; + TQString _indenterShowHelpParameter; + TQWidget *_mainWindow; + UiGuiErrorMessage *_errorMessageDialog; + TQString _indenterExecutableCallString; + TQString _indenterExecutableSuffix; + + TQMenu *_menuIndenter; + TQAction *_actionLoadIndenterConfigFile; + TQAction *_actionSaveIndenterConfigFile; + TQAction *_actionCreateShellScript; + TQAction *_actionResetIndenterParameters; + //! Needed for the NPP plugin. + void (*_parameterChangedCallback)(void); + //! Needed for the NPP plugin. + void (*_windowClosedCallback)(void); + + //TODO: This function should go into a string helper/tool class/file. + TQString encodeToHTML(const TQString &text); +}; + +#endif // INDENTHANDLER_H diff --git a/src/__TODO/MainWindow.ui b/src/__TODO/MainWindow.ui new file mode 100755 index 0000000..6377823 --- /dev/null +++ b/src/__TODO/MainWindow.ui @@ -0,0 +1,157 @@ +<!DOCTYPE UI><UI version="3.3" stdsetdef="1"> + <author>Thomas_-_S</author> + <class>MainWindowUi</class> + <widget class="TQMainWindow"> + <property name="name"> + <cstring>MainWindowUi</cstring> + </property> + <widget class="TQWidget" name="centralwidget"> + <layout class="TQHBoxLayout"> + <property name="spacing"> + <number>6</number> + </property> + <property name="margin"> + <number>0</number> + </property> + <item> + <layout class="TQHBoxLayout"> + <property name="spacing"> + <number>0</number> + </property> + <property name="margin"> + <number>2</number> + </property> + </layout> + </item> + </layout> + </widget> + <widget class="TQStatusBar" name="statusbar"/> + <widget class="TQDockWidget" name="dockWidget"> + <property name="sizePolicy"> + <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="features"> + <set>TQDockWidget::DockWidgetFloatable|TQDockWidget::DockWidgetMovable</set> + </property> + <property name="allowedAreas"> + <set>TQt::LeftDockWidgetArea|TQt::RightDockWidgetArea</set> + </property> + <property name="windowTitle"> + <string>Indenter Settings</string> + </property> + <attribute name="dockWidgetArea"> + <number>1</number> + </attribute> + <widget class="TQWidget" name="dockWidgetContents"> + <layout class="TQHBoxLayout"> + <property name="spacing"> + <number>6</number> + </property> + <property name="margin"> + <number>0</number> + </property> + <item> + <layout class="TQVBoxLayout"> + <property name="spacing"> + <number>0</number> + </property> + <property name="margin"> + <number>0</number> + </property> + </layout> + </item> + </layout> + </widget> + </widget> + <widget class="TQToolBar" name="toolBar"> + <property name="contextMenuPolicy"> + <enum>TQt::PreventContextMenu</enum> + </property> + <property name="windowTitle"> + <string>Main Toolbar</string> + </property> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="iconSize"> + <size> + <width>16</width> + <height>16</height> + </size> + </property> + <property name="toolButtonStyle"> + <enum>TQt::ToolButtonTextBesideIcon</enum> + </property> + <attribute name="toolBarArea"> + <enum>TopToolBarArea</enum> + </attribute> + <attribute name="toolBarBreak"> + <bool>false</bool> + </attribute> + </widget> + <action name="actionSave_Source_File"> + </action> + <action name="actionSave_Source_File_As"> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/document-save-as.png</normaloff>:/mainWindow/document-save-as.png</iconset> + </property> + <property name="text"> + <string>Save Source File As...</string> + </property> + <property name="iconText"> + <string>Save Source File As...</string> + </property> + <property name="toolTip"> + <string>Save Source File As...</string> + </property> + <property name="statusTip"> + <string>Opens a file dialog to save the currently shown source code.</string> + </property> + <property name="shortcut"> + <string>Ctrl+Shift+S</string> + </property> + </action> + <action name="actionCheck_for_update"> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/system-software-update.png</normaloff>:/mainWindow/system-software-update.png</iconset> + </property> + <property name="text"> + <string>Check for update</string> + </property> + <property name="toolTip"> + <string>Checks online whether a new version of UniversalIndentGUI is available.</string> + </property> + <property name="statusTip"> + <string>Checks online whether a new version of UniversalIndentGUI is available.</string> + </property> + </action> + <action name="actionClear_Recently_Opened_List"> + </action> + </widget> + <resources> + <include location="../resources/Icons.qrc"/> + </resources> + <connections> + <connection> + <sender>actionExit</sender> + <signal>triggered()</signal> + <receiver>MainWindowUi</receiver> + <slot>close()</slot> + <hints> + <hint type="sourcelabel"> + <x>-1</x> + <y>-1</y> + </hint> + <hint type="destinationlabel"> + <x>399</x> + <y>299</y> + </hint> + </hints> + </connection> + </connections> +</UI> diff --git a/src/__TODO/SettingsPaths.cpp b/src/__TODO/SettingsPaths.cpp new file mode 100644 index 0000000..a8016f7 --- /dev/null +++ b/src/__TODO/SettingsPaths.cpp @@ -0,0 +1,309 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "SettingsPaths.h" + +#include <tqcoreapplication.h> +#include <tntqfile.h> +#include <tntqdir.h> +#include <tqdiriterator.h> +#include <tntqstack.h> +#include <tqtdebug.h> + +#include <stdlib.h> + +//! \defgroup grp_Settings All concerning applications settings. + +/*! + \class SettingsPaths + \ingroup grp_Settings + \brief SettingsPaths is a pure static functions class from which info about the + paths needed for settings can be retrieved. +*/ + +bool SettingsPaths::_alreadyInitialized = false; +TQString SettingsPaths::_applicationBinaryPath = ""; +TQString SettingsPaths::_settingsPath = ""; +TQString SettingsPaths::_globalFilesPath = ""; +TQString SettingsPaths::_indenterPath = ""; +TQString SettingsPaths::_tempPath = ""; +bool SettingsPaths::_portableMode = false; + +/*! + \brief Initializes all available information about the paths. + + Mainly during this init it is detected whether to start in portable mode or not. This is + done by testing whether the directory "config" is in the same directory as this + applications executable file. + In portable mode all data is ONLY written to subdirectories of the applications executable file. + Means also that the directory "indenters" has to be there. + In not portable mode (multiuser mode) only users home directory is used for writing config data. + */ +void SettingsPaths::init() +{ + _alreadyInitialized = true; + + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Initializing application paths."; + + // Get the applications binary path, with respect to MacOSXs use of the .app folder. + _applicationBinaryPath = TQCoreApplication::applicationDirPath(); + // Remove any trailing slashes + while (_applicationBinaryPath.right(1) == "/") + { + _applicationBinaryPath.chop(1); + } + +#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS + _applicationBinaryPath += "/plugins/uigui"; +#endif + +#ifdef Q_OS_MAC + // Because on Mac universal binaries are used, the binary path is not equal + // to the applications (.app) path. So get the .apps path here. + int indexOfDotApp = _applicationBinaryPath.indexOf(".app"); + if (indexOfDotApp != -1) + { + // Cut off after the dot of ".app". + _applicationBinaryPath = _applicationBinaryPath.left(indexOfDotApp - 1); + // Cut off after the first slash that was in front of ".app" (normally this is the word + // "UniversalIndentGUI") + _applicationBinaryPath = _applicationBinaryPath.left(_applicationBinaryPath.lastIndexOf("/")); + } +#endif + + // If the "config" directory is a subdir of the applications binary path, use this one (portable + // mode) + _settingsPath = _applicationBinaryPath + "/config"; + if (TQFile::exists(_settingsPath)) + { + _portableMode = true; + TQDir dirCreator; + _globalFilesPath = _applicationBinaryPath; + _indenterPath = _applicationBinaryPath + "/indenters"; + dirCreator.mkpath(_settingsPath); + _tempPath = _applicationBinaryPath + "/temp"; + //TODO: If the portable drive has write protection, use local temp path and clean it up on exit. + dirCreator.mkpath(_tempPath); + } + // ... otherwise use the system specific global application data path. + else + { + _portableMode = false; + TQDir dirCreator; +#ifdef Q_OS_WIN + // Get the local users application settings directory. + // Remove any trailing slashes. + _settingsPath = TQDir::fromNativeSeparators(qgetenv("APPDATA")); + while (_settingsPath.right(1) == "/") + { + _settingsPath.chop(1); + } + _settingsPath = _settingsPath + "/UniversalIndentGUI"; + + // On windows systems the directories "indenters", "translations" are subdirs of the + // _applicationBinaryPath. + _globalFilesPath = _applicationBinaryPath; +#else + // Remove any trailing slashes. + _settingsPath = TQDir::homePath(); + while (_settingsPath.right(1) == "/") + { + _settingsPath.chop(1); + } + _settingsPath = _settingsPath + "/.universalindentgui"; + _globalFilesPath = "/usr/share/universalindentgui"; +#endif + dirCreator.mkpath(_settingsPath); + // If a highlighter config file does not exist in the users home config dir + // copy the default config file over there. + if (!TQFile::exists(_settingsPath + "/UiGuiSyntaxHighlightConfig.ini")) + { + TQFile::copy(_globalFilesPath + "/config/UiGuiSyntaxHighlightConfig.ini", + _settingsPath + "/UiGuiSyntaxHighlightConfig.ini"); + } + _indenterPath = _globalFilesPath + "/indenters"; + + // On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check + // this. + // Remove any trailing slashes. + _tempPath = TQDir::tempPath(); + while (_tempPath.right(1) == "/") + { + _tempPath.chop(1); + } + _tempPath = _tempPath + "/UniversalIndentGUI"; + +#if defined (Q_OS_WIN32) + dirCreator.mkpath(_tempPath); +#else + // On Unix based systems create a random temporary directory for security + // reasons. Otherwise an evil human being could create a symbolic link + // to an important existing file which gets overwritten when UiGUI writes + // into this normally temporary but linked file. + char *pathTemplate = new char[_tempPath.length() + 8]; + TQByteArray pathTemplateTQBA = TQString(_tempPath + "-XXXXXX").toAscii(); + delete[] pathTemplate; + pathTemplate = pathTemplateTQBA.data(); + pathTemplate = mkdtemp(pathTemplate); + _tempPath = pathTemplate; +#endif + } + + tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \ + "<ul><li>_applicationBinaryPath=" << + _applicationBinaryPath << "</li><li>_settingsPath=" << _settingsPath << + "</li><li>_globalFilesPath=" << _globalFilesPath << "</li><li>_indenterPath=" << + _indenterPath << "</li><li>_tempPath=" << _tempPath << + "</li><li>Running in portable mode=" << _portableMode << "</li></ul>"; +} + +/*! + \brief Returns the path of the applications executable. + */ +const TQString SettingsPaths::getApplicationBinaryPath() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _applicationBinaryPath; +} + +/*! + \brief Returns the path where all settings are being/should be written to. + */ +const TQString SettingsPaths::getSettingsPath() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _settingsPath; +} + +/*! + \brief Returns the path where the files concerning all users reside. For example translations. + */ +const TQString SettingsPaths::getGlobalFilesPath() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _globalFilesPath; +} + +/*! + \brief Returns the path where the indenter executables reside. + */ +const TQString SettingsPaths::getIndenterPath() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _indenterPath; +} + +/*! + \brief Returns the path where the where all temporary data should be written to. + */ +const TQString SettingsPaths::getTempPath() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _tempPath; +} + +/*! + \brief Returns true if portable mode shall be used. + */ +bool SettingsPaths::getPortableMode() +{ + if (!_alreadyInitialized) + { + SettingsPaths::init(); + } + return _portableMode; +} + +/*! + \brief Completely deletes the created temporary directory with all of its content. + */ +void SettingsPaths::cleanAndRemoveTempDir() +{ + TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories); + TQStack<TQString> directoryStack; + bool noErrorsOccurred = true; + + while (dirIterator.hasNext()) + { + TQString currentDirOrFile = dirIterator.next(); + // If this dummy call isn't done here, calling "dirIterator.fileInfo().isDir()" later somehow + // fails. + dirIterator.fileInfo(); + + if (!currentDirOrFile.isEmpty() && dirIterator.fileName() != "." && + dirIterator.fileName() != "..") + { + // There is a path on the stack but the current path doesn't start with that path. + // So we changed into another parent directory and the one on the stack can be deleted + // since it must be empty. + if (!directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top())) + { + TQString dirToBeRemoved = directoryStack.pop(); + bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved); + noErrorsOccurred &= couldRemoveDir; + if (couldRemoveDir == false) + { + tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " << + dirToBeRemoved; + } + //tqDebug() << "Removing Dir " << directoryStack.pop(); + } + + // If the iterator currently points to a directory push it onto the stack. + if (dirIterator.fileInfo().isDir()) + { + directoryStack.push(currentDirOrFile); + //tqDebug() << "Pushing onto Stack " << currentDirOrFile; + } + // otherwise it must be a file, so delete it. + else + { + bool couldRemoveFile = TQFile::remove(currentDirOrFile); + noErrorsOccurred &= couldRemoveFile; + if (couldRemoveFile == false) + { + tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the file: " << + currentDirOrFile; + } + //tqDebug() << "Removing File " << currentDirOrFile; + } + } + } + noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath); + if (noErrorsOccurred == false) + { + tqWarning() << __LINE__ << " " << __FUNCTION__ << + "While cleaning up the temp dir an error occurred."; + } +} diff --git a/src/__TODO/SettingsPaths.h b/src/__TODO/SettingsPaths.h new file mode 100644 index 0000000..92d1d52 --- /dev/null +++ b/src/__TODO/SettingsPaths.h @@ -0,0 +1,50 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef SETTINGSPATHS_H +#define SETTINGSPATHS_H + +class TQString; + + +class SettingsPaths +{ + public: + static void init(); + static const TQString getApplicationBinaryPath(); + static const TQString getSettingsPath(); + static const TQString getGlobalFilesPath(); + static const TQString getIndenterPath(); + static const TQString getTempPath(); + static bool getPortableMode(); + static void cleanAndRemoveTempDir(); + + private: + SettingsPaths(); + + static bool _alreadyInitialized; + static TQString _applicationBinaryPath; + static TQString _settingsPath; + static TQString _globalFilesPath; + static TQString _indenterPath; + static TQString _tempPath; + static bool _portableMode; +}; + +#endif // SETTINGSPATHS_H diff --git a/src/__TODO/TemplateBatchScript.cpp b/src/__TODO/TemplateBatchScript.cpp new file mode 100644 index 0000000..0650cb4 --- /dev/null +++ b/src/__TODO/TemplateBatchScript.cpp @@ -0,0 +1,171 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "TemplateBatchScript.h" + +// Need to include TQObject here so that platform specific defines like Q_OS_WIN32 are set. +#include <tntqobject.h> + +/*! + \brief The only and static function of this class returns a batch or shell script + as string that can be used to call an indenter with the current settings from + the command line. + + The returned string contains some placeholders where the indenter name needs to + be filled in. The placeholders are "__INDENTERCALLSTRING1__" that should be replaced + by the indenter call string that indents a complete directory. + "__INDENTERCALLSTRING2__" the call string for indenting only one file. + And "__INDENTERCALLSTRINGSCRIPTNAME__" which is only the shown name of the indenter. + */ +const char* TemplateBatchScript::getTemplateBatchScript() +{ + static const char *templateBatchScript = +#if defined (Q_OS_WIN32) + "@echo off\n" + "\n" + "IF (%1)==() GOTO error\n" + "dir /b /ad %1 >nul 2>nul && GOTO indentDir\n" + "IF NOT EXIST %1 GOTO error\n" + "goto indentFile\n" + "\n" + ":indentDir\n" + "set searchdir=%1\n" + "\n" + "IF (%2)==() GOTO assignDefaultSuffix\n" + "set filesuffix=%2\n" + "\n" + "GOTO run\n" + "\n" + ":assignDefaultSuffix\n" + "::echo !!!!DEFAULT SUFFIX!!!\n" + "set filesuffix=*\n" + "\n" + ":run\n" + "FOR /F \"tokens=*\" %%G IN ('DIR /B /S %searchdir%\\*.%filesuffix%') DO (\n" + "echo Indenting file \"%%G\"\n" + "__INDENTERCALLSTRING1__\n" + ")\n" + "GOTO ende\n" + "\n" + ":indentFile\n" + "echo Indenting one file %1\n" + "__INDENTERCALLSTRING2__\n" + "\n" + "GOTO ende\n" + "\n" + ":error\n" + "echo .\n" + "echo ERROR: As parameter given directory or file does not exist!\n" + "echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\n" + "echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\n" + "echo Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\n" + "echo .\n" + "\n" + ":ende\n"; + +#else + + "#!/bin/sh \n" + "\n" + "if [ ! -n \"$1\" ]; then\n" + "echo \"Syntax is: recurse.sh dirname filesuffix\"\n" + "echo \"Syntax is: recurse.sh filename\"\n" + "echo \"Example: recurse.sh temp cpp\"\n" + "exit 1\n" + "fi\n" + "\n" + "if [ -d \"$1\" ]; then\n" + "#echo \"Dir ${1} exists\"\n" + "if [ -n \"$2\" ]; then\n" + "filesuffix=$2\n" + "else\n" + "filesuffix=\"*\"\n" + "fi\n" + "\n" + "#echo \"Filtering files using suffix ${filesuffix}\"\n" + "\n" + "file_list=`find ${1} -name \"*.${filesuffix}\" -type f`\n" + "for file2indent in $file_list\n" + "do \n" + "echo \"Indenting file $file2indent\"\n" + "__INDENTERCALLSTRING1__\n" + "done\n" + "else\n" + "if [ -f \"$1\" ]; then\n" + "echo \"Indenting one file $1\"\n" + "__INDENTERCALLSTRING2__\n" + "else\n" + "echo \"ERROR: As parameter given directory or file does not exist!\"\n" + "echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\"\n" + "echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\"\n" + "echo \"Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\"\n" + "exit 1\n" + "fi\n" + "fi\n"; +#endif // #if defined(Q_OS_WIN32) + return templateBatchScript; +} + +/* Here comes the original batch script without the c++ markup +@echo off + +IF (%1)==() GOTO error +dir /b /ad %1 >nul 2>nul && GOTO indentDir +IF NOT EXIST %1 GOTO error +goto indentFile + +:indentDir +set searchdir=%1 + +IF (%2)==() GOTO assignDefaultSuffix +set filesuffix=%2 + +GOTO run + +:assignDefaultSuffix +::echo !!!!DEFAULT SUFFIX!!! +set filesuffix=* + +:run +FOR /F "tokens=*" %%G IN ('DIR /B /S %searchdir%\*.%filesuffix%') DO ( + echo Indenting file "%%G" + ::call call_CSSTidy.bat "%%G" + "C:/Dokumente und Einstellungen/ts/Eigene Dateien/Visual Studio 2005/Projects/UiGuixy/indenters/csstidy.exe" "%%G" --timestamp=true --allow_html_in_templates=false --compress_colors=true --compress_font=true --lowercase_s=false --preserve_css=false --remove_last_;=false --remove_bslash=true --sort_properties=false --sort_selectors=false indentoutput.css + move /Y indentoutput.css "%%G" +) +GOTO ende + +:indentFile +echo Indenting one file %1 +"C:/Dokumente und Einstellungen/ts/Eigene Dateien/Visual Studio 2005/Projects/UiGuixy/indenters/csstidy.exe" %1 --timestamp=true --allow_html_in_templates=false --compress_colors=true --compress_font=true --lowercase_s=false --preserve_css=false --remove_last_;=false --remove_bslash=true --sort_properties=false --sort_selectors=false indentoutput.css +move /Y indentoutput.css %1 + +GOTO ende + +:error +echo . +echo ERROR: As parameter given directory or file does not exist! +echo Syntax is: recurse.bat dirname filesuffix +echo Syntax is: recurse.bat filename +echo Example: recurse.bat temp cpp +echo . + +:ende + +*/ diff --git a/src/__TODO/TemplateBatchScript.h b/src/__TODO/TemplateBatchScript.h new file mode 100644 index 0000000..6384ff0 --- /dev/null +++ b/src/__TODO/TemplateBatchScript.h @@ -0,0 +1,32 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef TEMPLATEBATCHSCRIPT_H +#define TEMPLATEBATCHSCRIPT_H + +class TemplateBatchScript +{ + private: + TemplateBatchScript(); + + public: + static const char* getTemplateBatchScript(); +}; + +#endif // TEMPLATEBATCHSCRIPT_H diff --git a/src/__TODO/ToolBarWidget.ui b/src/__TODO/ToolBarWidget.ui new file mode 100755 index 0000000..8665cac --- /dev/null +++ b/src/__TODO/ToolBarWidget.ui @@ -0,0 +1,124 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ToolBarWidget</class> + <widget class="TQWidget" name="ToolBarWidget"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>773</width> + <height>34</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="TQHBoxLayout"> + <property name="spacing"> + <number>6</number> + </property> + <property name="margin"> + <number>0</number> + </property> + <item> + <widget class="TQPushButton" name="pbOpen_Source_File"> + <property name="toolTip"> + <string><html><head><meta name="qrichtext" content="1" /></head><body style=" white-space: pre-wrap; font-family:MS Shell Dlg; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Opens a dialog for selecting a source code file.</span></p><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;">This file will be used to show what the indent tool changes.</p></body></html></string> + </property> + <property name="text"> + <string>Open Source File </string> + </property> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/document-open.png</normaloff>:/mainWindow/document-open.png</iconset> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="cbLivePreview"> + <property name="toolTip"> + <string><html><head><meta name="qrichtext" content="1" /></head><body style=" white-space: pre-wrap; font-family:MS Shell Dlg 2; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:MS Shell Dlg; font-size:8pt;">Turns the preview of the reformatted source code on and off.</p><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:MS Shell Dlg; font-size:8pt;">In other words it switches between formatted and nonformatted code. (Ctrl+L)</p></body></html></string> + </property> + <property name="text"> + <string>Live Indent Preview</string> + </property> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/live-preview.png</normaloff>:/mainWindow/live-preview.png</iconset> + </property> + <property name="shortcut"> + <string>Ctrl+L</string> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="enableSyntaxHighlightningCheckBox"> + <property name="toolTip"> + <string><html><head><meta name="qrichtext" content="1" /></head><body style=" white-space: pre-wrap; font-family:MS Shell Dlg 2; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:MS Shell Dlg; font-size:8pt;">Enables and disables the highlightning of the source</p><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:MS Shell Dlg; font-size:8pt;">code shown below. (Still needs some performance improvements) (Ctrl+H)</p></body></html></string> + </property> + <property name="text"> + <string>Syntax Highlight</string> + </property> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/syntax-highlight.png</normaloff>:/mainWindow/syntax-highlight.png</iconset> + </property> + <property name="shortcut"> + <string>Ctrl+H</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + <property name="connectedSettingName" stdset="0"> + <string>DONOTTRANSLATE:SyntaxHighlightingEnabled</string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="TQPushButton" name="pbAbout"> + <property name="toolTip"> + <string><html><head><meta name="qrichtext" content="1" /></head><body style=" white-space: pre-wrap; font-family:MS Shell Dlg; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Shows info about UniversalIndentGUI</p></body></html></string> + </property> + <property name="text"> + <string>About</string> + </property> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/info.png</normaloff>:/mainWindow/info.png</iconset> + </property> + </widget> + </item> + <item> + <widget class="TQPushButton" name="pbExit"> + <property name="toolTip"> + <string><html><head><meta name="qrichtext" content="1" /></head><body style=" white-space: pre-wrap; font-family:MS Shell Dlg; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;"><p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Quits the UniversalIndentGUI</p></body></html></string> + </property> + <property name="text"> + <string>Exit</string> + </property> + <property name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/system-log-out.png</normaloff>:/mainWindow/system-log-out.png</iconset> + </property> + </widget> + </item> + </layout> + </widget> + <resources> + <include location="../resources/Icons.qrc"/> + </resources> + <connections/> +</ui> diff --git a/src/__TODO/UiGuiErrorMessage.cpp b/src/__TODO/UiGuiErrorMessage.cpp new file mode 100644 index 0000000..67e8e0c --- /dev/null +++ b/src/__TODO/UiGuiErrorMessage.cpp @@ -0,0 +1,93 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UiGuiErrorMessage.h" + +#include <tntqcheckbox.h> + +/*! + \class UiGuiErrorMessage + \ingroup grp_Dialogs + \brief UiGuiErrorMessage is a child of TQErrorMessage. But TQErrorMessages + "Do not show again" didn't work with my strings, so this is my own, working + implementation of it. +*/ + + +/*! + \brief Initializes the dialog. + + Retrieves the object pointer to the \a _showAgainCheckBox check box, sets the dialogs + modality and for a working translation sets the check box text. + */ +UiGuiErrorMessage::UiGuiErrorMessage(TQWidget *parent) : + TQErrorMessage(parent) +{ + _showAgainCheckBox = findChild<TQCheckBox*>(); + setWindowModality(TQt::ApplicationModal); + _showAgainCheckBox->setText(tr("Show this message again")); +} + +/*! + \brief Just a lazy nothin doin destructive destructor. + */ +UiGuiErrorMessage::~UiGuiErrorMessage(void) +{ +} + +/*! + \brief Shows an error \a message in a dialog box with \a title. + + The shown \a message is added to a list, if not already in there. If it is + already in that list and "Show this message again" is not checked, that + message will not be shown. + */ +void UiGuiErrorMessage::showMessage(const TQString &title, const TQString &message) +{ + bool showAgain = true; + + if (_showAgainCheckBox != 0) + { + showAgain = _showAgainCheckBox->isChecked(); + } + + setWindowTitle(title); + + if (!_errorMessageList.contains(message)) + { + _errorMessageList << message; + if (_showAgainCheckBox != 0) + { + _showAgainCheckBox->setChecked(true); + } + TQErrorMessage::showMessage(message); + } + else if (showAgain) + { + TQErrorMessage::showMessage(message); + } +} + +/*! + \brief For convinience, for showing a dialog box with the default title "UniversalIndentGUI". + */ +void UiGuiErrorMessage::showMessage(const TQString &message) +{ + showMessage("UniversalIndentGUI", message); +} diff --git a/src/__TODO/UiGuiErrorMessage.h b/src/__TODO/UiGuiErrorMessage.h new file mode 100644 index 0000000..0ad9f70 --- /dev/null +++ b/src/__TODO/UiGuiErrorMessage.h @@ -0,0 +1,44 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UIGUIERRORMESSAGE_H +#define UIGUIERRORMESSAGE_H + +#include <tntqerrormessage.h> + +class TQCheckBox; + + +class UiGuiErrorMessage : public TQErrorMessage +{ + Q_OBJECT + + public: + UiGuiErrorMessage(TQWidget *parent = 0); + ~UiGuiErrorMessage(void); + + void showMessage(const TQString &message); + void showMessage(const TQString &title, const TQString &message); + + private: + TQCheckBox *_showAgainCheckBox; + TQStringList _errorMessageList; +}; + +#endif // UIGUIERRORMESSAGE_H diff --git a/src/__TODO/UiGuiHighlighter.cpp b/src/__TODO/UiGuiHighlighter.cpp new file mode 100644 index 0000000..7ee13e8 --- /dev/null +++ b/src/__TODO/UiGuiHighlighter.cpp @@ -0,0 +1,604 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UiGuiHighlighter.h" + +#include "SettingsPaths.h" + +#include <tntqsettings.h> +#include <tqmenu.h> +#include <tntqscrollbar.h> +#include <tqcoreapplication.h> + +#include <Qsci/qsciscintilla.h> +#include <Qsci/qscilexer.h> +#include <Qsci/qscilexerbash.h> +#include <Qsci/qscilexerbatch.h> +#include <Qsci/qscilexercmake.h> +#include <Qsci/qscilexercpp.h> +#include <Qsci/qscilexercsharp.h> +#include <Qsci/qscilexercss.h> +#include <Qsci/qscilexerd.h> +#include <Qsci/qscilexerdiff.h> +#if (TQSCINTILLA_VERSION >= 0x020300) + #include <Qsci/qscilexerfortran.h> + #include <Qsci/qscilexerfortran77.h> +#endif +#include <Qsci/qscilexerhtml.h> +#include <Qsci/qscilexeridl.h> +#include <Qsci/qscilexerjava.h> +#include <Qsci/qscilexerjavascript.h> +#include <Qsci/qscilexerlua.h> +#include <Qsci/qscilexermakefile.h> +#if (TQSCINTILLA_VERSION >= 0x020300) + #include <Qsci/qscilexerpascal.h> +#endif +#include <Qsci/qscilexerperl.h> +#if (TQSCINTILLA_VERSION >= 0x020300) + #include <Qsci/qscilexerpostscript.h> +#endif +#include <Qsci/qscilexerpov.h> +#include <Qsci/qscilexerproperties.h> +#include <Qsci/qscilexerpython.h> +#include <Qsci/qscilexerruby.h> +#if (TQSCINTILLA_VERSION >= 0x020400) + #include <Qsci/qscilexerspice.h> +#endif +#include <Qsci/qscilexersql.h> +#if (TQSCINTILLA_VERSION >= 0x020300) + #include <Qsci/qscilexertcl.h> +#endif +#include <Qsci/qscilexertex.h> +#if (TQSCINTILLA_VERSION >= 0x020400) + #include <Qsci/qscilexerverilog.h> +#endif +#include <Qsci/qscilexervhdl.h> +#if (TQSCINTILLA_VERSION >= 0x020300) + #include <Qsci/qscilexerxml.h> + #include <Qsci/qscilexeryaml.h> +#endif + +//! \defgroup grp_EditorComponent All concerning editor widget. + +/*! + \class UiGuiHighlighter + \ingroup grp_EditorComponent + \brief UiGuiHighlighter used for selecting the syntax highlighter/lexer for the QsciScintilla component. +*/ + +/*! + \brief The constructor initializes some regular expressions and keywords to identify cpp tokens + */ +UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) : + TQObject(parent) +{ + _qsciEditorParent = parent; + + // Create the highlighter _settings object from the UiGuiSyntaxHighlightConfig.ini file. + _settings = new TQSettings( + SettingsPaths::getSettingsPath() + "/UiGuiSyntaxHighlightConfig.ini", TQSettings::IniFormat, + this); + + _highlightningIsOn = true; + + _mapHighlighternameToExtension["Bash"] = TQStringList() << "sh"; + _mapHighlighternameToExtension["Batch"] = TQStringList() << "bat"; + _mapHighlighternameToExtension["CMake"] = TQStringList() << "cmake"; + _mapHighlighternameToExtension["C++"] = TQStringList() << "c" << "h" << "cpp" << "hpp" << + "cxx" << "hxx"; + _mapHighlighternameToExtension["C#"] = TQStringList() << "cs"; + _mapHighlighternameToExtension["CSS"] = TQStringList() << "css"; + _mapHighlighternameToExtension["D"] = TQStringList() << "d"; + _mapHighlighternameToExtension["Diff"] = TQStringList() << "diff"; +#if (TQSCINTILLA_VERSION >= 0x020300) + _mapHighlighternameToExtension["Fortran"] = TQStringList() << "f" << "for" << "f90"; + _mapHighlighternameToExtension["Fortran77"] = TQStringList() << "f77"; +#endif + _mapHighlighternameToExtension["HTML"] = TQStringList() << "html" << "htm"; + _mapHighlighternameToExtension["IDL"] = TQStringList() << "idl"; + _mapHighlighternameToExtension["Java"] = TQStringList() << "java"; + _mapHighlighternameToExtension["JavaScript"] = TQStringList() << "js"; + _mapHighlighternameToExtension["LUA"] = TQStringList() << "lua"; + _mapHighlighternameToExtension["Makefile"] = TQStringList() << "makefile"; +#if (TQSCINTILLA_VERSION >= 0x020300) + _mapHighlighternameToExtension["Pascal"] = TQStringList() << "pas"; +#endif + _mapHighlighternameToExtension["Perl"] = TQStringList() << "perl" << "pl" << "pm"; + _mapHighlighternameToExtension["PHP"] = TQStringList() << "php"; +#if (TQSCINTILLA_VERSION >= 0x020300) + _mapHighlighternameToExtension["PostScript"] = TQStringList() << "ps" << "eps" << "pdf" << "ai" << + "fh"; +#endif + _mapHighlighternameToExtension["POV"] = TQStringList() << "pov"; + _mapHighlighternameToExtension["Ini"] = TQStringList() << "ini"; + _mapHighlighternameToExtension["Python"] = TQStringList() << "py"; + _mapHighlighternameToExtension["Ruby"] = TQStringList() << "rub" << "rb"; +#if (TQSCINTILLA_VERSION >= 0x020400) + _mapHighlighternameToExtension["Spice"] = TQStringList() << "cir"; +#endif + _mapHighlighternameToExtension["SQL"] = TQStringList() << "sql"; +#if (TQSCINTILLA_VERSION >= 0x020300) + _mapHighlighternameToExtension["TCL"] = TQStringList() << "tcl"; +#endif + _mapHighlighternameToExtension["TeX"] = TQStringList() << "tex"; +#if (TQSCINTILLA_VERSION >= 0x020400) + _mapHighlighternameToExtension["Verilog"] = TQStringList() << "v" << "vh"; +#endif + _mapHighlighternameToExtension["VHDL"] = TQStringList() << "vhdl"; + _mapHighlighternameToExtension["XML"] = TQStringList() << "xml"; +#if (TQSCINTILLA_VERSION >= 0x020300) + _mapHighlighternameToExtension["YAML"] = TQStringList() << "yaml"; +#endif + + _lexer = NULL; + + // This code is only for testing. + /* + foreach(TQStringList extensionList, _mapHighlighternameToExtension.values() ) { + setLexerForExtension( extensionList.at(0) ); + } + */ + + // Set default highlighter to C++ highlighter. + setLexerForExtension("cpp"); +} + +/*! + \brief Returns the available highlighters as TQStringList. + */ +TQStringList UiGuiHighlighter::getAvailableHighlighters() +{ + return _mapHighlighternameToExtension.keys(); +} + +/*! + \brief This slot handles signals coming from selecting another syntax highlighter. + */ +void UiGuiHighlighter::setHighlighterByAction(TQAction *highlighterAction) +{ + TQString highlighterName = highlighterAction->text(); + setLexerForExtension(_mapHighlighternameToExtension[highlighterName].first()); + //TODO: This is really no nice way. How do it better? + // Need to do this "text update" to update the syntax highlighting. Otherwise highlighting is + // wrong. + int scrollPos = _qsciEditorParent->verticalScrollBar()->value(); + _qsciEditorParent->setText(_qsciEditorParent->text()); + _qsciEditorParent->verticalScrollBar()->setValue(scrollPos); +} + +/*! + \brief Turns the syntax parser on. +*/ +void UiGuiHighlighter::turnHighlightOn() +{ + _highlightningIsOn = true; + _qsciEditorParent->setLexer(_lexer); + readCurrentSettings(""); +} + +/*! + \brief Turns the syntax parser off. +*/ +void UiGuiHighlighter::turnHighlightOff() +{ + _highlightningIsOn = false; + _qsciEditorParent->setLexer(); +#if defined (Q_OS_WIN) || defined (Q_OS_MAC) + _qsciEditorParent->setFont(TQFont("Courier", 10, TQFont::Normal)); + _qsciEditorParent->setMarginsFont(TQFont("Courier", 10, TQFont::Normal)); +#else + _qsciEditorParent->setFont(TQFont("Monospace", 10, TQFont::Normal)); + _qsciEditorParent->setMarginsFont(TQFont("Monospace", 10, TQFont::Normal)); +#endif +} + +/*! + \brief Read the settings for the current lexer from the settings file. + */ + +//TODO: Refactor this function so that the coding style and variable names suit better. +bool UiGuiHighlighter::readCurrentSettings(const char *prefix) +{ + bool ok, flag, rc = true; + int num; + TQString key; + + // Reset lists containing fonts and colors for each style + _fontForStyles.clear(); + _colorForStyles.clear(); + + // Read the styles. + for (int i = 0; i < 128; ++i) + { + // Ignore invalid styles. + if (_lexer->description(i).isEmpty()) + { + continue; + } + + key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i); + key.replace("+", "p"); + + // Read the foreground color. + ok = _settings->contains(key + "color"); + num = _settings->value(key + "color", 0).toInt(); + + if (ok) + { + setColor(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i); + } + else + { + rc = false; + } + + // Read the end-of-line fill. + ok = _settings->contains(key + "eolfill"); + flag = _settings->value(key + "eolfill", false).toBool(); + + if (ok) + { + _lexer->setEolFill(flag, i); + } + else + { + rc = false; + } + + // Read the font + TQStringList fdesc; + + ok = _settings->contains(key + "font"); + fdesc = _settings->value(key + "font").toStringList(); + + if (ok && fdesc.count() == 5) + { + TQFont f; + +#if defined (Q_OS_WIN) || defined (Q_OS_MAC) + f.setFamily(fdesc[0]); +#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()); + f.setItalic(fdesc[3].toInt()); + f.setUnderline(fdesc[4].toInt()); + + setFont(f, i); + } + else + { + rc = false; + } + + // Read the background color. + ok = _settings->contains(key + "paper"); + num = _settings->value(key + "paper", 0).toInt(); + + if (ok) + { + _lexer->setPaper(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i); + } + else + { + rc = false; + } + } + + // Read the properties. + key.sprintf("%s/%s/properties/", prefix, _lexer->language()); + + _lexer->refreshProperties(); + + return rc; +} + +/*! + \brief Write the settings for the current lexer to the settings file. + */ +void UiGuiHighlighter::writeCurrentSettings(const char *prefix) +{ + TQString key; + + // Write the styles. + for (int i = 0; i < 128; ++i) + { + // Ignore invalid styles. + if (_lexer->description(i).isEmpty()) + { + continue; + } + + int num; + TQColor c; + + key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i); + key.replace("+", "p"); + + // Write style name + _settings->setValue(key + "", _lexer->description(i)); + + // Write the foreground color. + if (_colorForStyles.contains(i)) + { + c = _colorForStyles[i]; + } + else + { + c = _lexer->color(i); + } + num = (c.red() << 16) | (c.green() << 8) | c.blue(); + + _settings->setValue(key + "color", num); + + // Write the end-of-line fill. + _settings->setValue(key + "eolfill", _lexer->eolFill(i)); + + // Write the font + TQStringList fdesc; + TQString fmt("%1"); + TQFont f; + + if (_fontForStyles.contains(i)) + { + f = _fontForStyles[i]; + } + else + { + f = _lexer->font(i); + } + + fdesc += f.family(); + fdesc += fmt.arg(f.pointSize()); + + // The casts are for Borland. + fdesc += fmt.arg((int)f.bold()); + fdesc += fmt.arg((int)f.italic()); + fdesc += fmt.arg((int)f.underline()); + + _settings->setValue(key + "font", fdesc); + + // Write the background color. + c = _lexer->paper(i); + num = (c.red() << 16) | (c.green() << 8) | c.blue(); + + _settings->setValue(key + "paper", num); + } +} + +/*! + \brief Sets the \a color for the given \a style. + */ +void UiGuiHighlighter::setColor(const TQColor &color, int style) +{ + _colorForStyles[style] = color; + _lexer->setColor(color, style); +} + +/*! + \brief Sets the \a font for the given \a style. + */ +void UiGuiHighlighter::setFont(const TQFont &font, int style) +{ + _fontForStyles[style] = font; + _lexer->setFont(font, style); +} + +/*! + \brief Sets the to be used lexer by giving his name. + */ +void UiGuiHighlighter::setLexerByName(TQString lexerName) +{ + setLexerForExtension(_mapHighlighternameToExtension[lexerName].first()); +} + +/*! + \brief Sets the proper highlighter / lexer for the given file \a extension. Returns the index of the used lexer in the list. + */ +int UiGuiHighlighter::setLexerForExtension(TQString extension) +{ + int indexOfHighlighter = 0; + extension = extension.toLower(); + + if (_lexer != NULL) + { + writeCurrentSettings(""); + delete _lexer; + } + + if (extension == "cpp" || extension == "hpp" || extension == "c" || extension == "h" || + extension == "cxx" || extension == "hxx") + { + _lexer = new QsciLexerCPP(); + } + else if (extension == "sh") + { + _lexer = new QsciLexerBash(); + } + else if (extension == "bat") + { + _lexer = new QsciLexerBatch(); + } + else if (extension == "cmake") + { + _lexer = new QsciLexerCMake(); + } + else if (extension == "cs") + { + _lexer = new QsciLexerCSharp(); + } + else if (extension == "css") + { + _lexer = new QsciLexerCSS(); + } + else if (extension == "d") + { + _lexer = new QsciLexerD(); + } + else if (extension == "diff") + { + _lexer = new QsciLexerDiff(); + } +#if (TQSCINTILLA_VERSION >= 0x020300) + else if (extension == "f" || extension == "for" || extension == "f90") + { + _lexer = new QsciLexerFortran(); + } + else if (extension == "f77") + { + _lexer = new QsciLexerFortran77(); + } +#endif + else if (extension == "html" || extension == "htm") + { + _lexer = new QsciLexerHTML(); + } + else if (extension == "idl") + { + _lexer = new QsciLexerIDL(); + } + else if (extension == "java") + { + _lexer = new QsciLexerJava(); + } + else if (extension == "js") + { + _lexer = new QsciLexerJavaScript(); + } + else if (extension == "lua") + { + _lexer = new QsciLexerLua(); + } + else if (extension == "makefile") + { + _lexer = new QsciLexerMakefile(); + } +#if (TQSCINTILLA_VERSION >= 0x020300) + else if (extension == "pas") + { + _lexer = new QsciLexerPascal(); + } +#endif + else if (extension == "perl" || extension == "pl" || extension == "pm") + { + _lexer = new QsciLexerPerl(); + } + else if (extension == "php") + { + _lexer = new QsciLexerHTML(); + } +#if (TQSCINTILLA_VERSION >= 0x020300) + else if (extension == "ps" || extension == "eps" || extension == "pdf" || extension == "ai" || + extension == "fh") + { + _lexer = new QsciLexerPostScript(); + } +#endif + else if (extension == "pov") + { + _lexer = new QsciLexerPOV(); + } + else if (extension == "ini") + { + _lexer = new QsciLexerProperties(); + } + else if (extension == "py") + { + _lexer = new QsciLexerPython(); + } + else if (extension == "rub" || extension == "rb") + { + _lexer = new QsciLexerRuby(); + } +#if (TQSCINTILLA_VERSION >= 0x020400) + else if (extension == "spice?") + { + _lexer = new QsciLexerSpice(); + } +#endif + else if (extension == "sql") + { + _lexer = new QsciLexerSQL(); + } +#if (TQSCINTILLA_VERSION >= 0x020300) + else if (extension == "tcl") + { + _lexer = new QsciLexerTCL(); + } +#endif + else if (extension == "tex") + { + _lexer = new QsciLexerTeX(); + } +#if (TQSCINTILLA_VERSION >= 0x020400) + else if (extension == "vlog?") + { + _lexer = new QsciLexerVerilog(); + } +#endif + else if (extension == "vhdl") + { + _lexer = new QsciLexerVHDL(); + } + else if (extension == "xml") + { +#if (TQSCINTILLA_VERSION >= 0x020300) + _lexer = new QsciLexerXML(); +#else + _lexer = new QsciLexerHTML(); +#endif + } +#if (TQSCINTILLA_VERSION >= 0x020300) + else if (extension == "yaml") + { + _lexer = new QsciLexerYAML(); + } +#endif + else + { + _lexer = new QsciLexerCPP(); + extension = "cpp"; + } + + // Find the index of the selected _lexer. + indexOfHighlighter = 0; + while (!_mapHighlighternameToExtension.values().at(indexOfHighlighter).contains(extension)) + { + indexOfHighlighter++; + } + + // Set the _lexer for the TQScintilla widget. + if (_highlightningIsOn) + { + _qsciEditorParent->setLexer(_lexer); + } + + // Read the _settings for the _lexer properties from file. + readCurrentSettings(""); + + return indexOfHighlighter; +} diff --git a/src/__TODO/UiGuiHighlighter.h b/src/__TODO/UiGuiHighlighter.h new file mode 100644 index 0000000..ad50849 --- /dev/null +++ b/src/__TODO/UiGuiHighlighter.h @@ -0,0 +1,75 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UIGUIHIGHLIGHTER_H +#define UIGUIHIGHLIGHTER_H + +#include <tntqobject.h> +#include <tntqmap.h> +#include <tntqfont.h> +#include <tntqcolor.h> + +class TQAction; +class TQSettings; + +class QsciScintilla; +class QsciLexer; + + +class UiGuiHighlighter : public TQObject +{ + Q_OBJECT + + public: + UiGuiHighlighter(QsciScintilla *parent); + + void turnHighlightOff(); + void turnHighlightOn(); + + bool readCurrentSettings(const char *prefix); + void writeCurrentSettings(const char *prefix); + TQStringList getAvailableHighlighters(); + + public slots: + //! The foreground color for style number \a style is set to \a color. If + //! \a style is -1 then the color is set for all styles. + void setColor(const TQColor &color, int style = -1); + + //! The font for style number \a style is set to \a font. If \a style is + //! -1 then the font is set for all styles. + void setFont(const TQFont &font, int style = -1); + + //! Sets the lexer that is responsible for the given \a extension. + int setLexerForExtension(TQString extension); + + void setLexerByName(TQString lexerName); + + void setHighlighterByAction(TQAction *highlighterAction); + + private: + bool _highlightningIsOn; + QsciScintilla *_qsciEditorParent; + TQMap<int, TQFont> _fontForStyles; + TQMap<int, TQColor> _colorForStyles; + QsciLexer *_lexer; + TQSettings *_settings; + TQMap<TQString, TQStringList> _mapHighlighternameToExtension; +}; + +#endif // UIGUIHIGHLIGHTER_H diff --git a/src/__TODO/UiGuiIndentServer.cpp b/src/__TODO/UiGuiIndentServer.cpp new file mode 100644 index 0000000..91c5ec7 --- /dev/null +++ b/src/__TODO/UiGuiIndentServer.cpp @@ -0,0 +1,175 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UiGuiIndentServer.h" + +#include <tqtcpserver.h> +#include <tqtcpsocket.h> +#include <tntqmessagebox.h> +#include <tqtdebug.h> + +//! \defgroup grp_Server All concerning the server component. + +/*! + \class UiGuiIndentServer + \ingroup grp_Server + \brief UiGuiIndentServer is in such an early state, that even the communication + protocol isn't completely planned. So this class lacks documentation until + I really know where all this will lead to. + + The plan however is to have a server that receives commands for selecting an + indenter and perhaps load some by the user predefined indenter config file. Then + the client can send a text to it and will receive it formatted. + The idea behind that is to make UiGUIs use as plugin or whatever more flexible. + So the plugin is developed for Eclipse for example and it takes the client role, + making it possible to use UiGUI from within Eclipse. Choosing a network protocol + makes everything platform and programming language independent, so it doesn't + matter for which application the plugin/client is developed. +*/ + +UiGuiIndentServer::UiGuiIndentServer(void) : + TQObject() +{ + _tcpServer = NULL; + _currentClientConnection = NULL; + _readyForHandleRequest = false; +} + +UiGuiIndentServer::~UiGuiIndentServer(void) +{ +} + +void UiGuiIndentServer::startServer() +{ + if (_tcpServer == NULL) + { + _tcpServer = new TQTcpServer(this); + } + + if (!_tcpServer->isListening()) + { + if (!_tcpServer->listen(TQHostAddress::Any, tquint16(84484))) + { + TQMessageBox::critical(NULL, tr("UiGUI Server"), + tr("Unable to start the server: %1.").arg(_tcpServer->errorString())); + return; + } + } + + connect(_tcpServer, SIGNAL(newConnection()), this, SLOT(handleNewConnection())); + _readyForHandleRequest = true; + _blockSize = 0; +} + +void UiGuiIndentServer::stopServer() +{ + if (_tcpServer != NULL) + { + _tcpServer->close(); + delete _tcpServer; + _tcpServer = NULL; + } + _currentClientConnection = NULL; + _readyForHandleRequest = false; +} + +void UiGuiIndentServer::handleNewConnection() +{ + TQTcpSocket *clientConnection = _tcpServer->nextPendingConnection(); + connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); + + connect(clientConnection, SIGNAL(readyRead()), this, SLOT(handleReceivedData())); +} + +void UiGuiIndentServer::handleReceivedData() +{ + if (!_readyForHandleRequest) + { + return; + } + + _currentClientConnection = qobject_cast<TQTcpSocket*>(sender()); + TQString receivedData = ""; + + if (_currentClientConnection != NULL) + { + TQDataStream in(_currentClientConnection); + in.setVersion(TQDataStream::TQt_4_0); + + if (_blockSize == 0) + { + if (_currentClientConnection->bytesAvailable() < (int)sizeof(tquint32)) + { + return; + } + + in >> _blockSize; + } + + if (_currentClientConnection->bytesAvailable() < _blockSize) + { + return; + } + + TQString receivedMessage; + in >> receivedMessage; + + _blockSize = 0; + + tqDebug() << "receivedMessage: " << receivedMessage; + + if (receivedMessage == "ts") + { + sendMessage("Toll"); + } + else + { + sendMessage("irgendwas"); + } + } +} + +void UiGuiIndentServer::sendMessage(const TQString &message) +{ + _readyForHandleRequest = false; + + _dataToSend = ""; + TQDataStream out(&_dataToSend, TQIODevice::WriteOnly); + out.setVersion(TQDataStream::TQt_4_0); + out << (tquint32)0; + out << message; + out.device()->seek(0); + out << (tquint32)(_dataToSend.size() - sizeof(tquint32)); + + connect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this, + SLOT(checkIfReadyForHandleRequest())); + _currentClientConnection->write(_dataToSend); +} + +void UiGuiIndentServer::checkIfReadyForHandleRequest() +{ + if (_currentClientConnection->bytesToWrite() == 0) + { + TQString dataToSendStr = _dataToSend.right(_dataToSend.size() - sizeof(tquint32)); + tqDebug() << "checkIfReadyForHandleRequest _dataToSend was: " << dataToSendStr; + disconnect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this, + SLOT(checkIfReadyForHandleRequest())); + _readyForHandleRequest = true; + } +} diff --git a/src/__TODO/UiGuiIndentServer.h b/src/__TODO/UiGuiIndentServer.h new file mode 100644 index 0000000..3f8c996 --- /dev/null +++ b/src/__TODO/UiGuiIndentServer.h @@ -0,0 +1,55 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UIGUIINDENTSERVER_H +#define UIGUIINDENTSERVER_H + +#include <tqobject.h> + +class TQTcpServer; +class TQTcpSocket; + + +class UiGuiIndentServer : public TQObject +{ + Q_OBJECT + + public: + UiGuiIndentServer(void); + ~UiGuiIndentServer(void); + + public slots: + void startServer(); + void stopServer(); + + private slots: + void handleNewConnection(); + void handleReceivedData(); + void sendMessage(const TQString &message); + void checkIfReadyForHandleRequest(); + + private: + TQTcpServer *_tcpServer; + TQByteArray _dataToSend; + bool _readyForHandleRequest; + TQTcpSocket *_currentClientConnection; + TQ_UINT32 _blockSize; +}; + +#endif // UIGUIINDENTSERVER_H diff --git a/src/__TODO/UiGuiIniFileParser.cpp b/src/__TODO/UiGuiIniFileParser.cpp new file mode 100644 index 0000000..e690139 --- /dev/null +++ b/src/__TODO/UiGuiIniFileParser.cpp @@ -0,0 +1,160 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UiGuiIniFileParser.h" + +#include <tntqfile.h> +#include <tntqstringlist.h> +#include <tntqvariant.h> +#include <tntqtextstream.h> + +//! \defgroup grp_Settings All concerning applications settings. + +/*! + \class UiGuiIniFileParser + \ingroup grp_Settings + \brief UiGuiIniFileParser is a simple ini file format parser. + + These ini files need to have key-value pairs in the style + "keyname=keyvalue". Groups can be defined by writing the groupname + in the style [groupname] before some key-value pairs. + + The reason why I use my own class instead of TQSettings is mainly, that + TQSettings always internally sorts the groups alphabetically and also + rewrites a settings file sorted. Very annoying for me. +*/ + +/*! + \brief Init and empty all needed lists and strings. + */ +UiGuiIniFileParser::UiGuiIniFileParser(void) +{ + init(); +} + +/*! + \brief Directly loads and parses the file with name \a iniFileName. + */ +UiGuiIniFileParser::UiGuiIniFileParser(const TQString &iniFileName) +{ + init(); + _iniFileName = iniFileName; + parseIniFile(); +} + +void UiGuiIniFileParser::init() +{ + _sections.clear(); + _keyValueMap.clear(); + _iniFileName = ""; +} + +UiGuiIniFileParser::~UiGuiIniFileParser(void) +{ +} + +/*! + \brief Returns the group/section names in the same order as they occurr in the ini file as TQStringList. + */ +TQStringList UiGuiIniFileParser::childGroups() +{ + TQStringList sectionsStringList; + + 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. + + The \a keyName is assembled by a section name, a slash and the key name itself. + For example if you wish to access the value of the following setting: + <code>[NiceSection]</br>niceKeyName=2</code> you would have to call + value("NiceSection/niceKeyName"). + */ +TQVariant UiGuiIniFileParser::value(const TQString &keyName, const TQString &defaultValue) +{ + return _keyValueMap.value(keyName, defaultValue); +} + +/*! + \brief Parses the ini file and stores the key value pairs in the internal vectors \a keys and \a values. + */ +void UiGuiIniFileParser::parseIniFile() +{ + TQFile iniFile(_iniFileName); + + if (iniFile.open(TQFile::ReadOnly)) + { + // Clear the vectors holding the keys and values. + _sections.clear(); + _keyValueMap.clear(); + + TQTextStream iniFileStream(&iniFile); + TQString line; + TQString currentSectionName = ""; + TQString keyName = ""; + TQString valueAsString = ""; + + while (!iniFileStream.atEnd()) + { + line = iniFileStream.readLine().trimmed(); + + // Test if the read line is a section name and if so remeber it. + if (line.startsWith("[") && line.endsWith("]")) + { + currentSectionName = line.remove(0, 1); + currentSectionName.chop(1); + + // Store the section name. + _sections.push_back(currentSectionName); + } + // Otherwise test whether the line has a assign char + else if (line.contains("=")) + { + int indexOfFirstAssign = line.indexOf("="); + keyName = line.left(indexOfFirstAssign); + + if (!keyName.isEmpty()) + { + valueAsString = line.remove(0, indexOfFirstAssign + 1); + // Remove any existing double quotes from the value. + if (valueAsString.startsWith("\"") && valueAsString.endsWith("\"")) + { + valueAsString = valueAsString.remove(0, 1); + valueAsString.chop(1); + } + + // Prepend an eventually section name to the key name. + if (!currentSectionName.isEmpty()) + { + keyName = currentSectionName + "/" + keyName; + } + + // Store the key and value in the map. + _keyValueMap.insert(keyName, valueAsString); + } + } + } + } +} diff --git a/src/__TODO/UiGuiIniFileParser.h b/src/__TODO/UiGuiIniFileParser.h new file mode 100644 index 0000000..0aebb09 --- /dev/null +++ b/src/__TODO/UiGuiIniFileParser.h @@ -0,0 +1,53 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UIGUIINIFILEPARSER_H +#define UIGUIINIFILEPARSER_H + +#include <tntqmap.h> +#include <tntqstring.h> + +#include <vector> + +class TQStringList; +class TQVariant; + + +class UiGuiIniFileParser +{ + public: + UiGuiIniFileParser(void); + UiGuiIniFileParser(const TQString &iniFileName); + ~UiGuiIniFileParser(void); + + TQVariant value(const TQString &keyName, const TQString &defaultValue = ""); + TQStringList childGroups(); + + protected: + void init(); + + private: + void parseIniFile(); + + TQString _iniFileName; + std::vector<TQString> _sections; + TQMap<TQString, TQVariant> _keyValueMap; +}; + +#endif // UIGUIINIFILEPARSER_H diff --git a/src/__TODO/UiGuiSettings.cpp b/src/__TODO/UiGuiSettings.cpp new file mode 100644 index 0000000..ebac977 --- /dev/null +++ b/src/__TODO/UiGuiSettings.cpp @@ -0,0 +1,933 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ + +#include "UiGuiSettings.h" + +#include "SettingsPaths.h" + +#include <tqsettings.h> +#include <tqpoint.h> +#include <tqsize.h> +#include <tqdir.h> +#include <tqdate.h> +#include <tqstringlist.h> +#include <tqcoreapplication.h> +#include <tqmetamethod.h> +#include <tqmetaproperty.h> +#include <tqwidget.h> + +//! \defgroup grp_Settings All concerning the settings. + +/*! + \class UiGuiSettings + \ingroup grp_Settings + \brief Handles the settings of the program. Reads them on startup and saves them on exit. + Is a singleton class and can only be accessed via getInstance(). +*/ + +// Inits the single class instance pointer. +TQWeakPointer<UiGuiSettings> UiGuiSettings::_instance; + + +/*! + \brief The constructor for the settings. +*/ +UiGuiSettings::UiGuiSettings() : + TQObject() +{ + // Create the main application settings object from the UniversalIndentGUI.ini file. + _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> sharedInstance = _instance.toStrongRef(); + if (sharedInstance.isNull()) + { + // Create the settings object, which loads all UiGui settings from a file. + sharedInstance = TQSharedPointer<UiGuiSettings>(new UiGuiSettings()); + _instance = sharedInstance.toWeakRef(); + } + + return sharedInstance; +} + +/*! + \brief The destructor saves the settings to a file. + */ +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() +{ + TQString languageShort; + TQStringList languageFileList; + + // 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. + TQDir translationDirectory = TQDir(SettingsPaths::getGlobalFilesPath() + "/translations"); + languageFileList << translationDirectory.entryList(TQStringList("universalindent_*.qm")); + + // Loop for each found translation file + foreach(languageShort, languageFileList) + { + // Remove the leading string "universalindent_" from the filename. + languageShort.remove(0, 16); + // Remove trailing file extension ".qm". + languageShort.chop(3); + + _availableTranslations.append(languageShort); + } +} + +/*! + \brief Returns a list of the mnemonics of the available translations. + */ +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) +{ + return _qsettings->value("UniversalIndentGUI/" + settingName); +} + +/*! + \brief Loads the settings for the main application. + + Settings are for example last selected indenter, last loaded source code file and so on. +*/ +bool UiGuiSettings::initSettings() +{ + // Read the version string saved in the settings file. + _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))); + + // Read last selected encoding for the opened source code file. + _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)); + + // Read if last opened source code file should be loaded on startup. + _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")); + + // Read last selected indenter from the settings file. + int selectedIndenter = _qsettings->value("UniversalIndentGUI/selectedIndenter", 0).toInt(); + 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)); + + // Read if white space characters should be displayed. + _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)); + + // Read the tab width from the settings file. + _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 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))); + + // Read the main window state. + _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) +{ + 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*))); + + int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); + if (connectSuccess && indexOfProp > -1) + { + TQMetaProperty mProp = metaObject->property(indexOfProp); + + // Connect to the property's value changed signal. + 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())); + } + + if (connectSuccess) + { + _registeredObjectProperties[obj] = TQStringList() << propertyName << settingName; + } + else + { + //TODO: Write a debug warning to the log. + 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)) + { + mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName)); + } + // Otherwise add the setting and set it to the value of the objects property. + else + { + _qsettings->setValue("UniversalIndentGUI/" + settingName, mProp.read(obj)); + } + } + else + { + //TODO: Write a debug warning to the log. + disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*))); + return false; + } + + 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. + + The custom properties, for which are searched, are "connectedPropertyName" and "connectedSettingName", + where "connectedPropertyName" is the name of a TQObject property as it is documented in the TQtDocs, and + "connectedSettingName" is the name of a setting here within UiGuiSettings. If the mentioned setting + name doesn't exist, it will be created. + + 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) +{ + 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) +{ + const TQMetaObject *metaObject = obj->metaObject(); + + int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); + 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)) + { + mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName)); + } + // The setting didn't exist so return that setting the objects property failed. + else + { + //TODO: Write a debug warning to the log. + return false; + } + } + else + { + //TODO: Write a debug warning to the log. + return false; + } + + 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. + + The custom properties, for which are searched, are "connectedPropertyName" and "connectedSettingName", + where "connectedPropertyName" is the name of a TQObject property as it is documented in the TQtDocs, and + "connectedSettingName" is the name of a setting here within UiGuiSettings. + + 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) +{ + 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. + + If the \a settingName didn't exist yet, it will be created. + + 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) +{ + const TQMetaObject *metaObject = obj->metaObject(); + + int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); + if (indexOfProp > -1) + { + TQMetaProperty mProp = metaObject->property(indexOfProp); + + setValueByName(settingName, mProp.read(obj)); + } + else + { + //TODO: Write a debug warning to the log. + return false; + } + + 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. + + The custom properties, for which are searched, are "connectedPropertyName" and "connectedSettingName", + where "connectedPropertyName" is the name of a TQObject property as it is documented in the TQtDocs, and + "connectedSettingName" is the name of a setting here within UiGuiSettings. If the settingName + didn't exist yet, it will be created. + + 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) +{ + 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 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) + { + 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()) + { + success &= (this->*callBackFunc)(object, propertyName, settingName); + } + } + + return success; +} + +/*! + \brief The with a certain property registered \a obj gets unregistered. + */ +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) + { + TQMetaProperty mProp = metaObject->property(indexOfProp); + + // Disconnect to the property's value changed signal. + 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())); + } + } + _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. + + The registered slot may have no parameters or exactly one. If it accepts one parameter, whenever the setting + \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) +{ + 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*))); + + TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName)); + int indexOfMethod = metaObject->indexOfMethod(qPrintable(normalizedSlotName)); + 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) + { + _registeredObjectSlots.insert(obj, TQStringList() << normalizedSlotName << settingName); + } + else + { + //TODO: Write a debug warning to the log. + disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*))); + return false; + } + } + else + { + //TODO: Write a debug warning to the log. + disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*))); + return false; + } + + 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) +{ + //const TQMetaObject *metaObject = obj->metaObject(); + TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName)); + TQMutableMapIterator<TQObject*, TQStringList> it(_registeredObjectSlots); + 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() +{ + TQObject *obj = TQObject::sender(); + TQString className = obj->metaObject()->className(); + const TQMetaObject *metaObject = obj->metaObject(); + TQString propertyName = _registeredObjectProperties[obj].first(); + TQString settingName = _registeredObjectProperties[obj].last(); + + int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); + if (indexOfProp > -1) + { + TQMetaProperty mProp = metaObject->property(indexOfProp); + setValueByName(settingName, mProp.read(obj)); + } +} + +/*! + \brief Sets the setting defined by \a settingName to \a value. + + When setting a changed value, all to this settingName registered objects get + 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) +{ + // Do the updating only, if the setting was really changed. + 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) + { + TQObject *obj = it.key(); + const TQMetaObject *metaObject = obj->metaObject(); + TQString propertyName = it.value().first(); + + int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); + if (indexOfProp > -1) + { + TQMetaProperty mProp = metaObject->property(indexOfProp); + mProp.write(obj, value); + } + } + } + + // Invoke all registered object methods for 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) + { + TQMetaMethod mMethod = metaObject->method(indexOfMethod); + //TQMetaMethod::Access access = mMethod.access(); + //TQMetaMethod::MethodType methType = mMethod.methodType(); + + bool success = false; + + // Handle registered slots taking one parameter. + if (mMethod.parameterTypes().size() == 1) + { + if (mMethod.parameterTypes().first() == value.typeName()) + { + success = invokeMethodWithValue(obj, mMethod, value); + } + } + // Handle registered slots taking zero parameters. + else + { + success = mMethod.invoke(obj, TQt::DirectConnection); + } + + if (success == false) + { + // TODO: Write a warning to the log if no success. + } + } + } + } + } +} + +#include <tqbitarray.h> +#include <tqbitmap.h> +#include <tqbrush.h> +#include <tqcursor.h> +#include <tqdatetime.h> +#include <tqfont.h> +#include <tqicon.h> +#include <tqkeysequence.h> +#include <tqlocale.h> +#include <tqpalette.h> +#include <tqpen.h> +#include <tqsizepolicy.h> +#include <tqtextformat.h> +#include <tqtextlength.h> +#include <tqurl.h> +#if TQT_VERSION >= 0x040600 + #include <tqmatrix4x4.h> + #include <tqvector2d.h> +#endif + +bool UiGuiSettings::invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value) +{ + 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>())); + } + + 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>())); + } + +#if TQT_VERSION >= 0x040600 + case TQVariant::Matrix4x4: + { + 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>())); + } + +#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>())); + } + + 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>())); + } + + case TQVariant::TextLength: + { + 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>())); + } + + case TQVariant::Vector3D: + { + 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>())); + } + +#endif + default: + { + return false; + } + } +} diff --git a/src/__TODO/UiGuiSettings.h b/src/__TODO/UiGuiSettings.h new file mode 100644 index 0000000..5068d52 --- /dev/null +++ b/src/__TODO/UiGuiSettings.h @@ -0,0 +1,94 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ + +#ifndef UIGUISETTINGS_H +#define UIGUISETTINGS_H + +#include <tqobject.h> +#include <tqstringlist.h> +/////#include <tqmultimap.h> + +class TQSettings; + + +class UiGuiSettings : public TQObject +{ + Q_OBJECT + + private: + UiGuiSettings(); + + static UiGuiSettings *_instance; + + public: + static UiGuiSettings* getInstance(); + + ~UiGuiSettings(); + + bool registerObjectProperty(TQObject *obj, const TQString &propertyName, + const TQString &settingName); + bool registerObjectPropertyRecursive(TQObject *obj); + bool setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName, + const TQString &settingName); + bool setObjectPropertyToSettingValueRecursive(TQObject *obj); + bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName, + const TQString &settingName); + bool setSettingToObjectPropertyValueRecursive(TQObject *obj); + bool registerObjectSlot(TQObject *obj, const TQString &slotName, + const TQString &settingName); + TQVariant getValueByName(TQString settingName); + TQStringList getAvailableTranslations(); + + public slots: + void setValueByName(const TQString &settingName, const TQVariant &value); + void unregisterObjectProperty(TQObject *obj); + void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "", + const TQString &settingName = ""); + + protected: + bool initSettings(); + bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value); + + bool checkCustomPropertiesAndCallFunction(TQObject * obj, + bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName, + const TQString &settingName)); + + private slots: + void handleObjectPropertyChange(); + + private: + void readAvailableTranslations(); + + //! Stores the mnemonics of the available translations. + TQStringList _availableTranslations; + + //! The settings file. + TQSettings *_qsettings; + + //! Maps an TQObject to a string list containing the property name and the associated setting + // name. + TQMap<TQObject*, TQStringList> _registeredObjectProperties; + + //! Maps TQObjects to a string list containing the method name and the associated setting name. + TQMultiMap<TQObject*, TQStringList> _registeredObjectSlots; + + TQString _indenterDirctoryStr; +}; + +#endif // UIGUISETTINGS_H diff --git a/src/__TODO/UiGuiSettingsDialog.cpp b/src/__TODO/UiGuiSettingsDialog.cpp new file mode 100644 index 0000000..8bfe0e5 --- /dev/null +++ b/src/__TODO/UiGuiSettingsDialog.cpp @@ -0,0 +1,205 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ + +#include "UiGuiSettingsDialog.h" +#include "ui_UiGuiSettingsDialog.h" + +#include "UiGuiSettings.h" + +/*! + \class UiGuiSettingsDialog + \ingroup grp_Settings + \brief Displays a dialog window with settings for UniversalIndentGUI +*/ + +/*! + \brief The constructor calls the setup function for the ui created by uic. +*/ +UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget *parent, + TQSharedPointer<UiGuiSettings> settings) : + TQDialog(parent) +{ + // Remember pointer to the UiGuiSettings object. + _settings = settings; + + // Init the user interface created by the UIC. + _settingsDialogForm = new Ui::SettingsDialog(); + _settingsDialogForm->setupUi(this); + + //TODO: This call has to be removed when the properties for the highlighters can be set + // with the settings dialog. + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip( + "(Will be implemented soon)" + + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip()); + + // Connect the accepted signal to own function, to write values back to the UiGuiSettings object. + connect(this, SIGNAL(accepted()), this, SLOT(writeWidgetValuesToSettings())); + + // Init the language selection combobox. + initTranslationSelection(); +} + +/*! + \brief By calling this function the combobox for selecting the application language will + be initialized. + + Also the translation itself will be reinitialized. + */ +void UiGuiSettingsDialog::initTranslationSelection() +{ + // First empty the combo box. + _settingsDialogForm->languageSelectionComboBox->clear(); + + // Now add an entry into the box for every language short. + foreach(TQString languageShort, _settings->getAvailableTranslations()) + { + // Identify the language mnemonic and set the full name. + if (languageShort == "en") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("English")); + } + else if (languageShort == "fr") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("French")); + } + else if (languageShort == "de") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("German")); + } + else if (languageShort == "zh_TW") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("Chinese (Taiwan)")); + } + else if (languageShort == "ja") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("Japanese")); + } + else if (languageShort == "ru") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("Russian")); + } + else if (languageShort == "uk") + { + _settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-" + + languageShort + ".png")), tr("Ukrainian")); + } + else + { + _settingsDialogForm->languageSelectionComboBox->addItem(tr( + "Unknown language mnemonic ") + languageShort); + } + } +} + +/*! + \brief Displays the dialog by calling the dialogs exec function. + + Before it gets all the values needed from the UiGuiSettings object. + */ +int UiGuiSettingsDialog::showDialog() +{ + // Init all settings dialog objects with values from settings. + _settings->setObjectPropertyToSettingValueRecursive(this); + + // Execute the dialog. + return exec(); +} + +/*! + \brief This slot is called when the dialog box is closed by pressing the Ok button. + + Writes all settings to the UiGuiSettings object. + */ +void UiGuiSettingsDialog::writeWidgetValuesToSettings() +{ + // Write settings dialog object values to settings. + _settings->setSettingToObjectPropertyValueRecursive(this); +} + +/*! + \brief Catches language change events and retranslates all needed widgets. + */ +void UiGuiSettingsDialog::changeEvent(TQEvent *event) +{ + if (event->type() == TQEvent::LanguageChange) + { + _settingsDialogForm->retranslateUi(this); + // If this is not explicit set here, TQt < 4.3.0 does not translate the buttons. + _settingsDialogForm->buttonBox->setStandardButtons( + TQDialogButtonBox::Cancel | TQDialogButtonBox::NoButton | TQDialogButtonBox::Ok); + + //TODO: This has to be removed when the properties for the highlighters can be set. + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip( + "(Will be implemented soon)" + + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip()); + + TQStringList languageShortList = _settings->getAvailableTranslations(); + + // Now retranslate every entry in the language selection box. + for (int i = 0; i < languageShortList.size(); i++) + { + TQString languageShort = languageShortList.at(i); + + // Identify the language mnemonic and set the full name. + if (languageShort == "en") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("English")); + } + else if (languageShort == "fr") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("French")); + } + else if (languageShort == "de") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("German")); + } + else if (languageShort == "zh_TW") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Chinese (Taiwan)")); + } + else if (languageShort == "ja") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Japanese")); + } + else if (languageShort == "ru") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Russian")); + } + else if (languageShort == "uk") + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Ukrainian")); + } + else + { + _settingsDialogForm->languageSelectionComboBox->setItemText(i, + tr("Unknown language mnemonic ") + languageShort); + } + } + } + else + { + TQWidget::changeEvent(event); + } +} diff --git a/src/__TODO/UiGuiSettingsDialog.h b/src/__TODO/UiGuiSettingsDialog.h new file mode 100644 index 0000000..8dc9543 --- /dev/null +++ b/src/__TODO/UiGuiSettingsDialog.h @@ -0,0 +1,55 @@ +/*************************************************************************** +* Copyright (C) 2006-2012 by Thomas Schweitzer * +* thomas-schweitzer(at)arcor.de * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2.0 as * +* published by the Free Software Foundation. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program in the file LICENSE.GPL; if not, write to the * +* Free Software Foundation, Inc., * +* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * +***************************************************************************/ + +#ifndef UIGUISETTINGSDIALOG_H +#define UIGUISETTINGSDIALOG_H + +#include <tntqdialog.h> + +#include "UiGuiSettings.h" + +namespace Ui +{ + class SettingsDialog; +} + + +class UiGuiSettingsDialog : public TQDialog +{ + Q_OBJECT + + public: + UiGuiSettingsDialog(TQWidget *parent, TQSharedPointer<UiGuiSettings> settings); + + public slots: + int showDialog(); + + private slots: + void writeWidgetValuesToSettings(); + + private: + Ui::SettingsDialog *_settingsDialogForm; + + void changeEvent(TQEvent *event); + void initTranslationSelection(); + + TQSharedPointer<UiGuiSettings> _settings; +}; + +#endif // UIGUISETTINGSDIALOG_H diff --git a/src/__TODO/UiGuiSettingsDialog.ui b/src/__TODO/UiGuiSettingsDialog.ui new file mode 100755 index 0000000..2f96561 --- /dev/null +++ b/src/__TODO/UiGuiSettingsDialog.ui @@ -0,0 +1,625 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>SettingsDialog</class> + <widget class="TQDialog" name="SettingsDialog"> + <property name="windowModality"> + <enum>TQt::ApplicationModal</enum> + </property> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>503</width> + <height>336</height> + </rect> + </property> + <property name="windowTitle"> + <string>Settings</string> + </property> + <property name="windowIcon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/preferences-system.png</normaloff>:/mainWindow/preferences-system.png</iconset> + </property> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQTabWidget" name="tabWidget"> + <property name="currentIndex"> + <number>0</number> + </property> + <widget class="TQWidget" name="tab"> + <attribute name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/settingsDialog/applications-system.png</normaloff>:/settingsDialog/applications-system.png</iconset> + </attribute> + <attribute name="title"> + <string>Common</string> + </attribute> + <layout class="TQVBoxLayout"> + <item> + <layout class="TQHBoxLayout"> + <item> + <widget class="TQLabel" name="label"> + <property name="toolTip"> + <string>Displays all available translations for UniversalIndentGui and lets you choose one.</string> + </property> + <property name="text"> + <string>Application language</string> + </property> + <property name="buddy"> + <cstring>languageSelectionComboBox</cstring> + </property> + </widget> + </item> + <item> + <widget class="TQComboBox" name="languageSelectionComboBox"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>Displays all available translations for UniversalIndentGui and lets you choose one.</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">language</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">currentIndex</string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <widget class="TQCheckBox" name="loadLastOpenedFileOnStartupComboBox"> + <property name="toolTip"> + <string>If selected opens the source code file on startup that was opened last time.</string> + </property> + <property name="text"> + <string>Automatically open last file on startup</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">loadLastSourceCodeFileOnStartup</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <widget class="TQCheckBox" name="enableIndenterParameterTooltipsCheckBox"> + <property name="toolTip"> + <string>If checked, tool tips will show up if the mouse cursor remains over an indenter parameter for a while.</string> + </property> + <property name="text"> + <string>Enable Parameter Tooltips</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">indenterParameterTooltipsEnabled</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <layout class="TQHBoxLayout"> + <item> + <widget class="TQLabel" name="labelRecentlyOpenedListSize"> + <property name="toolTip"> + <string>Sets how many files should be remembered in the list of recently opened files.</string> + </property> + <property name="text"> + <string>Number of files in recently opened list</string> + </property> + </widget> + </item> + <item> + <widget class="TQSpinBox" name="recentlyOpenedListSizeSpinBox"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>Sets how many files should be remembered in the list of recently opened files.</string> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>30</number> + </property> + <property name="value"> + <number>1</number> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">recentlyOpenedListSize</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">value</string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <widget class="TQWidget" name="tab_2"> + <attribute name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/settingsDialog/accessories-text-editor.png</normaloff>:/settingsDialog/accessories-text-editor.png</iconset> + </attribute> + <attribute name="title"> + <string>Editor</string> + </attribute> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQCheckBox" name="whiteSpaceIsVisibleCheckBox"> + <property name="toolTip"> + <string>Enables or disables displaying of white space characters in the editor.</string> + </property> + <property name="text"> + <string>Display white space character (tabs, spaces, etc.)</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">whiteSpaceIsVisible</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <layout class="TQHBoxLayout"> + <item> + <widget class="TQLabel" name="labelTabWidth"> + <property name="toolTip"> + <string>Sets width in single spaces used for tabs</string> + </property> + <property name="statusTip"> + <string>Defines how many spaces should be displayed in the editor for one tab.</string> + </property> + <property name="text"> + <string>Displayed width of tabs</string> + </property> + </widget> + </item> + <item> + <widget class="TQSpinBox" name="tabWidthSpinBox"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>Defines how many spaces should be displayed in the editor for one tab character.</string> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>99</number> + </property> + <property name="value"> + <number>1</number> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">tabWidth</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">value</string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <widget class="TQWidget" name="tab_4"> + <attribute name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/mainWindow/system-software-update.png</normaloff>:/mainWindow/system-software-update.png</iconset> + </attribute> + <attribute name="title"> + <string>Network</string> + </attribute> + <layout class="TQVBoxLayout" name="verticalLayout"> + <item> + <widget class="TQCheckBox" name="checkForUpdateCheckBox"> + <property name="toolTip"> + <string>Checks whether a new version of UniversalIndentGUI exists on program start, but only once a day.</string> + </property> + <property name="text"> + <string>Check online for update on program start</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">CheckForUpdate</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <widget class="TQGroupBox" name="groupBox"> + <property name="title"> + <string/> + </property> + <layout class="TQVBoxLayout" name="verticalLayout_5"> + <item> + <widget class="TQCheckBox" name="enableProxyCheckBox"> + <property name="toolTip"> + <string>If checked, the made proxy settings will be applied for all network connections. Type of the used proxy is SOCKS5.</string> + </property> + <property name="text"> + <string>Enable proxy</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">ProxyEnabled</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <widget class="TQWidget" name="widget" native="true"> + <property name="enabled"> + <bool>false</bool> + </property> + <layout class="TQGridLayout" name="gridLayout"> + <item row="0" column="0"> + <widget class="TQLabel" name="label_2"> + <property name="text"> + <string>Host name:</string> + </property> + <property name="buddy"> + <cstring>proxyHostNameLineEdit</cstring> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="TQLineEdit" name="proxyHostNameLineEdit"> + <property name="toolTip"> + <string>Host name of the to be used proxy. E.g.: proxy.example.com</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">ProxyHostName</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">text</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="TQLabel" name="label_3"> + <property name="text"> + <string>Port:</string> + </property> + <property name="buddy"> + <cstring>proxyPortSpinBox</cstring> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="TQSpinBox" name="proxyPortSpinBox"> + <property name="toolTip"> + <string>Port number to connect to the before named proxy.</string> + </property> + <property name="alignment"> + <set>TQt::AlignRight|TQt::AlignTrailing|TQt::AlignVCenter</set> + </property> + <property name="buttonSymbols"> + <enum>TQAbstractSpinBox::NoButtons</enum> + </property> + <property name="maximum"> + <number>99999</number> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">ProxyPort</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">text</string> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="TQLabel" name="label_4"> + <property name="text"> + <string>User name:</string> + </property> + <property name="buddy"> + <cstring>proxyUserNameLineEdit</cstring> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="TQLineEdit" name="proxyUserNameLineEdit"> + <property name="toolTip"> + <string>If the proxy needs authentification, enter the login name here.</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">ProxyUserName</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">text</string> + </property> + </widget> + </item> + <item row="3" column="0"> + <widget class="TQLabel" name="label_6"> + <property name="text"> + <string>Password:</string> + </property> + <property name="buddy"> + <cstring>proxyPasswordLineEdit</cstring> + </property> + </widget> + </item> + <item row="3" column="1"> + <widget class="TQLineEdit" name="proxyPasswordLineEdit"> + <property name="toolTip"> + <string>If the proxy needs authentification, enter the password here.</string> + </property> + <property name="echoMode"> + <enum>TQLineEdit::Password</enum> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">ProxyPassword</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">text</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <widget class="TQWidget" name="tab_3"> + <attribute name="icon"> + <iconset resource="../resources/Icons.qrc"> + <normaloff>:/settingsDialog/syntax-highlight.png</normaloff>:/settingsDialog/syntax-highlight.png</iconset> + </attribute> + <attribute name="title"> + <string>Syntax Highlighting</string> + </attribute> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQCheckBox" name="enableSyntaxHighlightningCheckBox"> + <property name="toolTip"> + <string>By enabling special key words of the source code are highlighted.</string> + </property> + <property name="text"> + <string>Enable syntax highlighting</string> + </property> + <property name="connectedSettingName" stdset="0"> + <string notr="true">SyntaxHighlightingEnabled</string> + </property> + <property name="connectedPropertyName" stdset="0"> + <string notr="true">checked</string> + </property> + </widget> + </item> + <item> + <widget class="TQGroupBox" name="groupBoxSyntaxHighlighterProperties"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Lets you make settings for all properties of the available syntax highlighters, like font and color.</string> + </property> + <property name="title"> + <string>Highlighter settings</string> + </property> + <layout class="TQHBoxLayout"> + <item> + <widget class="TQListWidget" name="listWidget"> + <property name="currentRow"> + <number>-1</number> + </property> + </widget> + </item> + <item> + <widget class="TQListWidget" name="listWidget_2"> + <property name="currentRow"> + <number>-1</number> + </property> + </widget> + </item> + <item> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQPushButton" name="pushButton_2"> + <property name="toolTip"> + <string>Set the font for the current selected highlighter property.</string> + </property> + <property name="text"> + <string>Set Font</string> + </property> + </widget> + </item> + <item> + <widget class="TQPushButton" name="pushButton"> + <property name="toolTip"> + <string>Set the color for the current selected highlighter property.</string> + </property> + <property name="text"> + <string>Set Color</string> + </property> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <spacer> + <property name="orientation"> + <enum>TQt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + </widget> + </item> + <item> + <widget class="TQDialogButtonBox" name="buttonBox"> + <property name="orientation"> + <enum>TQt::Horizontal</enum> + </property> + <property name="standardButtons"> + <set>TQDialogButtonBox::Cancel|TQDialogButtonBox::Ok</set> + </property> + </widget> + </item> + </layout> + </widget> + <resources> + <include location="../resources/Icons.qrc"/> + </resources> + <connections> + <connection> + <sender>buttonBox</sender> + <signal>accepted()</signal> + <receiver>SettingsDialog</receiver> + <slot>accept()</slot> + <hints> + <hint type="sourcelabel"> + <x>250</x> + <y>316</y> + </hint> + <hint type="destinationlabel"> + <x>153</x> + <y>236</y> + </hint> + </hints> + </connection> + <connection> + <sender>buttonBox</sender> + <signal>rejected()</signal> + <receiver>SettingsDialog</receiver> + <slot>reject()</slot> + <hints> + <hint type="sourcelabel"> + <x>327</x> + <y>316</y> + </hint> + <hint type="destinationlabel"> + <x>282</x> + <y>236</y> + </hint> + </hints> + </connection> + <connection> + <sender>enableProxyCheckBox</sender> + <signal>toggled(bool)</signal> + <receiver>widget</receiver> + <slot>setEnabled(bool)</slot> + <hints> + <hint type="sourcelabel"> + <x>73</x> + <y>68</y> + </hint> + <hint type="destinationlabel"> + <x>76</x> + <y>95</y> + </hint> + </hints> + </connection> + </connections> +</ui> diff --git a/src/__TODO/UiGuiSystemInfo.cpp b/src/__TODO/UiGuiSystemInfo.cpp new file mode 100644 index 0000000..5456519 --- /dev/null +++ b/src/__TODO/UiGuiSystemInfo.cpp @@ -0,0 +1,317 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UiGuiSystemInfo.h" + +#include <tntqstring.h> +#include <tqsysinfo.h> +#include <tntqprocess.h> +#include <tntqfile.h> + +UiGuiSystemInfo::UiGuiSystemInfo() +{ +} + +/*! + \brief Returns the operating system UiGUI is currently running on as one string. + + The String contains name and version of the os. E.g. Linux Ubuntu 9.04. + */ +TQString UiGuiSystemInfo::getOperatingSystem() +{ + TQString operatingSystemString = ""; + +#if defined (Q_WS_WIN) + switch (TQSysInfo::WindowsVersion) + { + case TQSysInfo::WV_32s: + { + operatingSystemString = "Windows 3.1 with Win 32s"; + break; + } + + case TQSysInfo::WV_95: + { + operatingSystemString = "Windows 95"; + break; + } + + case TQSysInfo::WV_98: + { + operatingSystemString = "Windows 98"; + break; + } + + case TQSysInfo::WV_Me: + { + operatingSystemString = "Windows Me"; + break; + } + + case TQSysInfo::WV_NT: + { + operatingSystemString = "Windows NT (operating system version 4.0)"; + break; + } + + case TQSysInfo::WV_2000: + { + operatingSystemString = "Windows 2000 (operating system version 5.0)"; + break; + } + + case TQSysInfo::WV_XP: + { + operatingSystemString = "Windows XP (operating system version 5.1)"; + break; + } + + case TQSysInfo::WV_2003: + { + operatingSystemString = + "Windows Server 2003, Windows Server 2003 R2, Windows Home Server, Windows XP Professional x64 Edition (operating system version 5.2)"; + break; + } + + case TQSysInfo::WV_VISTA: + { + operatingSystemString = "Windows Vista, Windows Server 2008 (operating system version 6.0)"; + break; + } + + case TQSysInfo::WV_WINDOWS7: + { + operatingSystemString = "Windows 7 (operating system version 6.1)"; + break; + } + + case TQSysInfo::WV_CE: + { + operatingSystemString = "Windows CE"; + break; + } + + case TQSysInfo::WV_CENET: + { + operatingSystemString = "Windows CE .NET"; + break; + } + + case TQSysInfo::WV_CE_5: + { + operatingSystemString = "Windows CE 5.x"; + break; + } + + case TQSysInfo::WV_CE_6: + { + operatingSystemString = "Windows CE 6.x"; + break; + } + + default: + { + operatingSystemString = "Unknown Windows operating system."; + break; + } + } +#elif defined (Q_WS_MAC) + switch (TQSysInfo::MacintoshVersion) + { + case TQSysInfo::MV_9: + { + operatingSystemString = "Mac OS 9 (unsupported)"; + break; + } + + case TQSysInfo::MV_10_0: + { + operatingSystemString = "Mac OS X 10.0 Cheetah (unsupported)"; + break; + } + + case TQSysInfo::MV_10_1: + { + operatingSystemString = "Mac OS X 10.1 Puma (unsupported)"; + break; + } + + case TQSysInfo::MV_10_2: + { + operatingSystemString = "Mac OS X 10.2 Jaguar (unsupported)"; + break; + } + + case TQSysInfo::MV_10_3: + { + operatingSystemString = "Mac OS X 10.3 Panther"; + break; + } + + case TQSysInfo::MV_10_4: + { + operatingSystemString = "Mac OS X 10.4 Tiger"; + break; + } + + case TQSysInfo::MV_10_5: + { + operatingSystemString = "Mac OS X 10.5 Leopard"; + break; + } + + case TQSysInfo::MV_10_6: + { + operatingSystemString = "Mac OS X 10.6 Snow Leopard"; + break; + } + + case TQSysInfo::MV_Unknown: + { + operatingSystemString = "An unknown and currently unsupported platform"; + break; + } + + default: + { + operatingSystemString = "Unknown Mac operating system."; + break; + } + } +#else + //TODO: Detect Unix, Linux etc. distro as described on + // http://www.novell.com/coolsolutions/feature/11251.html + operatingSystemString = "Linux"; + TQProcess process; + + process.start("uname -s"); + bool result = process.waitForFinished(1000); + TQString os = process.readAllStandardOutput().trimmed(); + + process.start("uname -r"); + result = process.waitForFinished(1000); + TQString rev = process.readAllStandardOutput().trimmed(); + + process.start("uname -m"); + result = process.waitForFinished(1000); + TQString mach = process.readAllStandardOutput().trimmed(); + + if (os == "SunOS") + { + os = "Solaris"; + + process.start("uname -p"); + result = process.waitForFinished(1000); + TQString arch = process.readAllStandardOutput().trimmed(); + + process.start("uname -v"); + result = process.waitForFinished(1000); + TQString timestamp = process.readAllStandardOutput().trimmed(); + + operatingSystemString = os + " " + rev + " (" + arch + " " + timestamp + ")"; + } + else if (os == "AIX") + { + process.start("oslevel -r"); + result = process.waitForFinished(1000); + TQString oslevel = process.readAllStandardOutput().trimmed(); + + operatingSystemString = os + "oslevel " + oslevel; + } + else if (os == "Linux") + { + TQString dist; + TQString pseudoname; + TQString kernel = rev; + + if (TQFile::exists("/etc/redhat-release")) + { + dist = "RedHat"; + + process.start("sh -c \"cat /etc/redhat-release | sed s/.*\\(// | sed s/\\)//\""); + result = process.waitForFinished(1000); + pseudoname = process.readAllStandardOutput().trimmed(); + + process.start("sh -c \"cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//\""); + result = process.waitForFinished(1000); + rev = process.readAllStandardOutput().trimmed(); + } + else if (TQFile::exists("/etc/SUSE-release")) + { + process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' '| sed s/VERSION.*//\""); + result = process.waitForFinished(1000); + dist = process.readAllStandardOutput().trimmed(); + + process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' ' | sed s/.*=\\ //\""); + result = process.waitForFinished(1000); + rev = process.readAllStandardOutput().trimmed(); + } + else if (TQFile::exists("/etc/mandrake-release")) + { + dist = "Mandrake"; + + process.start("sh -c \"cat /etc/mandrake-release | sed s/.*\\(// | sed s/\\)//\""); + result = process.waitForFinished(1000); + pseudoname = process.readAllStandardOutput().trimmed(); + + process.start("sh -c \"cat /etc/mandrake-release | sed s/.*release\\ // | sed s/\\ .*//\""); + result = process.waitForFinished(1000); + rev = process.readAllStandardOutput().trimmed(); + } + else if (TQFile::exists("/etc/lsb-release")) + { + dist = "Ubuntu"; + + TQString processCall = + "sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_RELEASE=// | sed s/\\ .*//\""; + process.start(processCall); + result = process.waitForFinished(1000); + rev = process.readAllStandardOutput().trimmed(); + TQString errorStr = process.readAllStandardError(); + + process.start( + "sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_CODENAME=// | sed s/\\ .*//\""); + result = process.waitForFinished(1000); + pseudoname = process.readAllStandardOutput().trimmed(); + } + else if (TQFile::exists("/etc/debian_version")) + { + dist = "Debian"; + + process.start("cat /etc/debian_version"); + result = process.waitForFinished(1000); + dist += process.readAllStandardOutput().trimmed(); + + rev = ""; + } + + if (TQFile::exists("/etc/UnitedLinux-release")) + { + process.start("sh -c \"cat /etc/UnitedLinux-release | tr '\\n' ' ' | sed s/VERSION.*//\""); + result = process.waitForFinished(1000); + dist += process.readAllStandardOutput().trimmed(); + } + + operatingSystemString = os + " " + dist + " " + rev + " (" + pseudoname + " " + kernel + " " + + mach + ")"; + } +#endif + + return operatingSystemString; +} diff --git a/src/__TODO/UiGuiSystemInfo.h b/src/__TODO/UiGuiSystemInfo.h new file mode 100644 index 0000000..4d6405d --- /dev/null +++ b/src/__TODO/UiGuiSystemInfo.h @@ -0,0 +1,35 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UIGUISYSTEMINFO_H +#define UIGUISYSTEMINFO_H + +class TQString; + + +class UiGuiSystemInfo +{ + public: + static TQString getOperatingSystem(); + + private: + UiGuiSystemInfo(); +}; + +#endif // UIGUISYSTEMINFO_H diff --git a/src/__TODO/UpdateCheckDialog.cpp b/src/__TODO/UpdateCheckDialog.cpp new file mode 100644 index 0000000..5c9b1e3 --- /dev/null +++ b/src/__TODO/UpdateCheckDialog.cpp @@ -0,0 +1,356 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "UpdateCheckDialog.h" +#include "ui_UpdateCheckDialog.h" + +#include "UiGuiSettings.h" +#include "UiGuiVersion.h" + +#include <tntqmessagebox.h> +#include <tqdesktopservices.h> +#include <tqnetworkaccessmanager.h> +#include <tntqtimer.h> +#include <tqdate.h> +#include <tntqurl.h> +#include <tqregexpvalidator.h> +#include <tqnetworkrequest.h> +#include <tqnetworkreply.h> +#include <tqnetworkproxy.h> + +/*! + \class UpdateCheckDialog + \ingroup grp_MainWindow + \brief UpdateCheckDialog is a dialog widget that contains functions + for online checking for a new version of UniversalIndentGUI. +*/ + +/*! + \brief Initializes member variables and stores the version of UiGui and a pointer to the _settings object. + */ +UpdateCheckDialog::UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent) : + TQDialog(parent), _manualUpdateRequested(false), _currentNetworkReply(NULL), + _roleOfClickedButton(TQDialogButtonBox::InvalidRole) +{ + _updateCheckDialogForm = new Ui::UpdateCheckDialog(); + _updateCheckDialogForm->setupUi(this); + + // Create object for _networkAccessManager request and connect it with the request return handler. + _networkAccessManager = new TQNetworkAccessManager(this); + connect(_networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this, + SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*))); + + // Create a timer object used for the progress bar. + _updateCheckProgressTimer = new TQTimer(this); + _updateCheckProgressTimer->setInterval(5); + connect(_updateCheckProgressTimer, SIGNAL(timeout()), this, SLOT(updateUpdateCheckProgressBar())); + _updateCheckProgressCounter = 0; + + // Connect the dialogs buttonbox with a button click handler. + connect(_updateCheckDialogForm->buttonBox, SIGNAL(clicked(TQAbstractButton*)), this, + SLOT(handleUpdateCheckDialogButtonClicked(TQAbstractButton*))); + + settings->registerObjectSlot(this, "initProxySettings()", "ProxyEnabled"); + settings->registerObjectSlot(this, "initProxySettings()", "ProxyHostName"); + settings->registerObjectSlot(this, "initProxySettings()", "ProxyPort"); + settings->registerObjectSlot(this, "initProxySettings()", "ProxyUserName"); + settings->registerObjectSlot(this, "initProxySettings()", "ProxyPassword"); + + _settings = settings; + + initProxySettings(); + + // This dialog is always modal. + setModal(true); +} + +/*! + \brief On destroy cancels any currently running network request. + */ +UpdateCheckDialog::~UpdateCheckDialog() +{ + disconnect(_networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this, + SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*))); + if (_currentNetworkReply != NULL) + { + _currentNetworkReply->abort(); + } +} + +/*! + \brief This slot should be called, if an update check is manually invoked. + + In difference to the automatic update check, during manual update check request + a modal progress indicator dialog will be shown. + */ +void UpdateCheckDialog::checkForUpdateAndShowDialog() +{ + _manualUpdateRequested = true; + getPadXMLFile(); + showCheckingForUpdateDialog(); +} + +/*! + \brief This slot should be called, if an update check is automatically invoked. + + An automatic invoked update check should run in background, so the user + gets not interrupted by a dialog box. + */ +void UpdateCheckDialog::checkForUpdate() +{ + _manualUpdateRequested = false; + getPadXMLFile(); +} + +/*! + \brief This function tries to download the UniversalIndentGui pad file from the SourceForge server. + */ +void UpdateCheckDialog::getPadXMLFile() +{ + //_networkAccessManager->setHost("universalindent.sourceforge.net"); + //_networkAccessManager->get("/universalindentgui_pad.xml"); + _currentNetworkReply = _networkAccessManager->get(TQNetworkRequest(TQUrl( + "http://universalindent.sourceforge.net/universalindentgui_pad.xml"))); +} + +/*! + \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. + + Shows a message if check was successful or not. Offers the user to go to the + download page if a newer version exists. In case of an error during update + check, a message box with the error will be displayed. + */ +void UpdateCheckDialog::checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply) +{ + Q_ASSERT(_currentNetworkReply == networkReply); + + // Stop the progress bar timer. + _updateCheckProgressTimer->stop(); + + if (networkReply->error() == TQNetworkReply::NoError) + { + // Try to find the version string. + TQString returnedString = networkReply->readAll(); + int leftPosition = returnedString.indexOf("<Program_Version>"); + int rightPosition = returnedString.indexOf("</Program_Version>"); + + // If the version string could be found in the returned string, show an update dialog and set + // last update check date. + if (leftPosition != -1 && rightPosition != -1) + { + // Get the pure version string from returned string. + returnedString = returnedString.mid(leftPosition + 17, rightPosition - (leftPosition + 17)); + + // Create integer values from the version strings. + int versionOnServerInt = convertVersionStringToNumber(returnedString); + int currentVersionInt = convertVersionStringToNumber(PROGRAM_VERSION_STRING); + + // Only show update dialog, if the current version number is lower than the one received from + // the server. + if (versionOnServerInt > currentVersionInt && currentVersionInt >= 0 && + versionOnServerInt >= 0) + { + // Show message box whether to download the new version. + showNewVersionAvailableDialog(returnedString); + + // If yes clicked, open the download url in the default browser. + if (_roleOfClickedButton == TQDialogButtonBox::YesRole) + { + TQDesktopServices::openUrl(TQUrl( + "_networkAccessManager://sourceforge.net/project/showfiles.php?group_id=167482")); + } + } + else if (_manualUpdateRequested) + { + showNoNewVersionAvailableDialog(); + } + // Set last update check date. + _settings->setValueByName("LastUpdateCheck", TQDate::currentDate()); + } + // In the returned string, the version string could not be found. + else + { + TQMessageBox::warning(this, tr("Update check error"), tr( + "There was an error while trying to check for an update! The retrieved file did not contain expected content.")); + } + } + // If there was some error while trying to retrieve the update info from server and not cancel was + // pressed. + else if (_roleOfClickedButton != TQDialogButtonBox::RejectRole) + { + TQMessageBox::warning(this, tr("Update check error"), + tr("There was an error while trying to check for an update! Error was : %1").arg( + networkReply->errorString())); + hide(); + } + _manualUpdateRequested = false; + networkReply->deleteLater(); + _currentNetworkReply = NULL; +} + +/*! + \brief Displays the progress bar during update check. + + For displaying activity during update check, a timer is started to + updated the progress bar. The user can press a cancel button to + stop the update check. + */ +void UpdateCheckDialog::showCheckingForUpdateDialog() +{ + // Reset the progress bar. + _updateCheckProgressCounter = 0; + _updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter); + _updateCheckDialogForm->progressBar->setInvertedAppearance(false); + + _updateCheckProgressTimer->start(); + _updateCheckDialogForm->progressBar->show(); + setWindowTitle(tr("Checking for update...")); + _updateCheckDialogForm->label->setText(tr("Checking whether a newer version is available")); + _updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Cancel); + show(); +} + +/*! + \brief Displays the dialog with info about the new available version. + */ +void UpdateCheckDialog::showNewVersionAvailableDialog(TQString newVersion) +{ + _updateCheckDialogForm->progressBar->hide(); + setWindowTitle(tr("Update available")); + _updateCheckDialogForm->label->setText(tr( + "A newer version of UniversalIndentGUI is available.\nYour version is %1. New version is %2.\nDo you want to go to the download website?").arg( + PROGRAM_VERSION_STRING).arg(newVersion)); + _updateCheckDialogForm->buttonBox->setStandardButtons( + TQDialogButtonBox::No | TQDialogButtonBox::NoButton | TQDialogButtonBox::Yes); + exec(); +} + +/*! + \brief Displays the dialog, that no new version is available. + */ +void UpdateCheckDialog::showNoNewVersionAvailableDialog() +{ + _updateCheckDialogForm->progressBar->hide(); + setWindowTitle(tr("No new update available")); + _updateCheckDialogForm->label->setText(tr( + "You already have the latest version of UniversalIndentGUI.")); + _updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Ok); + exec(); +} + +/*! + \brief This slot is called, when a button in the dialog is clicked. + + If the clicked button was the cancel button, the user wants to cancel + the update check. So the _networkAccessManager request is aborted and the timer for the + progress bar animation is stopped. + + In any case if a button is clicked, the dialog box will be closed. + */ +void UpdateCheckDialog::handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton) +{ + _roleOfClickedButton = _updateCheckDialogForm->buttonBox->buttonRole(clickedButton); + + if (_roleOfClickedButton == TQDialogButtonBox::RejectRole) + { + // Abort the _networkAccessManager request. + _currentNetworkReply->abort(); + // Stop the progress bar timer. + _updateCheckProgressTimer->stop(); + } + + accept(); +} + +/*! + \brief This slot is responsible for the animation of the update check progress bar. + */ +void UpdateCheckDialog::updateUpdateCheckProgressBar() +{ + // Depending on the progress bar direction, decrease or increase the progressbar value. + if (_updateCheckDialogForm->progressBar->invertedAppearance()) + { + _updateCheckProgressCounter--; + } + else + { + _updateCheckProgressCounter++; + } + + // If the progress bar reaches 0 or 100 as value, swap the animation direction. + if (_updateCheckProgressCounter == 0 || _updateCheckProgressCounter == 100) + { + _updateCheckDialogForm->progressBar->setInvertedAppearance( + !_updateCheckDialogForm->progressBar->invertedAppearance()); + } + + // Update the progress bar value. + _updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter); +} + +/*! + \brief Converts the as string given version \a versionString to an integer number. + + The \a versionString must have the format x.x.x where each x represents a number + of a maximum of 999. If the input format is wrong, -1 will be returned.The first + number will be multiplied by 1000000 the second by 1000 and then all three will + be summarized. + + Thus for example 12.5.170 will result in 12005170. + */ +int UpdateCheckDialog::convertVersionStringToNumber(TQString versionString) +{ + int versionInteger = 0; + int pos = 0; + + TQRegExp regEx("\\d{1,3}.\\d{1,3}.\\d{1,3}"); + TQRegExpValidator validator(regEx, NULL); + + if (validator.validate(versionString, pos) == TQValidator::Acceptable) + { + TQStringList versionNumberStringList = versionString.split("."); + versionInteger = versionNumberStringList.at(0).toInt() * 1000000; + versionInteger += versionNumberStringList.at(1).toInt() * 1000; + versionInteger += versionNumberStringList.at(2).toInt(); + } + else + { + versionInteger = -1; + } + + return versionInteger; +} + +void UpdateCheckDialog::initProxySettings() +{ + 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)); + } + else + { + _networkAccessManager->setProxy(TQNetworkProxy()); + } +} diff --git a/src/__TODO/UpdateCheckDialog.h b/src/__TODO/UpdateCheckDialog.h new file mode 100644 index 0000000..6f1116b --- /dev/null +++ b/src/__TODO/UpdateCheckDialog.h @@ -0,0 +1,74 @@ +/*************************************************************************** + * Copyright (C) 2006-2012 by Thomas Schweitzer * + * thomas-schweitzer(at)arcor.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License version 2.0 as * + * published by the Free Software Foundation. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program in the file LICENSE.GPL; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef UPDATECHECKDIALOG_H +#define UPDATECHECKDIALOG_H + +#include <tntqdialog.h> +#include <tqdialogbuttonbox.h> + +class UiGuiSettings; +namespace Ui +{ + class UpdateCheckDialog; +} + +class TQTimer; +class TQDesktopServices; +class TQNetworkAccessManager; +class TQNetworkReply; + + +class UpdateCheckDialog : public TQDialog +{ + Q_OBJECT + + public: + UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent = NULL); + ~UpdateCheckDialog(); + + public slots: + void checkForUpdateAndShowDialog(); + void checkForUpdate(); + + private slots: + void checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply); + void handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton); + void updateUpdateCheckProgressBar(); + void initProxySettings(); + + private: + Ui::UpdateCheckDialog *_updateCheckDialogForm; + + void getPadXMLFile(); + void showCheckingForUpdateDialog(); + void showNewVersionAvailableDialog(TQString newVersion); + void showNoNewVersionAvailableDialog(); + int convertVersionStringToNumber(TQString versionString); + + TQSharedPointer<UiGuiSettings> _settings; + bool _manualUpdateRequested; + TQNetworkAccessManager *_networkAccessManager; + TQNetworkReply *_currentNetworkReply; + TQDialogButtonBox::ButtonRole _roleOfClickedButton; + TQTimer *_updateCheckProgressTimer; + int _updateCheckProgressCounter; +}; + +#endif // UPDATECHECKDIALOG_H diff --git a/src/__TODO/UpdateCheckDialog.ui b/src/__TODO/UpdateCheckDialog.ui new file mode 100755 index 0000000..ebfc8bb --- /dev/null +++ b/src/__TODO/UpdateCheckDialog.ui @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>UpdateCheckDialog</class> + <widget class="TQDialog" name="UpdateCheckDialog"> + <property name="windowModality"> + <enum>TQt::WindowModal</enum> + </property> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>323</width> + <height>108</height> + </rect> + </property> + <property name="windowTitle"> + <string>Checking for update...</string> + </property> + <layout class="TQVBoxLayout"> + <item> + <widget class="TQLabel" name="label"> + <property name="text"> + <string>Checking whether a newer version is available</string> + </property> + </widget> + </item> + <item> + <widget class="TQProgressBar" name="progressBar"> + <property name="value"> + <number>0</number> + </property> + <property name="textVisible"> + <bool>false</bool> + </property> + </widget> + </item> + <item> + <widget class="TQDialogButtonBox" name="buttonBox"> + <property name="standardButtons"> + <set>TQDialogButtonBox::Cancel</set> + </property> + <property name="centerButtons"> + <bool>true</bool> + </property> + </widget> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> |