diff --git a/QGCExternalLibs.pri b/QGCExternalLibs.pri index 226dbef42a74e18ab2326387ba56efe63f81deb4..cbece537ccb67dd03bb8e1d624c7a29093131657 100644 --- a/QGCExternalLibs.pri +++ b/QGCExternalLibs.pri @@ -302,16 +302,8 @@ DEFINES += NOMINMAX # # [REQUIRED] OPMapControl library from OpenPilot. Provides 2D mapping functionality. # -include(libs/utils/utils_external.pri) include(libs/opmapcontrol/opmapcontrol_external.pri) -DEPENDPATH += \ - libs/utils \ - libs/utils/src \ - libs/opmapcontrol \ - libs/opmapcontrol/src \ - libs/opmapcontrol/src/mapwidget - INCLUDEPATH += \ libs/utils \ libs \ diff --git a/libs/opmapcontrol/src/core/cache.cpp b/libs/opmapcontrol/src/core/cache.cpp index 712efafbd4ab41d064b6755f42eea504e194d0df..0a00669873c402c7ca5b492b2105c09d1e1ce150 100644 --- a/libs/opmapcontrol/src/core/cache.cpp +++ b/libs/opmapcontrol/src/core/cache.cpp @@ -25,7 +25,6 @@ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "cache.h" -#include "utils/pathutils.h" #include namespace core { diff --git a/libs/utils/abstractprocess.h b/libs/utils/abstractprocess.h deleted file mode 100644 index 68f6a45d11ccb57ccc13a12e24f4906b9e9574ff..0000000000000000000000000000000000000000 --- a/libs/utils/abstractprocess.h +++ /dev/null @@ -1,78 +0,0 @@ -/** - ****************************************************************************** - * - * @file abstractprocess.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef ABSTRACTPROCESS_H -#define ABSTRACTPROCESS_H - -#include "utils_global.h" - -#include - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT AbstractProcess -{ -public: - AbstractProcess() {} - virtual ~AbstractProcess() {} - - QString workingDirectory() const { return m_workingDir; } - void setWorkingDirectory(const QString &dir) { m_workingDir = dir; } - - QStringList environment() const { return m_environment; } - void setEnvironment(const QStringList &env) { m_environment = env; } - - virtual bool start(const QString &program, const QStringList &args) = 0; - virtual void stop() = 0; - - virtual bool isRunning() const = 0; - virtual qint64 applicationPID() const = 0; - virtual int exitCode() const = 0; - -//signals: - virtual void processError(const QString &error) = 0; - -#ifdef Q_OS_WIN - // Add PATH and SystemRoot environment variables in case they are missing - static QStringList fixWinEnvironment(const QStringList &env); - // Quote a Windows command line correctly for the "CreateProcess" API - static QString createWinCommandline(const QString &program, const QStringList &args); - // Create a bytearray suitable to be passed on as environment - // to the "CreateProcess" API (0-terminated UTF 16 strings). - static QByteArray createWinEnvironment(const QStringList &env); -#endif - -private: - QString m_workingDir; - QStringList m_environment; -}; - -} //namespace Utils - -#endif // ABSTRACTPROCESS_H - diff --git a/libs/utils/abstractprocess_win.cpp b/libs/utils/abstractprocess_win.cpp deleted file mode 100644 index 861ca061fb14ecbf5325d7a6307fb6337f0578b6..0000000000000000000000000000000000000000 --- a/libs/utils/abstractprocess_win.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - ****************************************************************************** - * - * @file abstractprocess_win.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "abstractprocess.h" - -#include - -namespace Utils { - -QStringList AbstractProcess::fixWinEnvironment(const QStringList &env) -{ - QStringList envStrings = env; - // add PATH if necessary (for DLL loading) - if (envStrings.filter(QRegExp(QLatin1String("^PATH="),Qt::CaseInsensitive)).isEmpty()) { - QByteArray path = qgetenv("PATH"); - if (!path.isEmpty()) - envStrings.prepend(QString(QLatin1String("PATH=%1")).arg(QString::fromLocal8Bit(path))); - } - // add systemroot if needed - if (envStrings.filter(QRegExp(QLatin1String("^SystemRoot="),Qt::CaseInsensitive)).isEmpty()) { - QByteArray systemRoot = qgetenv("SystemRoot"); - if (!systemRoot.isEmpty()) - envStrings.prepend(QString(QLatin1String("SystemRoot=%1")).arg(QString::fromLocal8Bit(systemRoot))); - } - return envStrings; -} - -QString AbstractProcess::createWinCommandline(const QString &program, const QStringList &args) -{ - const QChar doubleQuote = QLatin1Char('"'); - const QChar blank = QLatin1Char(' '); - const QChar backSlash = QLatin1Char('\\'); - - QString programName = program; - if (!programName.startsWith(doubleQuote) && !programName.endsWith(doubleQuote) && programName.contains(blank)) { - programName.insert(0, doubleQuote); - programName.append(doubleQuote); - } - // add the prgram as the first arrg ... it works better - programName.replace(QLatin1Char('/'), backSlash); - QString cmdLine = programName; - if (args.empty()) - return cmdLine; - - cmdLine += blank; - for (int i = 0; i < args.size(); ++i) { - QString tmp = args.at(i); - // in the case of \" already being in the string the \ must also be escaped - tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\"")); - // escape a single " because the arguments will be parsed - tmp.replace(QString(doubleQuote), QLatin1String("\\\"")); - if (tmp.isEmpty() || tmp.contains(blank) || tmp.contains('\t')) { - // The argument must not end with a \ since this would be interpreted - // as escaping the quote -- rather put the \ behind the quote: e.g. - // rather use "foo"\ than "foo\" - QString endQuote(doubleQuote); - int i = tmp.length(); - while (i > 0 && tmp.at(i - 1) == backSlash) { - --i; - endQuote += backSlash; - } - cmdLine += QLatin1String(" \""); - cmdLine += tmp.left(i); - cmdLine += endQuote; - } else { - cmdLine += blank; - cmdLine += tmp; - } - } - return cmdLine; -} - -QByteArray AbstractProcess::createWinEnvironment(const QStringList &env) -{ - QByteArray envlist; - int pos = 0; - foreach (const QString &tmp, env) { - const uint tmpSize = sizeof(TCHAR) * (tmp.length() + 1); - envlist.resize(envlist.size() + tmpSize); - memcpy(envlist.data() + pos, tmp.utf16(), tmpSize); - pos += tmpSize; - } - envlist.resize(envlist.size() + 2); - envlist[pos++] = 0; - envlist[pos++] = 0; - return envlist; -} - -} //namespace Utils diff --git a/libs/utils/basevalidatinglineedit.cpp b/libs/utils/basevalidatinglineedit.cpp deleted file mode 100644 index fd3c85c5c006014efe3c7927507da4f43d04050d..0000000000000000000000000000000000000000 --- a/libs/utils/basevalidatinglineedit.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/** - ****************************************************************************** - * - * @file basevalidatinglineedit.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "basevalidatinglineedit.h" - -#include - -enum { debug = 0 }; - -namespace Utils { - -struct BaseValidatingLineEditPrivate { - explicit BaseValidatingLineEditPrivate(const QWidget *w); - - const QColor m_okTextColor; - QColor m_errorTextColor; - - BaseValidatingLineEdit::State m_state; - QString m_errorMessage; - QString m_initialText; - bool m_firstChange; -}; - -BaseValidatingLineEditPrivate::BaseValidatingLineEditPrivate(const QWidget *w) : - m_okTextColor(BaseValidatingLineEdit::textColor(w)), - m_errorTextColor(Qt::red), - m_state(BaseValidatingLineEdit::Invalid), - m_firstChange(true) -{ -} - -BaseValidatingLineEdit::BaseValidatingLineEdit(QWidget *parent) : - QLineEdit(parent), - m_bd(new BaseValidatingLineEditPrivate(this)) -{ - // Note that textChanged() is also triggered automagically by - // QLineEdit::setText(), no need to trigger manually. - connect(this, SIGNAL(textChanged(QString)), this, SLOT(slotChanged(QString))); -} - -BaseValidatingLineEdit::~BaseValidatingLineEdit() -{ - delete m_bd; -} - -QString BaseValidatingLineEdit::initialText() const -{ - return m_bd->m_initialText; -} - -void BaseValidatingLineEdit::setInitialText(const QString &t) -{ - if (m_bd->m_initialText != t) { - m_bd->m_initialText = t; - m_bd->m_firstChange = true; - setText(t); - } -} - -QColor BaseValidatingLineEdit::errorColor() const -{ - return m_bd->m_errorTextColor; -} - -void BaseValidatingLineEdit::setErrorColor(const QColor &c) -{ - m_bd->m_errorTextColor = c; -} - -QColor BaseValidatingLineEdit::textColor(const QWidget *w) -{ - return w->palette().color(QPalette::Active, QPalette::Text); -} - -void BaseValidatingLineEdit::setTextColor(QWidget *w, const QColor &c) -{ - QPalette palette = w->palette(); - palette.setColor(QPalette::Active, QPalette::Text, c); - w->setPalette(palette); -} - -BaseValidatingLineEdit::State BaseValidatingLineEdit::state() const -{ - return m_bd->m_state; -} - -bool BaseValidatingLineEdit::isValid() const -{ - return m_bd->m_state == Valid; -} - -QString BaseValidatingLineEdit::errorMessage() const -{ - return m_bd->m_errorMessage; -} - -void BaseValidatingLineEdit::slotChanged(const QString &t) -{ - m_bd->m_errorMessage.clear(); - // Are we displaying the initial text? - const bool isDisplayingInitialText = !m_bd->m_initialText.isEmpty() && t == m_bd->m_initialText; - const State newState = isDisplayingInitialText ? - DisplayingInitialText : - (validate(t, &m_bd->m_errorMessage) ? Valid : Invalid); - setToolTip(m_bd->m_errorMessage); - if (debug) - qDebug() << Q_FUNC_INFO << t << "State" << m_bd->m_state << "->" << newState << m_bd->m_errorMessage; - // Changed..figure out if valid changed. DisplayingInitialText is not valid, - // but should not show error color. Also trigger on the first change. - if (newState != m_bd->m_state || m_bd->m_firstChange) { - const bool validHasChanged = (m_bd->m_state == Valid) != (newState == Valid); - m_bd->m_state = newState; - m_bd->m_firstChange = false; - setTextColor(this, newState == Invalid ? m_bd->m_errorTextColor : m_bd->m_okTextColor); - if (validHasChanged) { - emit validChanged(newState == Valid); - emit validChanged(); - } - } -} - -void BaseValidatingLineEdit::slotReturnPressed() -{ - if (isValid()) - emit validReturnPressed(); -} - -void BaseValidatingLineEdit::triggerChanged() -{ - slotChanged(text()); -} - -} // namespace Utils diff --git a/libs/utils/basevalidatinglineedit.h b/libs/utils/basevalidatinglineedit.h deleted file mode 100644 index 2e66a7b588fde86bb8db876511abf91a673ae22a..0000000000000000000000000000000000000000 --- a/libs/utils/basevalidatinglineedit.h +++ /dev/null @@ -1,101 +0,0 @@ -/** - ****************************************************************************** - * - * @file basevalidatinglineedit.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef BASEVALIDATINGLINEEDIT_H -#define BASEVALIDATINGLINEEDIT_H - -#include "utils_global.h" - -#include - -namespace Utils { - -struct BaseValidatingLineEditPrivate; - -/** - * Base class for validating line edits that performs validation in a virtual - * validate() function to be implemented in derived classes. - * When invalid, the text color will turn red and a tooltip will - * contain the error message. This approach is less intrusive than a - * QValidator which will prevent the user from entering certain characters. - * - * The widget has a concept of an "initialText" which can be something like - * "". This results in state 'DisplayingInitialText', which - * is not valid, but is not marked red. - */ -class QTCREATOR_UTILS_EXPORT BaseValidatingLineEdit : public QLineEdit -{ - Q_OBJECT - Q_DISABLE_COPY(BaseValidatingLineEdit) - Q_PROPERTY(QString initialText READ initialText WRITE setInitialText DESIGNABLE true) - Q_PROPERTY(QColor errorColor READ errorColor WRITE setErrorColor DESIGNABLE true) - -public: - enum State { Invalid, DisplayingInitialText, Valid }; - - explicit BaseValidatingLineEdit(QWidget *parent = 0); - virtual ~BaseValidatingLineEdit(); - - - State state() const; - bool isValid() const; - QString errorMessage() const; - - QString initialText() const; - void setInitialText(const QString &); - - QColor errorColor() const; - void setErrorColor(const QColor &); - - // Trigger an update (after changing settings) - void triggerChanged(); - - static QColor textColor(const QWidget *w); - static void setTextColor(QWidget *w, const QColor &c); - -signals: - void validChanged(); - void validChanged(bool validState); - void validReturnPressed(); - -protected: - virtual bool validate(const QString &value, QString *errorMessage) const = 0; - -protected slots: - // Custom behaviour can be added here. The base implementation must - // be called. - virtual void slotReturnPressed(); - virtual void slotChanged(const QString &t); - -private: - BaseValidatingLineEditPrivate *m_bd; -}; - -} // namespace Utils - -#endif // BASEVALIDATINGLINEEDIT_H diff --git a/libs/utils/checkablemessagebox.cpp b/libs/utils/checkablemessagebox.cpp deleted file mode 100644 index d176d7ee6e7a36007e7f3eb029db83f11611a364..0000000000000000000000000000000000000000 --- a/libs/utils/checkablemessagebox.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - ****************************************************************************** - * - * @file checkablemessagebox.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "checkablemessagebox.h" -#include "ui_checkablemessagebox.h" - -#include -#include - -namespace Utils { - -struct CheckableMessageBoxPrivate { - CheckableMessageBoxPrivate() : clickedButton(0) {} - - Ui::CheckableMessageBox ui; - QAbstractButton *clickedButton; -}; - -CheckableMessageBox::CheckableMessageBox(QWidget *parent) : - QDialog(parent), - m_d(new CheckableMessageBoxPrivate) -{ - setModal(true); - setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - m_d->ui.setupUi(this); - m_d->ui.pixmapLabel->setVisible(false); - connect(m_d->ui.buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(m_d->ui.buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - connect(m_d->ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(slotClicked(QAbstractButton*))); -} - -CheckableMessageBox::~CheckableMessageBox() -{ - delete m_d; -} - -void CheckableMessageBox::slotClicked(QAbstractButton *b) -{ - m_d->clickedButton = b; -} - -QAbstractButton *CheckableMessageBox::clickedButton() const -{ - return m_d->clickedButton; -} - -QDialogButtonBox::StandardButton CheckableMessageBox::clickedStandardButton() const -{ - if (m_d->clickedButton) - return m_d->ui.buttonBox->standardButton(m_d->clickedButton); - return QDialogButtonBox::NoButton; -} - -QString CheckableMessageBox::text() const -{ - return m_d->ui.messageLabel->text(); -} - -void CheckableMessageBox::setText(const QString &t) -{ - m_d->ui.messageLabel->setText(t); -} - -QPixmap CheckableMessageBox::iconPixmap() const -{ - if (const QPixmap *p = m_d->ui.pixmapLabel->pixmap()) - return QPixmap(*p); - return QPixmap(); -} - -void CheckableMessageBox::setIconPixmap(const QPixmap &p) -{ - m_d->ui.pixmapLabel->setPixmap(p); - m_d->ui.pixmapLabel->setVisible(!p.isNull()); -} - -bool CheckableMessageBox::isChecked() const -{ - return m_d->ui.checkBox->isChecked(); -} - -void CheckableMessageBox::setChecked(bool s) -{ - m_d->ui.checkBox->setChecked(s); -} - -QString CheckableMessageBox::checkBoxText() const -{ - return m_d->ui.checkBox->text(); -} - -void CheckableMessageBox::setCheckBoxText(const QString &t) -{ - m_d->ui.checkBox->setText(t); -} - -QDialogButtonBox::StandardButtons CheckableMessageBox::standardButtons() const -{ - return m_d->ui.buttonBox->standardButtons(); -} - -void CheckableMessageBox::setStandardButtons(QDialogButtonBox::StandardButtons s) -{ - m_d->ui.buttonBox->setStandardButtons(s); -} - -QDialogButtonBox::StandardButton CheckableMessageBox::defaultButton() const -{ - foreach (QAbstractButton *b, m_d->ui.buttonBox->buttons()) - if (QPushButton *pb = qobject_cast(b)) - if (pb->isDefault()) - return m_d->ui.buttonBox->standardButton(pb); - return QDialogButtonBox::NoButton; -} - -void CheckableMessageBox::setDefaultButton(QDialogButtonBox::StandardButton s) -{ - if (QPushButton *b = m_d->ui.buttonBox->button(s)) { - b->setDefault(true); - b->setFocus(); - } -} - -QDialogButtonBox::StandardButton - CheckableMessageBox::question(QWidget *parent, - const QString &title, - const QString &question, - const QString &checkBoxText, - bool *checkBoxSetting, - QDialogButtonBox::StandardButtons buttons, - QDialogButtonBox::StandardButton defaultButton) -{ - CheckableMessageBox mb(parent); - mb.setWindowTitle(title); - mb.setIconPixmap(QMessageBox::standardIcon(QMessageBox::Question)); - mb.setText(question); - mb.setCheckBoxText(checkBoxText); - mb.setChecked(*checkBoxSetting); - mb.setStandardButtons(buttons); - mb.setDefaultButton(defaultButton); - mb.exec(); - *checkBoxSetting = mb.isChecked(); - return mb.clickedStandardButton(); -} - -QMessageBox::StandardButton CheckableMessageBox::dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton db) -{ - return static_cast(int(db)); -} - -} // namespace Utils diff --git a/libs/utils/checkablemessagebox.h b/libs/utils/checkablemessagebox.h deleted file mode 100644 index f9af481dda37c658b45c42a93426b7b9fbd908b0..0000000000000000000000000000000000000000 --- a/libs/utils/checkablemessagebox.h +++ /dev/null @@ -1,103 +0,0 @@ -/** - ****************************************************************************** - * - * @file checkablemessagebox.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef CHECKABLEMESSAGEBOX_H -#define CHECKABLEMESSAGEBOX_H - -#include "utils_global.h" - -#include -#include -#include - -namespace Utils { - -struct CheckableMessageBoxPrivate; - -/* A messagebox suitable for questions with a - * "Do not ask me again" checkbox. Emulates the QMessageBox API with - * static conveniences. */ - -class QTCREATOR_UTILS_EXPORT CheckableMessageBox : public QDialog -{ - Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap) - Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) - Q_PROPERTY(QString checkBoxText READ checkBoxText WRITE setCheckBoxText) - Q_PROPERTY(QDialogButtonBox::StandardButtons buttons READ standardButtons WRITE setStandardButtons) - Q_PROPERTY(QDialogButtonBox::StandardButton defaultButton READ defaultButton WRITE setDefaultButton) -public: - explicit CheckableMessageBox(QWidget *parent); - virtual ~CheckableMessageBox(); - - static QDialogButtonBox::StandardButton - question(QWidget *parent, - const QString &title, - const QString &question, - const QString &checkBoxText, - bool *checkBoxSetting, - QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Yes|QDialogButtonBox::No, - QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::No); - - QString text() const; - void setText(const QString &); - - bool isChecked() const; - void setChecked(bool s); - - QString checkBoxText() const; - void setCheckBoxText(const QString &); - - QDialogButtonBox::StandardButtons standardButtons() const; - void setStandardButtons(QDialogButtonBox::StandardButtons s); - - QDialogButtonBox::StandardButton defaultButton() const; - void setDefaultButton(QDialogButtonBox::StandardButton s); - - // see static QMessageBox::standardPixmap() - QPixmap iconPixmap() const; - void setIconPixmap (const QPixmap &p); - - // Query the result - QAbstractButton *clickedButton() const; - QDialogButtonBox::StandardButton clickedStandardButton() const; - - // Conversion convenience - static QMessageBox::StandardButton dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton); - -private slots: - void slotClicked(QAbstractButton *b); - -private: - CheckableMessageBoxPrivate *m_d; -}; - -} // namespace Utils - -#endif // CHECKABLEMESSAGEBOX_H diff --git a/libs/utils/checkablemessagebox.ui b/libs/utils/checkablemessagebox.ui deleted file mode 100644 index 7491a849162f780d910cadd27faf7a6a7aa25847..0000000000000000000000000000000000000000 --- a/libs/utils/checkablemessagebox.ui +++ /dev/null @@ -1,154 +0,0 @@ - - - Utils::CheckableMessageBox - - - - 0 - 0 - 195 - 107 - - - - Dialog - - - - - - - - - - - - - Qt::Vertical - - - QSizePolicy::MinimumExpanding - - - - 0 - 5 - - - - - - - - - - TextLabel - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - CheckBox - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 0 - 5 - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - true - - - - - - - - - buttonBox - accepted() - Utils::CheckableMessageBox - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Utils::CheckableMessageBox - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/libs/utils/classnamevalidatinglineedit.cpp b/libs/utils/classnamevalidatinglineedit.cpp deleted file mode 100644 index 1f23c9be5f7989a3dc6fbb75444baf1270f2ade8..0000000000000000000000000000000000000000 --- a/libs/utils/classnamevalidatinglineedit.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - ****************************************************************************** - * - * @file classnamevalidatinglineedit.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "classnamevalidatinglineedit.h" - -#include - -#include -#include - -namespace Utils { - -struct ClassNameValidatingLineEditPrivate { - ClassNameValidatingLineEditPrivate(); - - const QRegExp m_nameRegexp; - const QString m_namespaceDelimiter; - bool m_namespacesEnabled; - bool m_lowerCaseFileName; -}; - -// Match something like "Namespace1::Namespace2::ClassName". -ClassNameValidatingLineEditPrivate:: ClassNameValidatingLineEditPrivate() : - m_nameRegexp(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*")), - m_namespaceDelimiter(QLatin1String("::")), - m_namespacesEnabled(false), - m_lowerCaseFileName(true) -{ - QTC_ASSERT(m_nameRegexp.isValid(), return); -} - -// --------------------- ClassNameValidatingLineEdit -ClassNameValidatingLineEdit::ClassNameValidatingLineEdit(QWidget *parent) : - Utils::BaseValidatingLineEdit(parent), - m_d(new ClassNameValidatingLineEditPrivate) -{ -} - -ClassNameValidatingLineEdit::~ClassNameValidatingLineEdit() -{ - delete m_d; -} - -bool ClassNameValidatingLineEdit::namespacesEnabled() const -{ - return m_d->m_namespacesEnabled; -} - -void ClassNameValidatingLineEdit::setNamespacesEnabled(bool b) -{ - m_d->m_namespacesEnabled = b; -} - -bool ClassNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const -{ - if (!m_d->m_namespacesEnabled && value.contains(QLatin1Char(':'))) { - if (errorMessage) - *errorMessage = tr("The class name must not contain namespace delimiters."); - return false; - } else if (value.isEmpty()) { - if (errorMessage) - *errorMessage = tr("Please enter a class name."); - return false; - } else if (!m_d->m_nameRegexp.exactMatch(value)) { - if (errorMessage) - *errorMessage = tr("The class name contains invalid characters."); - return false; - } - return true; -} - -void ClassNameValidatingLineEdit::slotChanged(const QString &t) -{ - Utils::BaseValidatingLineEdit::slotChanged(t); - if (isValid()) { - // Suggest file names, strip namespaces - QString fileName = m_d->m_lowerCaseFileName ? t.toLower() : t; - if (m_d->m_namespacesEnabled) { - const int namespaceIndex = fileName.lastIndexOf(m_d->m_namespaceDelimiter); - if (namespaceIndex != -1) - fileName.remove(0, namespaceIndex + m_d->m_namespaceDelimiter.size()); - } - emit updateFileName(fileName); - } -} - -QString ClassNameValidatingLineEdit::createClassName(const QString &name) -{ - // Remove spaces and convert the adjacent characters to uppercase - QString className = name; - QRegExp spaceMatcher(QLatin1String(" +(\\w)"), Qt::CaseSensitive, QRegExp::RegExp2); - QTC_ASSERT(spaceMatcher.isValid(), /**/); - int pos; - while ((pos = spaceMatcher.indexIn(className)) != -1) { - className.replace(pos, spaceMatcher.matchedLength(), - spaceMatcher.cap(1).toUpper()); - } - - // Filter out any remaining invalid characters - className.remove(QRegExp(QLatin1String("[^a-zA-Z0-9_]"))); - - // If the first character is numeric, prefix the name with a "_" - if (className.at(0).isNumber()) { - className.prepend(QLatin1Char('_')); - } else { - // Convert the first character to uppercase - className.replace(0, 1, className.left(1).toUpper()); - } - - return className; -} - -bool ClassNameValidatingLineEdit::lowerCaseFileName() const -{ - return m_d->m_lowerCaseFileName; -} - -void ClassNameValidatingLineEdit::setLowerCaseFileName(bool v) -{ - m_d->m_lowerCaseFileName = v; -} - -} // namespace Utils diff --git a/libs/utils/classnamevalidatinglineedit.h b/libs/utils/classnamevalidatinglineedit.h deleted file mode 100644 index 83890f31e291439f103f185e5507ccf2a6381d7a..0000000000000000000000000000000000000000 --- a/libs/utils/classnamevalidatinglineedit.h +++ /dev/null @@ -1,78 +0,0 @@ -/** - ****************************************************************************** - * - * @file classnamevalidatinglineedit.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef CLASSNAMEVALIDATINGLINEEDIT_H -#define CLASSNAMEVALIDATINGLINEEDIT_H - -#include "utils_global.h" -#include "basevalidatinglineedit.h" - -namespace Utils { - -struct ClassNameValidatingLineEditPrivate; - -/* A Line edit that validates a C++ class name and emits a signal - * to derive suggested file names from it. */ - -class QTCREATOR_UTILS_EXPORT ClassNameValidatingLineEdit - : public Utils::BaseValidatingLineEdit -{ - Q_DISABLE_COPY(ClassNameValidatingLineEdit) - Q_PROPERTY(bool namespacesEnabled READ namespacesEnabled WRITE setNamespacesEnabled DESIGNABLE true) - Q_PROPERTY(bool lowerCaseFileName READ lowerCaseFileName WRITE setLowerCaseFileName) - Q_OBJECT - -public: - explicit ClassNameValidatingLineEdit(QWidget *parent = 0); - virtual ~ClassNameValidatingLineEdit(); - - bool namespacesEnabled() const; - void setNamespacesEnabled(bool b); - - bool lowerCaseFileName() const; - void setLowerCaseFileName(bool v); - - // Clean an input string to get a valid class name. - static QString createClassName(const QString &name); - -signals: - // Will be emitted with a suggestion for a base name of the - // source/header file of the class. - void updateFileName(const QString &t); - -protected: - virtual bool validate(const QString &value, QString *errorMessage) const; - virtual void slotChanged(const QString &t); - -private: - ClassNameValidatingLineEditPrivate *m_d; -}; - -} // namespace Utils - -#endif // CLASSNAMEVALIDATINGLINEEDIT_H diff --git a/libs/utils/codegeneration.cpp b/libs/utils/codegeneration.cpp deleted file mode 100644 index a8b93c6f2ae8653aec5a0087d87d8c261d09af9d..0000000000000000000000000000000000000000 --- a/libs/utils/codegeneration.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/** - ****************************************************************************** - * - * @file codegeneration.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "codegeneration.h" - -#include -#include -#include - -namespace Utils { - -QTCREATOR_UTILS_EXPORT QString fileNameToCppIdentifier(const QString &s) -{ - QString rc; - const int len = s.size(); - const QChar underscore = QLatin1Char('_'); - const QChar dot = QLatin1Char('.'); - - for (int i = 0; i < len; i++) { - const QChar c = s.at(i); - if (c == underscore || c.isLetterOrNumber()) - rc += c; - else if (c == dot) - rc += underscore; - } - return rc; -} - -QTCREATOR_UTILS_EXPORT QString headerGuard(const QString &file) -{ - const QFileInfo fi(file); - QString rc = fileNameToCppIdentifier(fi.completeBaseName()).toUpper(); - rc += QLatin1Char('_'); - rc += fileNameToCppIdentifier(fi.suffix()).toUpper(); - return rc; -} - -QTCREATOR_UTILS_EXPORT -void writeIncludeFileDirective(const QString &file, bool globalInclude, - QTextStream &str) -{ - const QChar opening = globalInclude ? QLatin1Char('<') : QLatin1Char('"'); - const QChar closing = globalInclude ? QLatin1Char('>') : QLatin1Char('"'); - str << QLatin1String("#include ") << opening << file << closing << QLatin1Char('\n'); -} - -QTCREATOR_UTILS_EXPORT -QString writeOpeningNameSpaces(const QStringList &l, const QString &indent, - QTextStream &str) -{ - const int count = l.size(); - QString rc; - if (count) { - str << '\n'; - for (int i = 0; i < count; i++) { - str << rc << "namespace " << l.at(i) << " {\n"; - rc += indent; - } - } - return rc; -} - -QTCREATOR_UTILS_EXPORT -void writeClosingNameSpaces(const QStringList &l, const QString &indent, - QTextStream &str) -{ - if (!l.empty()) - str << '\n'; - for (int i = l.size() - 1; i >= 0; i--) { - if (i) - str << QString(indent.size() * i, QLatin1Char(' ')); - str << "} // namespace " << l.at(i) << '\n'; - } -} - -} // namespace Utils diff --git a/libs/utils/codegeneration.h b/libs/utils/codegeneration.h deleted file mode 100644 index 80debe585ce69ce04ead9793f46d99fdb6407837..0000000000000000000000000000000000000000 --- a/libs/utils/codegeneration.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - ****************************************************************************** - * - * @file codegeneration.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef CODEGENERATION_H -#define CODEGENERATION_H - -#include "utils_global.h" -#include - -QT_BEGIN_NAMESPACE -class QTextStream; -class QStringList; -QT_END_NAMESPACE - -namespace Utils { - -// Convert a file name to a Cpp identifier (stripping invalid characters -// or replacing them by an underscore). -QTCREATOR_UTILS_EXPORT QString fileNameToCppIdentifier(const QString &s); - -QTCREATOR_UTILS_EXPORT QString headerGuard(const QString &file); - -QTCREATOR_UTILS_EXPORT -void writeIncludeFileDirective(const QString &file, - bool globalInclude, - QTextStream &str); - -// Write opening namespaces and return an indentation string to be used -// in the following code if there are any. -QTCREATOR_UTILS_EXPORT -QString writeOpeningNameSpaces(const QStringList &namespaces, - const QString &indent, - QTextStream &str); - -// Close namespacesnamespaces -QTCREATOR_UTILS_EXPORT -void writeClosingNameSpaces(const QStringList &namespaces, - const QString &indent, - QTextStream &str); - -} // namespace Utils - -#endif // CODEGENERATION_H diff --git a/libs/utils/consoleprocess.cpp b/libs/utils/consoleprocess.cpp deleted file mode 100644 index 596e45977253c2d87caccbf6766e5adc55df1d35..0000000000000000000000000000000000000000 --- a/libs/utils/consoleprocess.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - ****************************************************************************** - * - * @file consoleprocess.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "consoleprocess.h" - -namespace Utils { - -QString ConsoleProcess::modeOption(Mode m) -{ - switch (m) { - case Debug: - return QLatin1String("debug"); - case Suspend: - return QLatin1String("suspend"); - case Run: - break; - } - return QLatin1String("run"); -} - -QString ConsoleProcess::msgCommChannelFailed(const QString &error) -{ - return tr("Cannot set up communication channel: %1").arg(error); -} - -QString ConsoleProcess::msgPromptToClose() -{ - //! Showed in a terminal which might have - //! a different character set on Windows. - return tr("Press to close this window..."); -} - -QString ConsoleProcess::msgCannotCreateTempFile(const QString &why) -{ - return tr("Cannot create temporary file: %1").arg(why); -} - -QString ConsoleProcess::msgCannotCreateTempDir(const QString & dir, const QString &why) -{ - return tr("Cannot create temporary directory '%1': %2").arg(dir, why); -} - -QString ConsoleProcess::msgUnexpectedOutput() -{ - return tr("Unexpected output from helper program."); -} - -QString ConsoleProcess::msgCannotChangeToWorkDir(const QString & dir, const QString &why) -{ - return tr("Cannot change to working directory '%1': %2").arg(dir, why); -} - -QString ConsoleProcess::msgCannotExecute(const QString & p, const QString &why) -{ - return tr("Cannot execute '%1': %2").arg(p, why); -} - -} diff --git a/libs/utils/consoleprocess.h b/libs/utils/consoleprocess.h deleted file mode 100644 index 389a14c386d5b97f13ad84e8049dcb02235cf44d..0000000000000000000000000000000000000000 --- a/libs/utils/consoleprocess.h +++ /dev/null @@ -1,140 +0,0 @@ -/** - ****************************************************************************** - * - * @file consoleprocess.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef CONSOLEPROCESS_H -#define CONSOLEPROCESS_H - -#include "abstractprocess.h" - -#include -#include -#include -#include - -#include - -#ifdef Q_OS_WIN -#include -QT_BEGIN_NAMESPACE -class QWinEventNotifier; -QT_END_NAMESPACE -#endif - -QT_BEGIN_NAMESPACE -class QSettings; -class QTemporaryFile; -QT_END_NAMESPACE - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT ConsoleProcess : public QObject, public AbstractProcess -{ - Q_OBJECT - -public: - enum Mode { Run, Debug, Suspend }; - ConsoleProcess(QObject *parent = 0); - ~ConsoleProcess(); - - bool start(const QString &program, const QStringList &args); - void stop(); - - void setMode(Mode m) { m_mode = m; } - Mode mode() const { return m_mode; } - - bool isRunning() const; // This reflects the state of the console+stub - qint64 applicationPID() const { return m_appPid; } - int exitCode() const { return m_appCode; } // This will be the signal number if exitStatus == CrashExit - QProcess::ExitStatus exitStatus() const { return m_appStatus; } - -#ifdef Q_OS_UNIX - void setSettings(QSettings *settings) { m_settings = settings; } - static QString defaultTerminalEmulator(); - static QString terminalEmulator(const QSettings *settings); - static void setTerminalEmulator(QSettings *settings, const QString &term); -#endif - -signals: - void processError(const QString &error); - // These reflect the state of the actual client process - void processStarted(); - void processStopped(); - - // These reflect the state of the console+stub - void wrapperStarted(); - void wrapperStopped(); - -private slots: - void stubConnectionAvailable(); - void readStubOutput(); - void stubExited(); -#ifdef Q_OS_WIN - void inferiorExited(); -#endif - -private: - static QString modeOption(Mode m); - static QString msgCommChannelFailed(const QString &error); - static QString msgPromptToClose(); - static QString msgCannotCreateTempFile(const QString &why); - static QString msgCannotCreateTempDir(const QString & dir, const QString &why); - static QString msgUnexpectedOutput(); - static QString msgCannotChangeToWorkDir(const QString & dir, const QString &why); - static QString msgCannotExecute(const QString & p, const QString &why); - - QString stubServerListen(); - void stubServerShutdown(); -#ifdef Q_OS_WIN - void cleanupStub(); - void cleanupInferior(); -#endif - - Mode m_mode; - qint64 m_appPid; - int m_appCode; - QString m_executable; - QProcess::ExitStatus m_appStatus; - QLocalServer m_stubServer; - QLocalSocket *m_stubSocket; - QTemporaryFile *m_tempFile; -#ifdef Q_OS_WIN - PROCESS_INFORMATION *m_pid; - HANDLE m_hInferior; - QWinEventNotifier *inferiorFinishedNotifier; - QWinEventNotifier *processFinishedNotifier; -#else - QProcess m_process; - QByteArray m_stubServerDir; - QSettings *m_settings; -#endif - -}; - -} //namespace Utils - -#endif diff --git a/libs/utils/consoleprocess_unix.cpp b/libs/utils/consoleprocess_unix.cpp deleted file mode 100644 index 6a66d6d78f08935656cdb4df795e8948db126805..0000000000000000000000000000000000000000 --- a/libs/utils/consoleprocess_unix.cpp +++ /dev/null @@ -1,258 +0,0 @@ -/** - ****************************************************************************** - * - * @file consoleprocess_unix.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "consoleprocess.h" - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -using namespace Utils; - -ConsoleProcess::ConsoleProcess(QObject *parent) : - QObject(parent), - m_mode(Run), - m_appPid(0), - m_stubSocket(0), - m_settings(0) -{ - connect(&m_stubServer, SIGNAL(newConnection()), SLOT(stubConnectionAvailable())); - - m_process.setProcessChannelMode(QProcess::ForwardedChannels); - connect(&m_process, SIGNAL(finished(int, QProcess::ExitStatus)), - SLOT(stubExited())); -} - -ConsoleProcess::~ConsoleProcess() -{ - stop(); -} - -bool ConsoleProcess::start(const QString &program, const QStringList &args) -{ - if (isRunning()) - return false; - - const QString err = stubServerListen(); - if (!err.isEmpty()) { - emit processError(msgCommChannelFailed(err)); - return false; - } - - if (!environment().isEmpty()) { - m_tempFile = new QTemporaryFile(); - if (!m_tempFile->open()) { - stubServerShutdown(); - emit processError(msgCannotCreateTempFile(m_tempFile->errorString())); - delete m_tempFile; - m_tempFile = 0; - return false; - } - foreach (const QString &var, environment()) { - m_tempFile->write(var.toLocal8Bit()); - m_tempFile->write("", 1); - } - m_tempFile->flush(); - } - - QStringList xtermArgs = terminalEmulator(m_settings).split(QLatin1Char(' ')); // FIXME: quoting - xtermArgs -#ifdef Q_OS_MAC - << (QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/qtcreator_process_stub")) -#else - << (QCoreApplication::applicationDirPath() + QLatin1String("/qtcreator_process_stub")) -#endif - << modeOption(m_mode) - << m_stubServer.fullServerName() - << msgPromptToClose() - << workingDirectory() - << (m_tempFile ? m_tempFile->fileName() : 0) - << program << args; - - QString xterm = xtermArgs.takeFirst(); - m_process.start(xterm, xtermArgs); - if (!m_process.waitForStarted()) { - stubServerShutdown(); - emit processError(tr("Cannot start the terminal emulator '%1'.").arg(xterm)); - delete m_tempFile; - m_tempFile = 0; - return false; - } - m_executable = program; - emit wrapperStarted(); - return true; -} - -void ConsoleProcess::stop() -{ - if (!isRunning()) - return; - stubServerShutdown(); - m_appPid = 0; - m_process.terminate(); - if (!m_process.waitForFinished(1000)) - m_process.kill(); - m_process.waitForFinished(); -} - -bool ConsoleProcess::isRunning() const -{ - return m_process.state() != QProcess::NotRunning; -} - -QString ConsoleProcess::stubServerListen() -{ - // We need to put the socket in a private directory, as some systems simply do not - // check the file permissions of sockets. - QString stubFifoDir; - forever { - { - QTemporaryFile tf; - if (!tf.open()) - return msgCannotCreateTempFile(tf.errorString()); - stubFifoDir = QFile::encodeName(tf.fileName()); - } - // By now the temp file was deleted again - m_stubServerDir = QFile::encodeName(stubFifoDir); - if (!::mkdir(m_stubServerDir.constData(), 0700)) - break; - if (errno != EEXIST) - return msgCannotCreateTempDir(stubFifoDir, QString::fromLocal8Bit(strerror(errno))); - } - const QString stubServer = stubFifoDir + "/stub-socket"; - if (!m_stubServer.listen(stubServer)) { - ::rmdir(m_stubServerDir.constData()); - return tr("Cannot create socket '%1': %2").arg(stubServer, m_stubServer.errorString()); - } - return QString(); -} - -void ConsoleProcess::stubServerShutdown() -{ - delete m_stubSocket; - m_stubSocket = 0; - if (m_stubServer.isListening()) { - m_stubServer.close(); - ::rmdir(m_stubServerDir.constData()); - } -} - -void ConsoleProcess::stubConnectionAvailable() -{ - m_stubSocket = m_stubServer.nextPendingConnection(); - connect(m_stubSocket, SIGNAL(readyRead()), SLOT(readStubOutput())); -} - -static QString errorMsg(int code) -{ - return QString::fromLocal8Bit(strerror(code)); -} - -void ConsoleProcess::readStubOutput() -{ - while (m_stubSocket->canReadLine()) { - QByteArray out = m_stubSocket->readLine(); - out.chop(1); // \n - if (out.startsWith("err:chdir ")) { - emit processError(msgCannotChangeToWorkDir(workingDirectory(), errorMsg(out.mid(10).toInt()))); - } else if (out.startsWith("err:exec ")) { - emit processError(msgCannotExecute(m_executable, errorMsg(out.mid(9).toInt()))); - } else if (out.startsWith("pid ")) { - // Will not need it any more - delete m_tempFile; - m_tempFile = 0; - - m_appPid = out.mid(4).toInt(); - emit processStarted(); - } else if (out.startsWith("exit ")) { - m_appStatus = QProcess::NormalExit; - m_appCode = out.mid(5).toInt(); - m_appPid = 0; - emit processStopped(); - } else if (out.startsWith("crash ")) { - m_appStatus = QProcess::CrashExit; - m_appCode = out.mid(6).toInt(); - m_appPid = 0; - emit processStopped(); - } else { - emit processError(msgUnexpectedOutput()); - m_process.terminate(); - break; - } - } -} - -void ConsoleProcess::stubExited() -{ - // The stub exit might get noticed before we read the error status. - if (m_stubSocket && m_stubSocket->state() == QLocalSocket::ConnectedState) - m_stubSocket->waitForDisconnected(); - stubServerShutdown(); - delete m_tempFile; - m_tempFile = 0; - if (m_appPid) { - m_appStatus = QProcess::CrashExit; - m_appCode = -1; - m_appPid = 0; - emit processStopped(); // Maybe it actually did not, but keep state consistent - } - emit wrapperStopped(); -} - -QString ConsoleProcess::defaultTerminalEmulator() -{ -// FIXME: enable this once runInTerminal works nicely -#if 0 //def Q_OS_MAC - return QDir::cleanPath(QCoreApplication::applicationDirPath() - + QLatin1String("/../Resources/runInTerminal.command")); -#else - return QLatin1String("xterm"); -#endif -} - -QString ConsoleProcess::terminalEmulator(const QSettings *settings) -{ - const QString dflt = defaultTerminalEmulator() + QLatin1String(" -e"); - if (!settings) - return dflt; - return settings->value(QLatin1String("General/TerminalEmulator"), dflt).toString(); -} - -void ConsoleProcess::setTerminalEmulator(QSettings *settings, const QString &term) -{ - return settings->setValue(QLatin1String("General/TerminalEmulator"), term); -} diff --git a/libs/utils/consoleprocess_win.cpp b/libs/utils/consoleprocess_win.cpp deleted file mode 100644 index 15eec83619bb6f14003a407c111001d594d6f11e..0000000000000000000000000000000000000000 --- a/libs/utils/consoleprocess_win.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/** - ****************************************************************************** - * - * @file consoleprocess_win.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "consoleprocess.h" -#include "winutils.h" - -#include -#include -#include -#include -#include "qwineventnotifier_p.h" - -#include - -#include - -using namespace Utils; - -ConsoleProcess::ConsoleProcess(QObject *parent) : - QObject(parent), - m_mode(Run), - m_appPid(0), - m_stubSocket(0), - m_tempFile(0), - m_pid(0), - m_hInferior(NULL), - inferiorFinishedNotifier(0), - processFinishedNotifier(0) -{ - connect(&m_stubServer, SIGNAL(newConnection()), SLOT(stubConnectionAvailable())); -} - -ConsoleProcess::~ConsoleProcess() -{ - stop(); -} - -bool ConsoleProcess::start(const QString &program, const QStringList &args) -{ - if (isRunning()) - return false; - - const QString err = stubServerListen(); - if (!err.isEmpty()) { - emit processError(msgCommChannelFailed(err)); - return false; - } - - if (!environment().isEmpty()) { - m_tempFile = new QTemporaryFile(); - if (!m_tempFile->open()) { - stubServerShutdown(); - emit processError(msgCannotCreateTempFile(m_tempFile->errorString())); - delete m_tempFile; - m_tempFile = 0; - return false; - } - QTextStream out(m_tempFile); - out.setCodec("UTF-16LE"); - out.setGenerateByteOrderMark(false); - foreach (const QString &var, fixWinEnvironment(environment())) - out << var << QChar(0); - out << QChar(0); - } - - STARTUPINFO si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - m_pid = new PROCESS_INFORMATION; - ZeroMemory(m_pid, sizeof(PROCESS_INFORMATION)); - - QString workDir = QDir::toNativeSeparators(workingDirectory()); - if (!workDir.isEmpty() && !workDir.endsWith('\\')) - workDir.append('\\'); - - QStringList stubArgs; - stubArgs << modeOption(m_mode) - << m_stubServer.fullServerName() - << workDir - << (m_tempFile ? m_tempFile->fileName() : 0) - << createWinCommandline(program, args) - << msgPromptToClose(); - - const QString cmdLine = createWinCommandline( - QCoreApplication::applicationDirPath() + QLatin1String("/qtcreator_process_stub.exe"), stubArgs); - - bool success = CreateProcessW(0, (WCHAR*)cmdLine.utf16(), - 0, 0, FALSE, CREATE_NEW_CONSOLE, - 0, 0, - &si, m_pid); - - if (!success) { - delete m_pid; - m_pid = 0; - delete m_tempFile; - m_tempFile = 0; - stubServerShutdown(); - emit processError(tr("The process '%1' could not be started: %2").arg(cmdLine, winErrorMessage(GetLastError()))); - return false; - } - - processFinishedNotifier = new QWinEventNotifier(m_pid->hProcess, this); - connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), SLOT(stubExited())); - emit wrapperStarted(); - return true; -} - -void ConsoleProcess::stop() -{ - if (m_hInferior != NULL) { - TerminateProcess(m_hInferior, (unsigned)-1); - cleanupInferior(); - } - if (m_pid) { - TerminateProcess(m_pid->hProcess, (unsigned)-1); - WaitForSingleObject(m_pid->hProcess, INFINITE); - cleanupStub(); - } -} - -bool ConsoleProcess::isRunning() const -{ - return m_pid != 0; -} - -QString ConsoleProcess::stubServerListen() -{ - if (m_stubServer.listen(QString::fromLatin1("creator-%1-%2") - .arg(QCoreApplication::applicationPid()) - .arg(rand()))) - return QString(); - return m_stubServer.errorString(); -} - -void ConsoleProcess::stubServerShutdown() -{ - delete m_stubSocket; - m_stubSocket = 0; - if (m_stubServer.isListening()) - m_stubServer.close(); -} - -void ConsoleProcess::stubConnectionAvailable() -{ - m_stubSocket = m_stubServer.nextPendingConnection(); - connect(m_stubSocket, SIGNAL(readyRead()), SLOT(readStubOutput())); -} - -void ConsoleProcess::readStubOutput() -{ - while (m_stubSocket->canReadLine()) { - QByteArray out = m_stubSocket->readLine(); - out.chop(2); // \r\n - if (out.startsWith("err:chdir ")) { - emit processError(msgCannotChangeToWorkDir(workingDirectory(), winErrorMessage(out.mid(10).toInt()))); - } else if (out.startsWith("err:exec ")) { - emit processError(msgCannotExecute(m_executable, winErrorMessage(out.mid(9).toInt()))); - } else if (out.startsWith("pid ")) { - // Wil not need it any more - delete m_tempFile; - m_tempFile = 0; - - m_appPid = out.mid(4).toInt(); - m_hInferior = OpenProcess( - SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, - FALSE, m_appPid); - if (m_hInferior == NULL) { - emit processError(tr("Cannot obtain a handle to the inferior: %1") - .arg(winErrorMessage(GetLastError()))); - // Uhm, and now what? - continue; - } - inferiorFinishedNotifier = new QWinEventNotifier(m_hInferior, this); - connect(inferiorFinishedNotifier, SIGNAL(activated(HANDLE)), SLOT(inferiorExited())); - emit processStarted(); - } else { - emit processError(msgUnexpectedOutput()); - TerminateProcess(m_pid->hProcess, (unsigned)-1); - break; - } - } -} - -void ConsoleProcess::cleanupInferior() -{ - delete inferiorFinishedNotifier; - inferiorFinishedNotifier = 0; - CloseHandle(m_hInferior); - m_hInferior = NULL; - m_appPid = 0; -} - -void ConsoleProcess::inferiorExited() -{ - DWORD chldStatus; - - if (!GetExitCodeProcess(m_hInferior, &chldStatus)) - emit processError(tr("Cannot obtain exit status from inferior: %1") - .arg(winErrorMessage(GetLastError()))); - cleanupInferior(); - m_appStatus = QProcess::NormalExit; - m_appCode = chldStatus; - emit processStopped(); -} - -void ConsoleProcess::cleanupStub() -{ - stubServerShutdown(); - delete processFinishedNotifier; - processFinishedNotifier = 0; - CloseHandle(m_pid->hThread); - CloseHandle(m_pid->hProcess); - delete m_pid; - m_pid = 0; - delete m_tempFile; - m_tempFile = 0; -} - -void ConsoleProcess::stubExited() -{ - // The stub exit might get noticed before we read the pid for the kill. - if (m_stubSocket && m_stubSocket->state() == QLocalSocket::ConnectedState) - m_stubSocket->waitForDisconnected(); - cleanupStub(); - if (m_hInferior != NULL) { - TerminateProcess(m_hInferior, (unsigned)-1); - cleanupInferior(); - m_appStatus = QProcess::CrashExit; - m_appCode = -1; - emit processStopped(); - } - emit wrapperStopped(); -} - diff --git a/libs/utils/coordinateconversions.cpp b/libs/utils/coordinateconversions.cpp deleted file mode 100644 index 19c5dc2b05b3a9b687cb59f45985816052f744e2..0000000000000000000000000000000000000000 --- a/libs/utils/coordinateconversions.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - ****************************************************************************** - * - * @file coordinateconversions.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * @brief General conversions with different coordinate systems. - * - all angles in deg - * - distances in meters - * - altitude above WGS-84 elipsoid - * - * @see The GNU Public License (GPL) Version 3 - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "coordinateconversions.h" -#include -#include -#include -#include - -#define RAD2DEG (180.0/M_PI) -#define DEG2RAD (M_PI/180.0) - -namespace Utils { - -CoordinateConversions::CoordinateConversions() -{ - -} - -/** - * Get rotation matrix from ECEF to NED for that LLA - * @param[in] LLA Longitude latitude altitude for this location - * @param[out] Rne[3][3] Rotation matrix - */ -void CoordinateConversions::RneFromLLA(double LLA[3], double Rne[3][3]){ - float sinLat, sinLon, cosLat, cosLon; - - sinLat=(float)sin(DEG2RAD*LLA[0]); - sinLon=(float)sin(DEG2RAD*LLA[1]); - cosLat=(float)cos(DEG2RAD*LLA[0]); - cosLon=(float)cos(DEG2RAD*LLA[1]); - - Rne[0][0] = -sinLat*cosLon; Rne[0][1] = -sinLat*sinLon; Rne[0][2] = cosLat; - Rne[1][0] = -sinLon; Rne[1][1] = cosLon; Rne[1][2] = 0; - Rne[2][0] = -cosLat*cosLon; Rne[2][1] = -cosLat*sinLon; Rne[2][2] = -sinLat; -} - -/** - * Convert from LLA coordinates to ECEF coordinates - * @param[in] LLA[3] latitude longitude alititude coordinates in - * @param[out] ECEF[3] location in ECEF coordinates - */ -void CoordinateConversions::LLA2ECEF(double LLA[3], double ECEF[3]){ - const double a = 6378137.0; // Equatorial Radius - const double e = 8.1819190842622e-2; // Eccentricity - double sinLat, sinLon, cosLat, cosLon; - double N; - - sinLat=sin(DEG2RAD*LLA[0]); - sinLon=sin(DEG2RAD*LLA[1]); - cosLat=cos(DEG2RAD*LLA[0]); - cosLon=cos(DEG2RAD*LLA[1]); - - N = a / sqrt(1.0 - e*e*sinLat*sinLat); //prime vertical radius of curvature - - ECEF[0] = (N+LLA[2])*cosLat*cosLon; - ECEF[1] = (N+LLA[2])*cosLat*sinLon; - ECEF[2] = ((1-e*e)*N + LLA[2]) * sinLat; -} - -/** - * Convert from ECEF coordinates to LLA coordinates - * @param[in] ECEF[3] location in ECEF coordinates - * @param[out] LLA[3] latitude longitude alititude coordinates - */ -int CoordinateConversions::ECEF2LLA(double ECEF[3], double LLA[3]) -{ - const double a = 6378137.0; // Equatorial Radius - const double e = 8.1819190842622e-2; // Eccentricity - double x=ECEF[0], y=ECEF[1], z=ECEF[2]; - double Lat, N, NplusH, delta, esLat; - uint16_t iter; - - LLA[1] = RAD2DEG*atan2(y,x); - N = a; - NplusH = N; - delta = 1; - Lat = 1; - iter=0; - - while (((delta > 1.0e-14)||(delta < -1.0e-14)) && (iter < 100)) - { - delta = Lat - atan(z / (sqrt(x*x + y*y)*(1-(N*e*e/NplusH)))); - Lat = Lat-delta; - esLat = e*sin(Lat); - N = a / sqrt(1 - esLat*esLat); - NplusH = sqrt(x*x + y*y)/cos(Lat); - iter += 1; - } - - LLA[0] = RAD2DEG*Lat; - LLA[2] = NplusH - N; - - if (iter==500) return (0); - else return (1); -} - -/** - * Get the current location in Longitude, Latitude Altitude (above WSG-48 ellipsoid) - * @param[in] BaseECEF the ECEF of the home location (in cm) - * @param[in] NED the offset from the home location (in m) - * @param[out] position three element double for position in degrees and meters - * @returns - * @arg 0 success - * @arg -1 for failure - */ -int CoordinateConversions::GetLLA(double BaseECEFcm[3], double NED[3], double position[3]) -{ - int i; - // stored value is in cm, convert to m - double BaseECEFm[3] = {BaseECEFcm[0], BaseECEFcm[1], BaseECEFcm[2]}; - double BaseLLA[3]; - double ECEF[3]; - double Rne [3][3]; - - // Get LLA address to compute conversion matrix - ECEF2LLA(BaseECEFm, BaseLLA); - RneFromLLA(BaseLLA, Rne); - - /* P = ECEF + Rne' * NED */ - for(i = 0; i < 3; i++) - ECEF[i] = BaseECEFm[i] + Rne[0][i]*NED[0] + Rne[1][i]*NED[1] + Rne[2][i]*NED[2]; - - ECEF2LLA(ECEF,position); - - return 0; -} - -void CoordinateConversions::LLA2Base(double LLA[3], double BaseECEF[3], float Rne[3][3], float NED[3]) -{ - double ECEF[3]; - float diff[3]; - - LLA2ECEF(LLA, ECEF); - - diff[0] = (float)(ECEF[0] - BaseECEF[0]); - diff[1] = (float)(ECEF[1] - BaseECEF[1]); - diff[2] = (float)(ECEF[2] - BaseECEF[2]); - - NED[0] = Rne[0][0] * diff[0] + Rne[0][1] * diff[1] + Rne[0][2] * diff[2]; - NED[1] = Rne[1][0] * diff[0] + Rne[1][1] * diff[1] + Rne[1][2] * diff[2]; - NED[2] = Rne[2][0] * diff[0] + Rne[2][1] * diff[1] + Rne[2][2] * diff[2]; -} - -// ****** find roll, pitch, yaw from quaternion ******** -void CoordinateConversions::Quaternion2RPY(const float q[4], float rpy[3]) -{ - float R13, R11, R12, R23, R33; - float q0s = q[0] * q[0]; - float q1s = q[1] * q[1]; - float q2s = q[2] * q[2]; - float q3s = q[3] * q[3]; - - R13 = 2 * (q[1] * q[3] - q[0] * q[2]); - R11 = q0s + q1s - q2s - q3s; - R12 = 2 * (q[1] * q[2] + q[0] * q[3]); - R23 = 2 * (q[2] * q[3] + q[0] * q[1]); - R33 = q0s - q1s - q2s + q3s; - - rpy[1] = RAD2DEG * asinf(-R13); // pitch always between -pi/2 to pi/2 - rpy[2] = RAD2DEG * atan2f(R12, R11); - rpy[0] = RAD2DEG * atan2f(R23, R33); - - //TODO: consider the cases where |R13| ~= 1, |pitch| ~= pi/2 -} - -// ****** find quaternion from roll, pitch, yaw ******** -void CoordinateConversions::RPY2Quaternion(const float rpy[3], float q[4]) -{ - float phi, theta, psi; - float cphi, sphi, ctheta, stheta, cpsi, spsi; - - phi = DEG2RAD * rpy[0] / 2; - theta = DEG2RAD * rpy[1] / 2; - psi = DEG2RAD * rpy[2] / 2; - cphi = cosf(phi); - sphi = sinf(phi); - ctheta = cosf(theta); - stheta = sinf(theta); - cpsi = cosf(psi); - spsi = sinf(psi); - - q[0] = cphi * ctheta * cpsi + sphi * stheta * spsi; - q[1] = sphi * ctheta * cpsi - cphi * stheta * spsi; - q[2] = cphi * stheta * cpsi + sphi * ctheta * spsi; - q[3] = cphi * ctheta * spsi - sphi * stheta * cpsi; - - if (q[0] < 0) { // q0 always positive for uniqueness - q[0] = -q[0]; - q[1] = -q[1]; - q[2] = -q[2]; - q[3] = -q[3]; - } -} - -//** Find Rbe, that rotates a vector from earth fixed to body frame, from quaternion ** -void CoordinateConversions::Quaternion2R(const float q[4], float Rbe[3][3]) -{ - - float q0s = q[0] * q[0], q1s = q[1] * q[1], q2s = q[2] * q[2], q3s = q[3] * q[3]; - - Rbe[0][0] = q0s + q1s - q2s - q3s; - Rbe[0][1] = 2 * (q[1] * q[2] + q[0] * q[3]); - Rbe[0][2] = 2 * (q[1] * q[3] - q[0] * q[2]); - Rbe[1][0] = 2 * (q[1] * q[2] - q[0] * q[3]); - Rbe[1][1] = q0s - q1s + q2s - q3s; - Rbe[1][2] = 2 * (q[2] * q[3] + q[0] * q[1]); - Rbe[2][0] = 2 * (q[1] * q[3] + q[0] * q[2]); - Rbe[2][1] = 2 * (q[2] * q[3] - q[0] * q[1]); - Rbe[2][2] = q0s - q1s - q2s + q3s; -} - - -} diff --git a/libs/utils/coordinateconversions.h b/libs/utils/coordinateconversions.h deleted file mode 100644 index 60785e9b468db040aab4bcce59971dd163d61d09..0000000000000000000000000000000000000000 --- a/libs/utils/coordinateconversions.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - ****************************************************************************** - * - * @file coordinateconversions.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef COORDINATECONVERSIONS_H -#define COORDINATECONVERSIONS_H - -#include "utils_global.h" -#ifndef EXTERNAL_USE -#include "../extensionsystem/pluginmanager.h" -#include "../../plugins/uavobjects/uavobjectmanager.h" -#include "../../plugins/uavobjects/uavobject.h" -#endif -#include "math.h" - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT CoordinateConversions -{ -public: - CoordinateConversions(); - int GetLLA(double LLA[3], double NED[3], double position[3]); - void RneFromLLA(double LLA[3], double Rne[3][3]); - void LLA2ECEF(double LLA[3], double ECEF[3]); - int ECEF2LLA(double ECEF[3], double LLA[3]); - void LLA2Base(double LLA[3], double BaseECEF[3], float Rne[3][3], float NED[3]); - void Quaternion2RPY(const float q[4], float rpy[3]); - void RPY2Quaternion(const float rpy[3], float q[4]); - void Quaternion2R(const float q[4], float Rbe[3][3]); -}; - -} - -#endif /* COORDINATECONVERSIONS_H */ diff --git a/libs/utils/detailsbutton.cpp b/libs/utils/detailsbutton.cpp deleted file mode 100644 index 0424e2bb07628f0499987896eec1ea409acc1306..0000000000000000000000000000000000000000 --- a/libs/utils/detailsbutton.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - ****************************************************************************** - * - * @file detailsbutton.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "detailsbutton.h" - -using namespace Utils; - -DetailsButton::DetailsButton(QWidget *parent) -#ifdef Q_OS_MAC - : QPushButton(parent), -#else - : QToolButton(parent), -#endif - m_checked(false) -{ -#ifdef Q_OS_MAC - setAttribute(Qt::WA_MacSmallSize); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); -#else - setCheckable(true); -#endif - setText(tr("Show Details")); - connect(this, SIGNAL(clicked()), - this, SLOT(onClicked())); -} - -void DetailsButton::onClicked() -{ - m_checked = !m_checked; -} - -bool DetailsButton::isToggled() -{ - return m_checked; -} diff --git a/libs/utils/detailsbutton.h b/libs/utils/detailsbutton.h deleted file mode 100644 index c4b5d9bd994737d6ac1433d26516c75b8431ac22..0000000000000000000000000000000000000000 --- a/libs/utils/detailsbutton.h +++ /dev/null @@ -1,56 +0,0 @@ -/** - ****************************************************************************** - * - * @file detailsbutton.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef DETAILSBUTTON_H -#define DETAILSBUTTON_H - -#include -#include - -#include "utils_global.h" - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT DetailsButton -#ifdef Q_OS_MAC - : public QPushButton -#else - : public QToolButton -#endif -{ - Q_OBJECT -public: - DetailsButton(QWidget *parent=0); - bool isToggled(); -public slots: - void onClicked(); -private: - bool m_checked; -}; -} -#endif // DETAILSBUTTON_H diff --git a/libs/utils/detailswidget.cpp b/libs/utils/detailswidget.cpp deleted file mode 100644 index 0f8a4ad18f458b1c4e53abd90f8b74d8c5284203..0000000000000000000000000000000000000000 --- a/libs/utils/detailswidget.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/** - ****************************************************************************** - * - * @file detailswidget.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "detailswidget.h" -#include "detailsbutton.h" - -#include -#include -#include -#include -#include - -using namespace Utils; - -DetailsWidget::DetailsWidget(QWidget *parent) - : QWidget(parent), - m_summaryLabel(new QLabel(this)), - m_detailsButton(new DetailsButton(this)), - m_widget(0), - m_toolWidget(0), - m_grid(new QGridLayout(this)) - -{ - m_grid->setContentsMargins(4, 3, 4, 3); - - m_summaryLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - m_summaryLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - m_grid->addWidget(m_summaryLabel, 0, 0); - m_grid->addWidget(m_detailsButton, 0, 2, 1, 1, Qt::AlignBottom); - - m_dummyWidget = new QWidget(this); - m_dummyWidget->setMaximumHeight(4); - m_dummyWidget->setMaximumHeight(4); - m_dummyWidget->setVisible(false); - m_grid->addWidget(m_dummyWidget, 2, 0, 1, 1); - - connect(m_detailsButton, SIGNAL(clicked()), - this, SLOT(detailsButtonClicked())); -} - -DetailsWidget::~DetailsWidget() -{ - -} - -void DetailsWidget::paintEvent(QPaintEvent *paintEvent) -{ - //TL--> ___________ <-- TR - // | | - //ML-> ______________| <--MM | <--MR - // | | - //BL-> |_________________________| <-- BR - - - QWidget::paintEvent(paintEvent); - - if (!m_detailsButton->isToggled()) - return; - - const QRect detailsGeometry = m_detailsButton->geometry(); - const QRect widgetGeometry = m_widget ? m_widget->geometry() : QRect(x(), y() + height(), width(), 0); - - QPoint tl(detailsGeometry.topLeft()); - tl += QPoint(-3, -3); - - QPoint tr(detailsGeometry.topRight()); - tr += QPoint(3, -3); - - QPoint mm(detailsGeometry.left() - 3, widgetGeometry.top() - 3); - - QPoint ml(1, mm.y()); - - QPoint mr(tr.x(), mm.y()); - - int bottom = geometry().height() - 3; - QPoint bl(1, bottom); - QPoint br(tr.x(), bottom); - - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - p.setPen(Qt::NoPen); - - p.setBrush(palette().dark()); - p.drawRoundedRect(QRect(tl, br), 5, 5); - p.drawRoundedRect(QRect(ml, br), 5, 5); -} - -void DetailsWidget::detailsButtonClicked() -{ - bool visible = m_detailsButton->isToggled(); - if (m_widget) - m_widget->setVisible(visible); - m_dummyWidget->setVisible(visible); - fixUpLayout(); -} - -void DetailsWidget::setSummaryText(const QString &text) -{ - m_summaryLabel->setText(text); -} - -QString DetailsWidget::summaryText() const -{ - return m_summaryLabel->text(); -} - -bool DetailsWidget::expanded() const -{ - return m_detailsButton->isToggled(); -} - -void DetailsWidget::setExpanded(bool v) -{ - if (expanded() != v) - m_detailsButton->animateClick(); -} - -QWidget *DetailsWidget::widget() const -{ - return m_widget; -} - -void DetailsWidget::setWidget(QWidget *widget) -{ - if (m_widget == widget) - return; - if (m_widget) { - m_grid->removeWidget(m_widget); - m_widget = 0; - } - if (widget) { - m_grid->addWidget(widget, 1, 0, 1, 3); - m_widget = widget; - bool visible = m_detailsButton->isToggled(); - m_widget->setVisible(visible); - m_dummyWidget->setVisible(visible); - } -} - -void DetailsWidget::setToolWidget(QWidget *widget) -{ - if (m_toolWidget == widget) - return; - if (m_toolWidget) { - m_grid->removeWidget(m_toolWidget); - m_toolWidget = 0; - } - if (widget) { - m_grid->addWidget(widget, 0, 1, 1, 1, Qt::AlignBottom); - m_toolWidget = widget; - } -} - -QWidget *DetailsWidget::toolWidget() const -{ - return m_toolWidget; -} - -void DetailsWidget::fixUpLayout() -{ - if (!m_widget) - return; - QWidget *parent = m_widget; - QStack widgets; - while((parent = parent->parentWidget()) && parent && parent->layout()) { - widgets.push(parent); - parent->layout()->update(); - } - - while(!widgets.isEmpty()) { - widgets.pop()->layout()->activate(); - } -} diff --git a/libs/utils/detailswidget.h b/libs/utils/detailswidget.h deleted file mode 100644 index c5d6345e1343058b754ab407ac4063d03a0a717e..0000000000000000000000000000000000000000 --- a/libs/utils/detailswidget.h +++ /dev/null @@ -1,83 +0,0 @@ -/** - ****************************************************************************** - * - * @file detailswidget.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef DETAILSWIDGET_H -#define DETAILSWIDGET_H - -#include "utils_global.h" - -#include - -QT_BEGIN_NAMESPACE -class QLabel; -class QGridLayout; -QT_END_NAMESPACE - -namespace Utils { -class DetailsButton; - -class QTCREATOR_UTILS_EXPORT DetailsWidget : public QWidget -{ - Q_OBJECT - Q_PROPERTY(QString summaryText READ summaryText WRITE setSummaryText DESIGNABLE true) - Q_PROPERTY(bool expanded READ expanded WRITE setExpanded DESIGNABLE true) -public: - DetailsWidget(QWidget *parent = 0); - ~DetailsWidget(); - - void setSummaryText(const QString &text); - QString summaryText() const; - - bool expanded() const; - void setExpanded(bool); - - void setWidget(QWidget *widget); - QWidget *widget() const; - - void setToolWidget(QWidget *widget); - QWidget *toolWidget() const; - -protected: - void paintEvent(QPaintEvent *paintEvent); - -private slots: - void detailsButtonClicked(); - -private: - void fixUpLayout(); - QLabel *m_summaryLabel; - DetailsButton *m_detailsButton; - - QWidget *m_widget; - QWidget *m_toolWidget; - QWidget *m_dummyWidget; - QGridLayout *m_grid; -}; -} - -#endif // DETAILSWIDGET_H diff --git a/libs/utils/fancylineedit.cpp b/libs/utils/fancylineedit.cpp deleted file mode 100644 index 83d92fa88f29363bcccd4768e8d1ecc771dfd7d2..0000000000000000000000000000000000000000 --- a/libs/utils/fancylineedit.cpp +++ /dev/null @@ -1,311 +0,0 @@ -/** - ****************************************************************************** - * - * @file fancylineedit.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "fancylineedit.h" - -#include -#include -#include -#include -#include -#include -#include - -enum { margin = 6 }; - -namespace Utils { - -static inline QString sideToStyleSheetString(FancyLineEdit::Side side) -{ - return side == FancyLineEdit::Left ? QLatin1String("left") : QLatin1String("right"); -} - -// Format style sheet for the label containing the pixmap. It has a margin on -// the outer side of the whole FancyLineEdit. -static QString labelStyleSheet(FancyLineEdit::Side side) -{ - QString rc = QLatin1String("QLabel { margin-"); - rc += sideToStyleSheetString(side); - rc += QLatin1String(": "); - rc += QString::number(margin); - rc += QLatin1Char('}'); - return rc; -} - -// --------- FancyLineEditPrivate as QObject with label -// event filter - -class FancyLineEditPrivate : public QObject { -public: - explicit FancyLineEditPrivate(QLineEdit *parent); - - virtual bool eventFilter(QObject *obj, QEvent *event); - - const QString m_leftLabelStyleSheet; - const QString m_rightLabelStyleSheet; - - QLineEdit *m_lineEdit; - QPixmap m_pixmap; - QMenu *m_menu; - QLabel *m_menuLabel; - FancyLineEdit::Side m_side; - bool m_useLayoutDirection; - bool m_menuTabFocusTrigger; - QString m_hintText; - bool m_showingHintText; -}; - - -FancyLineEditPrivate::FancyLineEditPrivate(QLineEdit *parent) : - QObject(parent), - m_leftLabelStyleSheet(labelStyleSheet(FancyLineEdit::Left)), - m_rightLabelStyleSheet(labelStyleSheet(FancyLineEdit::Right)), - m_lineEdit(parent), - m_menu(0), - m_menuLabel(0), - m_side(FancyLineEdit::Left), - m_useLayoutDirection(false), - m_menuTabFocusTrigger(false), - m_showingHintText(false) -{ -} - -bool FancyLineEditPrivate::eventFilter(QObject *obj, QEvent *event) -{ - if (!m_menu || obj != m_menuLabel) - return QObject::eventFilter(obj, event); - - switch (event->type()) { - case QEvent::MouseButtonPress: { - const QMouseEvent *me = static_cast(event); - m_menu->exec(me->globalPos()); - return true; - } - case QEvent::FocusIn: - if (m_menuTabFocusTrigger) { - m_lineEdit->setFocus(); - m_menu->exec(m_menuLabel->mapToGlobal(m_menuLabel->rect().center())); - return true; - } - default: - break; - } - return QObject::eventFilter(obj, event); -} - -// --------- FancyLineEdit -FancyLineEdit::FancyLineEdit(QWidget *parent) : - QLineEdit(parent), - m_d(new FancyLineEditPrivate(this)) -{ - m_d->m_menuLabel = new QLabel(this); - m_d->m_menuLabel->installEventFilter(m_d); - updateMenuLabel(); - showHintText(); -} - -FancyLineEdit::~FancyLineEdit() -{ -} - -// Position the menu label left or right according to size. -// Called when switching side and from resizeEvent. -void FancyLineEdit::positionMenuLabel() -{ - switch (side()) { - case Left: - m_d->m_menuLabel->setGeometry(0, 0, m_d->m_pixmap.width()+margin, height()); - break; - case Right: - m_d->m_menuLabel->setGeometry(width() - m_d->m_pixmap.width() - margin, 0, - m_d->m_pixmap.width()+margin, height()); - break; - } -} - -void FancyLineEdit::updateStyleSheet(Side side) -{ - // Udate the LineEdit style sheet. Make room for the label on the - // respective side and set color according to whether we are showing the - // hint text - QString sheet = QLatin1String("QLineEdit{ padding-"); - sheet += sideToStyleSheetString(side); - sheet += QLatin1String(": "); - sheet += QString::number(m_d->m_pixmap.width() + margin); - sheet += QLatin1Char(';'); - if (m_d->m_showingHintText) - sheet += QLatin1String(" color: #BBBBBB;"); - sheet += QLatin1Char('}'); - setStyleSheet(sheet); -} - -void FancyLineEdit::updateMenuLabel() -{ - m_d->m_menuLabel->setPixmap(m_d->m_pixmap); - const Side s = side(); - switch (s) { - case Left: - m_d->m_menuLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); - m_d->m_menuLabel->setStyleSheet(m_d->m_leftLabelStyleSheet); - break; - case Right: - m_d->m_menuLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); - m_d->m_menuLabel->setStyleSheet(m_d->m_rightLabelStyleSheet); - break; - } - updateStyleSheet(s); - positionMenuLabel(); -} - -void FancyLineEdit::setSide(Side side) -{ - m_d->m_side = side; - updateMenuLabel(); -} - -FancyLineEdit::Side FancyLineEdit::side() const -{ - if (m_d->m_useLayoutDirection) - return qApp->layoutDirection() == Qt::LeftToRight ? Left : Right; - return m_d->m_side; -} - -void FancyLineEdit::resizeEvent(QResizeEvent *) -{ - positionMenuLabel(); -} - -void FancyLineEdit::setPixmap(const QPixmap &pixmap) -{ - m_d->m_pixmap = pixmap; - updateMenuLabel(); -} - -QPixmap FancyLineEdit::pixmap() const -{ - return m_d->m_pixmap; -} - -void FancyLineEdit::setMenu(QMenu *menu) -{ - m_d->m_menu = menu; -} - -QMenu *FancyLineEdit::menu() const -{ - return m_d->m_menu; -} - -bool FancyLineEdit::useLayoutDirection() const -{ - return m_d->m_useLayoutDirection; -} - -void FancyLineEdit::setUseLayoutDirection(bool v) -{ - m_d->m_useLayoutDirection = v; -} - -bool FancyLineEdit::isSideStored() const -{ - return !m_d->m_useLayoutDirection; -} - -bool FancyLineEdit::hasMenuTabFocusTrigger() const -{ - return m_d->m_menuTabFocusTrigger; -} - -void FancyLineEdit::setMenuTabFocusTrigger(bool v) -{ - if (m_d->m_menuTabFocusTrigger == v) - return; - - m_d->m_menuTabFocusTrigger = v; - m_d->m_menuLabel->setFocusPolicy(v ? Qt::TabFocus : Qt::NoFocus); -} - -QString FancyLineEdit::hintText() const -{ - return m_d->m_hintText; -} - -void FancyLineEdit::setHintText(const QString &ht) -{ - // Updating magic to make the property work in Designer. - if (ht == m_d->m_hintText) - return; - hideHintText(); - m_d->m_hintText = ht; - if (!hasFocus() && !ht.isEmpty()) - showHintText(); -} - -void FancyLineEdit::showHintText() -{ - if (!m_d->m_showingHintText && text().isEmpty() && !m_d->m_hintText.isEmpty()) { - m_d->m_showingHintText = true; - setText(m_d->m_hintText); - updateStyleSheet(side()); - } -} - -void FancyLineEdit::hideHintText() -{ - if (m_d->m_showingHintText && !m_d->m_hintText.isEmpty()) { - m_d->m_showingHintText = false; - setText(QString()); - updateStyleSheet(side()); - } -} - -void FancyLineEdit::focusInEvent(QFocusEvent *e) -{ - hideHintText(); - QLineEdit::focusInEvent(e); -} - -void FancyLineEdit::focusOutEvent(QFocusEvent *e) -{ - // Focus out: Switch to displaying the hint text unless - // there is user input - showHintText(); - QLineEdit::focusOutEvent(e); -} - -bool FancyLineEdit::isShowingHintText() const -{ - return m_d->m_showingHintText; -} - -QString FancyLineEdit::typedText() const -{ - return m_d->m_showingHintText ? QString() : text(); -} - -} // namespace Utils diff --git a/libs/utils/fancylineedit.h b/libs/utils/fancylineedit.h deleted file mode 100644 index f25c8507edfdeff0c4d8ed43821d1dff66dfb533..0000000000000000000000000000000000000000 --- a/libs/utils/fancylineedit.h +++ /dev/null @@ -1,109 +0,0 @@ -/** - ****************************************************************************** - * - * @file fancylineedit.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FANCYLINEEDIT_H -#define FANCYLINEEDIT_H - -#include "utils_global.h" - -#include - -namespace Utils { - -class FancyLineEditPrivate; - -/* A line edit with an embedded pixmap on one side that is connected to - * a menu. Additionally, it can display a grayed hintText (like "Type Here to") - * when not focussed and empty. When connecting to the changed signals and - * querying text, one has to be aware that the text is set to that hint - * text if isShowingHintText() returns true (that is, does not contain - * valid user input). - */ -class QTCREATOR_UTILS_EXPORT FancyLineEdit : public QLineEdit -{ - Q_DISABLE_COPY(FancyLineEdit) - Q_OBJECT - Q_ENUMS(Side) - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap DESIGNABLE true) - Q_PROPERTY(Side side READ side WRITE setSide DESIGNABLE isSideStored STORED isSideStored) - Q_PROPERTY(bool useLayoutDirection READ useLayoutDirection WRITE setUseLayoutDirection DESIGNABLE true) - Q_PROPERTY(bool menuTabFocusTrigger READ hasMenuTabFocusTrigger WRITE setMenuTabFocusTrigger DESIGNABLE true) - Q_PROPERTY(QString hintText READ hintText WRITE setHintText DESIGNABLE true) - -public: - enum Side {Left, Right}; - - explicit FancyLineEdit(QWidget *parent = 0); - ~FancyLineEdit(); - - QPixmap pixmap() const; - - void setMenu(QMenu *menu); - QMenu *menu() const; - - void setSide(Side side); - Side side() const; - - bool useLayoutDirection() const; - void setUseLayoutDirection(bool v); - - // Set whether tabbing in will trigger the menu. - bool hasMenuTabFocusTrigger() const; - void setMenuTabFocusTrigger(bool v); - - // Hint text that is displayed when no focus is set. - QString hintText() const; - - bool isShowingHintText() const; - - // Convenience for accessing the text that returns "" in case of isShowingHintText(). - QString typedText() const; - -public slots: - void setPixmap(const QPixmap &pixmap); - void setHintText(const QString &ht); - void showHintText(); - void hideHintText(); - -protected: - virtual void resizeEvent(QResizeEvent *e); - virtual void focusInEvent(QFocusEvent *e); - virtual void focusOutEvent(QFocusEvent *e); - -private: - bool isSideStored() const; - void updateMenuLabel(); - void positionMenuLabel(); - void updateStyleSheet(Side side); - - FancyLineEditPrivate *m_d; -}; - -} // namespace Utils - -#endif // FANCYLINEEDIT_H diff --git a/libs/utils/fancymainwindow.cpp b/libs/utils/fancymainwindow.cpp deleted file mode 100644 index 87090433441cef9dea70e5f5875a5b70845819b7..0000000000000000000000000000000000000000 --- a/libs/utils/fancymainwindow.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/** - ****************************************************************************** - * - * @file fancymainwindow.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "fancymainwindow.h" - -#include -#include -#include -#include - - -using namespace Utils; - -FancyMainWindow::FancyMainWindow(QWidget *parent) - : QMainWindow(parent), - m_locked(true), - m_handleDockVisibilityChanges(true) -{ -} - -QDockWidget *FancyMainWindow::addDockForWidget(QWidget *widget) -{ - QDockWidget *dockWidget = new QDockWidget(widget->windowTitle(), this); - dockWidget->setObjectName(widget->windowTitle()); - dockWidget->setWidget(widget); - connect(dockWidget->toggleViewAction(), SIGNAL(triggered()), - this, SLOT(onDockActionTriggered()), Qt::QueuedConnection); - connect(dockWidget, SIGNAL(visibilityChanged(bool)), - this, SLOT(onDockVisibilityChange(bool))); - connect(dockWidget, SIGNAL(topLevelChanged(bool)), - this, SLOT(onTopLevelChanged())); - m_dockWidgets.append(dockWidget); - m_dockWidgetActiveState.append(true); - updateDockWidget(dockWidget); - return dockWidget; -} - -void FancyMainWindow::updateDockWidget(QDockWidget *dockWidget) -{ - const QDockWidget::DockWidgetFeatures features = - (m_locked) ? QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable - : QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable; - QWidget *titleBarWidget = dockWidget->titleBarWidget(); - if (m_locked && !titleBarWidget && !dockWidget->isFloating()) - titleBarWidget = new QWidget(dockWidget); - else if ((!m_locked || dockWidget->isFloating()) && titleBarWidget) { - delete titleBarWidget; - titleBarWidget = 0; - } - dockWidget->setTitleBarWidget(titleBarWidget); - dockWidget->setFeatures(features); -} - -void FancyMainWindow::onDockActionTriggered() -{ - QDockWidget *dw = qobject_cast(sender()->parent()); - if (dw) { - if (dw->isVisible()) - dw->raise(); - } -} - -void FancyMainWindow::onDockVisibilityChange(bool visible) -{ - if (!m_handleDockVisibilityChanges) - return; - QDockWidget *dockWidget = qobject_cast(sender()); - int index = m_dockWidgets.indexOf(dockWidget); - m_dockWidgetActiveState[index] = visible; -} - -void FancyMainWindow::onTopLevelChanged() -{ - updateDockWidget(qobject_cast(sender())); -} - -void FancyMainWindow::setTrackingEnabled(bool enabled) -{ - if (enabled) { - m_handleDockVisibilityChanges = true; - for (int i = 0; i < m_dockWidgets.size(); ++i) - m_dockWidgetActiveState[i] = m_dockWidgets[i]->isVisible(); - } else { - m_handleDockVisibilityChanges = false; - } -} - -void FancyMainWindow::setLocked(bool locked) -{ - m_locked = locked; - foreach (QDockWidget *dockWidget, m_dockWidgets) { - updateDockWidget(dockWidget); - } -} - -void FancyMainWindow::hideEvent(QHideEvent *event) -{ - Q_UNUSED(event) - handleVisibilityChanged(false); -} - -void FancyMainWindow::showEvent(QShowEvent *event) -{ - Q_UNUSED(event) - handleVisibilityChanged(true); -} - -void FancyMainWindow::handleVisibilityChanged(bool visible) -{ - m_handleDockVisibilityChanges = false; - for (int i = 0; i < m_dockWidgets.size(); ++i) { - QDockWidget *dockWidget = m_dockWidgets.at(i); - if (dockWidget->isFloating()) { - dockWidget->setVisible(visible && m_dockWidgetActiveState.at(i)); - } - } - if (visible) - m_handleDockVisibilityChanges = true; -} - -void FancyMainWindow::saveSettings(QSettings *settings) const -{ - QHash hash = saveSettings(); - QHashIterator it(hash); - while (it.hasNext()) { - it.next(); - settings->setValue(it.key(), it.value()); - } -} - -void FancyMainWindow::restoreSettings(QSettings *settings) -{ - QHash hash; - foreach (const QString &key, settings->childKeys()) { - hash.insert(key, settings->value(key)); - } - restoreSettings(hash); -} - -QHash FancyMainWindow::saveSettings() const -{ - QHash settings; - settings["State"] = saveState(); - settings["Locked"] = m_locked; - for (int i = 0; i < m_dockWidgetActiveState.count(); ++i) { - settings[m_dockWidgets.at(i)->objectName()] = - m_dockWidgetActiveState.at(i); - } - return settings; -} - -void FancyMainWindow::restoreSettings(const QHash &settings) -{ - QByteArray ba = settings.value("State", QByteArray()).toByteArray(); - if (!ba.isEmpty()) - restoreState(ba); - m_locked = settings.value("Locked", true).toBool(); - for (int i = 0; i < m_dockWidgetActiveState.count(); ++i) { - m_dockWidgetActiveState[i] = settings.value(m_dockWidgets.at(i)->objectName(), false).toBool(); - } -} diff --git a/libs/utils/fancymainwindow.h b/libs/utils/fancymainwindow.h deleted file mode 100644 index fb8e03e33c7d5b7e7b2de3f9167c8ad7915d722c..0000000000000000000000000000000000000000 --- a/libs/utils/fancymainwindow.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - ****************************************************************************** - * - * @file fancymainwindow.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FANCYMAINWINDOW_H -#define FANCYMAINWINDOW_H - -#include "utils_global.h" - -#include -#include - -#include - -QT_BEGIN_NAMESPACE -class QSettings; -QT_END_NAMESPACE - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT FancyMainWindow : public QMainWindow -{ - Q_OBJECT - -public: - FancyMainWindow(QWidget *parent = 0); - - QDockWidget *addDockForWidget(QWidget *widget); - QList dockWidgets() const { return m_dockWidgets; } - - void setTrackingEnabled(bool enabled); - bool isLocked() const { return m_locked; } - - void saveSettings(QSettings *settings) const; - void restoreSettings(QSettings *settings); - QHash saveSettings() const; - void restoreSettings(const QHash &settings); - -public slots: - void setLocked(bool locked); - -protected: - void hideEvent(QHideEvent *event); - void showEvent(QShowEvent *event); - -private slots: - void onDockActionTriggered(); - void onDockVisibilityChange(bool); - void onTopLevelChanged(); - -private: - void updateDockWidget(QDockWidget *dockWidget); - void handleVisibilityChanged(bool visible); - - QList m_dockWidgets; - QList m_dockWidgetActiveState; - bool m_locked; - bool m_handleDockVisibilityChanges; //todo -}; - -} // namespace Utils - -#endif // FANCYMAINWINDOW_H diff --git a/libs/utils/filenamevalidatinglineedit.cpp b/libs/utils/filenamevalidatinglineedit.cpp deleted file mode 100644 index 2111f0afea64cbb1119027fad71e98cfe60fe232..0000000000000000000000000000000000000000 --- a/libs/utils/filenamevalidatinglineedit.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/** - ****************************************************************************** - * - * @file filenamevalidatinglineedit.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "filenamevalidatinglineedit.h" -#include "qtcassert.h" - -#include -#include - -namespace Utils { - -#define WINDOWS_DEVICES "CON|AUX|PRN|COM1|COM2|LPT1|LPT2|NUL" - -// Naming a file like a device name will break on Windows, even if it is -// "com1.txt". Since we are cross-platform, we generally disallow such file -// names. -static const QRegExp &windowsDeviceNoSubDirPattern() -{ - static const QRegExp rc(QLatin1String(WINDOWS_DEVICES), - Qt::CaseInsensitive); - QTC_ASSERT(rc.isValid(), return rc); - return rc; -} - -static const QRegExp &windowsDeviceSubDirPattern() -{ - static const QRegExp rc(QLatin1String(".*[/\\\\](" WINDOWS_DEVICES ")"), Qt::CaseInsensitive); - QTC_ASSERT(rc.isValid(), return rc); - return rc; -} - -// ----------- FileNameValidatingLineEdit -FileNameValidatingLineEdit::FileNameValidatingLineEdit(QWidget *parent) : - BaseValidatingLineEdit(parent), - m_allowDirectories(false), - m_unused(0) -{ -} - -bool FileNameValidatingLineEdit::allowDirectories() const -{ - return m_allowDirectories; -} - -void FileNameValidatingLineEdit::setAllowDirectories(bool v) -{ - m_allowDirectories = v; -} - -/* Validate a file base name, check for forbidden characters/strings. */ - -#ifdef Q_OS_WIN -# define SLASHES "/\\" -#else -# define SLASHES "/" -#endif - -static const char *notAllowedCharsSubDir = "?:&*\"|#%<> "; -static const char *notAllowedCharsNoSubDir = "?:&*\"|#%<> "SLASHES; - -static const char *notAllowedSubStrings[] = {".."}; - -bool FileNameValidatingLineEdit::validateFileName(const QString &name, - bool allowDirectories, - QString *errorMessage /* = 0*/) -{ - if (name.isEmpty()) { - if (errorMessage) - *errorMessage = tr("The name must not be empty"); - return false; - } - // Characters - const char *notAllowedChars = allowDirectories ? notAllowedCharsSubDir : notAllowedCharsNoSubDir; - for (const char *c = notAllowedChars; *c; c++) - if (name.contains(QLatin1Char(*c))) { - if (errorMessage) - *errorMessage = tr("The name must not contain any of the characters '%1'.").arg(QLatin1String(notAllowedChars)); - return false; - } - // Substrings - const int notAllowedSubStringCount = sizeof(notAllowedSubStrings)/sizeof(const char *); - for (int s = 0; s < notAllowedSubStringCount; s++) { - const QLatin1String notAllowedSubString(notAllowedSubStrings[s]); - if (name.contains(notAllowedSubString)) { - if (errorMessage) - *errorMessage = tr("The name must not contain '%1'.").arg(QString(notAllowedSubString)); - return false; - } - } - // Windows devices - bool matchesWinDevice = windowsDeviceNoSubDirPattern().exactMatch(name); - if (!matchesWinDevice && allowDirectories) - matchesWinDevice = windowsDeviceSubDirPattern().exactMatch(name); - if (matchesWinDevice) { - if (errorMessage) - *errorMessage = tr("The name must not match that of a MS Windows device. (%1)."). - arg(windowsDeviceNoSubDirPattern().pattern().replace(QLatin1Char('|'), QLatin1Char(','))); - return false; - } - return true; -} - -bool FileNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const -{ - return validateFileName(value, m_allowDirectories, errorMessage); -} - -} // namespace Utils diff --git a/libs/utils/filenamevalidatinglineedit.h b/libs/utils/filenamevalidatinglineedit.h deleted file mode 100644 index 7036ac332cb66c89e5fca9e2c89fa6be37d83313..0000000000000000000000000000000000000000 --- a/libs/utils/filenamevalidatinglineedit.h +++ /dev/null @@ -1,69 +0,0 @@ -/** - ****************************************************************************** - * - * @file filenamevalidatinglineedit.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FILENAMEVALIDATINGLINEEDIT_H -#define FILENAMEVALIDATINGLINEEDIT_H - -#include "basevalidatinglineedit.h" - -namespace Utils { - -/** - * A control that let's the user choose a file name, based on a QLineEdit. Has - * some validation logic for embedding into QWizardPage. - */ -class QTCREATOR_UTILS_EXPORT FileNameValidatingLineEdit : public BaseValidatingLineEdit -{ - Q_OBJECT - Q_DISABLE_COPY(FileNameValidatingLineEdit) - Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories) -public: - explicit FileNameValidatingLineEdit(QWidget *parent = 0); - - static bool validateFileName(const QString &name, - bool allowDirectories = false, - QString *errorMessage = 0); - - /** - * Sets whether entering directories is allowed. This will enable the user - * to enter slashes in the filename. Default is off. - */ - bool allowDirectories() const; - void setAllowDirectories(bool v); - -protected: - virtual bool validate(const QString &value, QString *errorMessage) const; - -private: - bool m_allowDirectories; - void *m_unused; -}; - -} // namespace Utils - -#endif // FILENAMEVALIDATINGLINEEDIT_H diff --git a/libs/utils/filesearch.cpp b/libs/utils/filesearch.cpp deleted file mode 100644 index b2d5a647e1f2f14bd2e35d99b988d6c781b4a708..0000000000000000000000000000000000000000 --- a/libs/utils/filesearch.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/** - ****************************************************************************** - * - * @file filesearch.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "filesearch.h" -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Utils; - -static inline QString msgCanceled(const QString &searchTerm, int numMatches, int numFilesSearched) -{ - return QCoreApplication::translate("Utils::FileSearch", - "%1: canceled. %n occurrences found in %2 files.", - 0, QCoreApplication::CodecForTr, numMatches). - arg(searchTerm).arg(numFilesSearched); -} - -static inline QString msgFound(const QString &searchTerm, int numMatches, int numFilesSearched) -{ - return QCoreApplication::translate("Utils::FileSearch", - "%1: %n occurrences found in %2 files.", - 0, QCoreApplication::CodecForTr, numMatches). - arg(searchTerm).arg(numFilesSearched); -} - -static inline QString msgFound(const QString &searchTerm, int numMatches, int numFilesSearched, int filesSize) -{ - return QCoreApplication::translate("Utils::FileSearch", - "%1: %n occurrences found in %2 of %3 files.", - 0, QCoreApplication::CodecForTr, numMatches). - arg(searchTerm).arg(numFilesSearched).arg(filesSize); -} - -namespace { - -void runFileSearch(QFutureInterface &future, - QString searchTerm, - QStringList files, - QTextDocument::FindFlags flags, - QMap fileToContentsMap) -{ - future.setProgressRange(0, files.size()); - int numFilesSearched = 0; - int numMatches = 0; - - bool caseInsensitive = !(flags & QTextDocument::FindCaseSensitively); - bool wholeWord = (flags & QTextDocument::FindWholeWords); - - QByteArray sa = searchTerm.toUtf8(); - int scMaxIndex = sa.length()-1; - const char *sc = sa.constData(); - - QByteArray sal = searchTerm.toLower().toUtf8(); - const char *scl = sal.constData(); - - QByteArray sau = searchTerm.toUpper().toUtf8(); - const char *scu = sau.constData(); - - int chunkSize = qMax(100000, sa.length()); - - QFile file; - QBuffer buffer; - foreach (QString s, files) { - if (future.isPaused()) - future.waitForResume(); - if (future.isCanceled()) { - future.setProgressValueAndText(numFilesSearched, msgCanceled(searchTerm, numMatches, numFilesSearched)); - break; - } - QIODevice *device; - if (fileToContentsMap.contains(s)) { - buffer.setData(fileToContentsMap.value(s).toLocal8Bit()); - device = &buffer; - } else { - file.setFileName(s); - device = &file; - } - if (!device->open(QIODevice::ReadOnly)) - continue; - int lineNr = 1; - const char *startOfLastLine = NULL; - - bool firstChunk = true; - while (!device->atEnd()) { - if (!firstChunk) - device->seek(device->pos()-sa.length()+1); - - const QByteArray chunk = device->read(chunkSize); - const char *chunkPtr = chunk.constData(); - startOfLastLine = chunkPtr; - for (const char *regionPtr = chunkPtr; regionPtr < chunkPtr + chunk.length()-scMaxIndex; ++regionPtr) { - const char *regionEnd = regionPtr + scMaxIndex; - - if (*regionPtr == '\n') { - startOfLastLine = regionPtr + 1; - ++lineNr; - } - else if ( - // case sensitive - (!caseInsensitive && *regionPtr == sc[0] && *regionEnd == sc[scMaxIndex]) - || - // case insensitive - (caseInsensitive && (*regionPtr == scl[0] || *regionPtr == scu[0]) - && (*regionEnd == scl[scMaxIndex] || *regionEnd == scu[scMaxIndex])) - ) { - const char *afterRegion = regionEnd + 1; - const char *beforeRegion = regionPtr - 1; - bool equal = true; - if (wholeWord && - ( isalnum(*beforeRegion) - || (*beforeRegion == '_') - || isalnum(*afterRegion) - || (*afterRegion == '_'))) { - equal = false; - } - - int regionIndex = 1; - for (const char *regionCursor = regionPtr + 1; regionCursor < regionEnd; ++regionCursor, ++regionIndex) { - if ( // case sensitive - (!caseInsensitive && equal && *regionCursor != sc[regionIndex]) - || - // case insensitive - (caseInsensitive && equal && *regionCursor != sc[regionIndex] && *regionCursor != scl[regionIndex] && *regionCursor != scu[regionIndex]) - ) { - equal = false; - } - } - if (equal) { - int textLength = chunk.length() - (startOfLastLine - chunkPtr); - if (textLength > 0) { - QByteArray res; - res.reserve(256); - int i = 0; - int n = 0; - while (startOfLastLine[i] != '\n' && startOfLastLine[i] != '\r' && i < textLength && n++ < 256) - res.append(startOfLastLine[i++]); - future.reportResult(FileSearchResult(s, lineNr, QString(res), - regionPtr - startOfLastLine, sa.length())); - ++numMatches; - } - } - } - } - firstChunk = false; - } - ++numFilesSearched; - future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched, files.size())); - device->close(); - } - if (!future.isCanceled()) - future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched)); -} - -void runFileSearchRegExp(QFutureInterface &future, - QString searchTerm, - QStringList files, - QTextDocument::FindFlags flags, - QMap fileToContentsMap) -{ - future.setProgressRange(0, files.size()); - int numFilesSearched = 0; - int numMatches = 0; - if (flags & QTextDocument::FindWholeWords) - searchTerm = QString::fromLatin1("\\b%1\\b").arg(searchTerm); - const Qt::CaseSensitivity caseSensitivity = (flags & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive; - const QRegExp expression(searchTerm, caseSensitivity); - - QFile file; - QString str; - QTextStream stream; - foreach (const QString &s, files) { - if (future.isPaused()) - future.waitForResume(); - if (future.isCanceled()) { - future.setProgressValueAndText(numFilesSearched, msgCanceled(searchTerm, numMatches, numFilesSearched)); - break; - } - - bool needsToCloseFile = false; - if (fileToContentsMap.contains(s)) { - str = fileToContentsMap.value(s); - stream.setString(&str); - } else { - file.setFileName(s); - if (!file.open(QIODevice::ReadOnly)) - continue; - needsToCloseFile = true; - stream.setDevice(&file); - } - int lineNr = 1; - QString line; - while (!stream.atEnd()) { - line = stream.readLine(); - int pos = 0; - while ((pos = expression.indexIn(line, pos)) != -1) { - future.reportResult(FileSearchResult(s, lineNr, line, - pos, expression.matchedLength())); - pos += expression.matchedLength(); - } - ++lineNr; - } - ++numFilesSearched; - future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched, files.size())); - if (needsToCloseFile) - file.close(); - } - if (!future.isCanceled()) - future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched)); -} - -} // namespace - - -QFuture Utils::findInFiles(const QString &searchTerm, const QStringList &files, - QTextDocument::FindFlags flags, QMap fileToContentsMap) -{ - return QtConcurrent::run > - (runFileSearch, searchTerm, files, flags, fileToContentsMap); -} - -QFuture Utils::findInFilesRegExp(const QString &searchTerm, const QStringList &files, - QTextDocument::FindFlags flags, QMap fileToContentsMap) -{ - return QtConcurrent::run > - (runFileSearchRegExp, searchTerm, files, flags, fileToContentsMap); -} diff --git a/libs/utils/filesearch.h b/libs/utils/filesearch.h deleted file mode 100644 index c7a046b0f8ebf9cfcfb8e4089f908967f4e28119..0000000000000000000000000000000000000000 --- a/libs/utils/filesearch.h +++ /dev/null @@ -1,64 +0,0 @@ -/** - ****************************************************************************** - * - * @file filesearch.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FILESEARCH_H -#define FILESEARCH_H - -#include "utils_global.h" - -#include -#include -#include -#include - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT FileSearchResult -{ -public: - FileSearchResult() {} - FileSearchResult(QString fileName, int lineNumber, QString matchingLine, int matchStart, int matchLength) - : fileName(fileName), lineNumber(lineNumber), matchingLine(matchingLine), matchStart(matchStart), matchLength(matchLength) - { - } - QString fileName; - int lineNumber; - QString matchingLine; - int matchStart; - int matchLength; -}; - -QTCREATOR_UTILS_EXPORT QFuture findInFiles(const QString &searchTerm, const QStringList &files, - QTextDocument::FindFlags flags, QMap fileToContentsMap = QMap()); - -QTCREATOR_UTILS_EXPORT QFuture findInFilesRegExp(const QString &searchTerm, const QStringList &files, - QTextDocument::FindFlags flags, QMap fileToContentsMap = QMap()); - -} // namespace Utils - -#endif // FILESEARCH_H diff --git a/libs/utils/filewizarddialog.cpp b/libs/utils/filewizarddialog.cpp deleted file mode 100644 index 615b3b0cabe059c35413e80b1e6fdc4fd19a7c7b..0000000000000000000000000000000000000000 --- a/libs/utils/filewizarddialog.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - ****************************************************************************** - * - * @file filewizarddialog.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "filewizarddialog.h" -#include "filewizardpage.h" - -#include - -namespace Utils { - -FileWizardDialog::FileWizardDialog(QWidget *parent) : - QWizard(parent), - m_filePage(new FileWizardPage) -{ - setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - setOption(QWizard::NoCancelButton, false); - setOption(QWizard::NoDefaultButton, false); - setPixmap(QWizard::WatermarkPixmap, QPixmap(QLatin1String(":/core/images/qtwatermark.png"))); - addPage(m_filePage); - connect(m_filePage, SIGNAL(activated()), button(QWizard::FinishButton), SLOT(animateClick())); -} - -QString FileWizardDialog::name() const -{ - return m_filePage->name(); -} - -QString FileWizardDialog::path() const -{ - return m_filePage->path(); -} - -void FileWizardDialog::setPath(const QString &path) -{ - m_filePage->setPath(path); - -} - -void FileWizardDialog::setName(const QString &name) -{ - m_filePage->setName(name); -} - -} // namespace Utils diff --git a/libs/utils/filewizarddialog.h b/libs/utils/filewizarddialog.h deleted file mode 100644 index f68e203ce9e3cf35ebbde0f9539382459c305270..0000000000000000000000000000000000000000 --- a/libs/utils/filewizarddialog.h +++ /dev/null @@ -1,64 +0,0 @@ -/** - ****************************************************************************** - * - * @file filewizarddialog.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FILEWIZARDDIALOG_H -#define FILEWIZARDDIALOG_H - -#include "utils_global.h" - -#include - -namespace Utils { - -class FileWizardPage; - -/* - Standard wizard for a single file letting the user choose name - and path. Custom pages can be added via Core::IWizardExtension. -*/ - -class QTCREATOR_UTILS_EXPORT FileWizardDialog : public QWizard { - Q_OBJECT - Q_DISABLE_COPY(FileWizardDialog) -public: - explicit FileWizardDialog(QWidget *parent = 0); - - QString name() const; - QString path() const; - -public slots: - void setPath(const QString &path); - void setName(const QString &name); - -private: - FileWizardPage *m_filePage; -}; - -} // namespace Utils - -#endif // FILEWIZARDDIALOG_H diff --git a/libs/utils/filewizardpage.cpp b/libs/utils/filewizardpage.cpp deleted file mode 100644 index 17f16e06560714c3f0dface5dbf0ce971e758100..0000000000000000000000000000000000000000 --- a/libs/utils/filewizardpage.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/** - ****************************************************************************** - * - * @file filewizardpage.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "filewizardpage.h" -#include "ui_filewizardpage.h" - -namespace Utils { - -struct FileWizardPagePrivate -{ - FileWizardPagePrivate(); - Ui::WizardPage m_ui; - bool m_complete; -}; - -FileWizardPagePrivate::FileWizardPagePrivate() : - m_complete(false) -{ -} - -FileWizardPage::FileWizardPage(QWidget *parent) : - QWizardPage(parent), - m_d(new FileWizardPagePrivate) -{ - m_d->m_ui.setupUi(this); - connect(m_d->m_ui.pathChooser, SIGNAL(validChanged()), this, SLOT(slotValidChanged())); - connect(m_d->m_ui.nameLineEdit, SIGNAL(validChanged()), this, SLOT(slotValidChanged())); - - connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()), this, SLOT(slotActivated())); - connect(m_d->m_ui.nameLineEdit, SIGNAL(validReturnPressed()), this, SLOT(slotActivated())); -} - -FileWizardPage::~FileWizardPage() -{ - delete m_d; -} - -QString FileWizardPage::name() const -{ - return m_d->m_ui.nameLineEdit->text(); -} - -QString FileWizardPage::path() const -{ - return m_d->m_ui.pathChooser->path(); -} - -void FileWizardPage::setPath(const QString &path) -{ - m_d->m_ui.pathChooser->setPath(path); -} - -void FileWizardPage::setName(const QString &name) -{ - m_d->m_ui.nameLineEdit->setText(name); -} - -void FileWizardPage::changeEvent(QEvent *e) -{ - QWizardPage::changeEvent(e); - switch (e->type()) { - case QEvent::LanguageChange: - m_d->m_ui.retranslateUi(this); - break; - default: - break; - } -} - -bool FileWizardPage::isComplete() const -{ - return m_d->m_complete; -} - -void FileWizardPage::setNameLabel(const QString &label) -{ - m_d->m_ui.nameLabel->setText(label); -} - -void FileWizardPage::setPathLabel(const QString &label) -{ - m_d->m_ui.pathLabel->setText(label); -} - -void FileWizardPage::slotValidChanged() -{ - const bool newComplete = m_d->m_ui.pathChooser->isValid() && m_d->m_ui.nameLineEdit->isValid(); - if (newComplete != m_d->m_complete) { - m_d->m_complete = newComplete; - emit completeChanged(); - } -} - -void FileWizardPage::slotActivated() -{ - if (m_d->m_complete) - emit activated(); -} - -bool FileWizardPage::validateBaseName(const QString &name, QString *errorMessage /* = 0*/) -{ - return FileNameValidatingLineEdit::validateFileName(name, false, errorMessage); -} - -} // namespace Utils diff --git a/libs/utils/filewizardpage.h b/libs/utils/filewizardpage.h deleted file mode 100644 index 88d8b01e1d7218502be966ca5d1cc3e2c90d094a..0000000000000000000000000000000000000000 --- a/libs/utils/filewizardpage.h +++ /dev/null @@ -1,89 +0,0 @@ -/** - ****************************************************************************** - * - * @file filewizardpage.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef FILEWIZARDPAGE_H -#define FILEWIZARDPAGE_H - -#include "utils_global.h" - -#include - -namespace Utils { - -struct FileWizardPagePrivate; - -/** - * Standard wizard page for a single file letting the user choose name - * and path. Sets the "FileNames" QWizard field. - * - * The name and path labels can be changed. By default they are simply "Name:" - * and "Path:". - */ -class QTCREATOR_UTILS_EXPORT FileWizardPage : public QWizardPage -{ - Q_OBJECT - Q_DISABLE_COPY(FileWizardPage) - Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true) - Q_PROPERTY(QString name READ name WRITE setName DESIGNABLE true) -public: - explicit FileWizardPage(QWidget *parent = 0); - virtual ~FileWizardPage(); - - QString name() const; - QString path() const; - - virtual bool isComplete() const; - - void setNameLabel(const QString &label); - void setPathLabel(const QString &label); - - // Validate a base name entry field (potentially containing extension) - static bool validateBaseName(const QString &name, QString *errorMessage = 0); - -signals: - void activated(); - void pathChanged(); - -public slots: - void setPath(const QString &path); - void setName(const QString &name); - -private slots: - void slotValidChanged(); - void slotActivated(); - -protected: - virtual void changeEvent(QEvent *e); - -private: - FileWizardPagePrivate *m_d; -}; - -} // namespace Utils - -#endif // FILEWIZARDPAGE_H diff --git a/libs/utils/filewizardpage.ui b/libs/utils/filewizardpage.ui deleted file mode 100644 index 2657a586bdd350cda06dc504f6bfced6cb5ff82d..0000000000000000000000000000000000000000 --- a/libs/utils/filewizardpage.ui +++ /dev/null @@ -1,54 +0,0 @@ - - - Utils::WizardPage - - - - 0 - 0 - 196 - 68 - - - - Choose the location - - - - - - Name: - - - - - - - - - - Path: - - - - - - - - - - - Utils::PathChooser - QWidget -
pathchooser.h
- 1 -
- - Utils::FileNameValidatingLineEdit - QLineEdit -
filenamevalidatinglineedit.h
-
-
- - -
diff --git a/libs/utils/homelocationutil.cpp b/libs/utils/homelocationutil.cpp deleted file mode 100644 index a4de2bef442e3668e4a1fd7df9b9a4deae5e4571..0000000000000000000000000000000000000000 --- a/libs/utils/homelocationutil.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/** - ****************************************************************************** - * - * @file homelocationutil.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * @brief Utilities to find the location of openpilot GCS files: - * - Plugins Share directory path - * - * @brief Home location utility functions - * - * @see The GNU Public License (GPL) Version 3 - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "homelocationutil.h" - -#include -#include -#include - -#include "coordinateconversions.h" -#include "worldmagmodel.h" - -namespace Utils { - - HomeLocationUtil::HomeLocationUtil() - { -// Initialize(); - } - - // input params: LLA - // - // output params: ECEF, RNE and Be - int HomeLocationUtil::getDetails(double LLA[3], double ECEF[3], double RNE[9], double Be[3]) - { - // ************* - // check input parms - - double latitude = LLA[0]; - double longitude = LLA[1]; - double altitude = LLA[2]; - - if (latitude != latitude) return -1; // prevent nan error - if (longitude != longitude) return -2; // prevent nan error - if (altitude != altitude) return -3; // prevent nan error - - if (latitude < -90 || latitude > 90) return -4; // range checking - if (longitude < -180 || longitude > 180) return -5; // range checking - - // ************* - - QDateTime dt = QDateTime::currentDateTime().toUTC(); - - CoordinateConversions().LLA2ECEF(LLA, ECEF); - CoordinateConversions().RneFromLLA(LLA, (double (*)[3])RNE); - if (WorldMagModel().GetMagVector(LLA, dt.date().month(), dt.date().day(), dt.date().year(), Be) < 0) - return -6; - - return 0; // OK - } - -} diff --git a/libs/utils/homelocationutil.h b/libs/utils/homelocationutil.h deleted file mode 100644 index cf1023f78ef6c2000db55cbd66f6564c882f12bd..0000000000000000000000000000000000000000 --- a/libs/utils/homelocationutil.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - ****************************************************************************** - * - * @file homelocationutil.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef HOMELOCATIONUTIL_H -#define HOMELOCATIONUTIL_H - -#include "utils_global.h" - -// ****************************** - -namespace Utils { - - class QTCREATOR_UTILS_EXPORT HomeLocationUtil - { - public: - HomeLocationUtil(); - - int getDetails(double LLA[3], double ECEF[3], double RNE[9], double Be[3]); - - private: - - }; - -} - -// ****************************** - -#endif diff --git a/libs/utils/images/removesubmitfield.png b/libs/utils/images/removesubmitfield.png deleted file mode 100644 index e4139afc552b36d5d1aabf2fe2697d00d61b6d70..0000000000000000000000000000000000000000 Binary files a/libs/utils/images/removesubmitfield.png and /dev/null differ diff --git a/libs/utils/iwelcomepage.cpp b/libs/utils/iwelcomepage.cpp deleted file mode 100644 index c6cac187fee76b8cb4bd2721e34ad1e4fd02157d..0000000000000000000000000000000000000000 --- a/libs/utils/iwelcomepage.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - ****************************************************************************** - * - * @file iwelcomepage.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "iwelcomepage.h" - -using namespace Utils; - -IWelcomePage::IWelcomePage() -{ - -} - -IWelcomePage::~IWelcomePage() -{ - -} diff --git a/libs/utils/iwelcomepage.h b/libs/utils/iwelcomepage.h deleted file mode 100644 index 34d910bbbd07e47ce4c4e8daf807b24c70341b5d..0000000000000000000000000000000000000000 --- a/libs/utils/iwelcomepage.h +++ /dev/null @@ -1,60 +0,0 @@ -/** - ****************************************************************************** - * - * @file iwelcomepage.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef IWELCOMEPAGE_H -#define IWELCOMEPAGE_H - - -#include "utils_global.h" - -#include - -namespace Utils { - -class IWelcomePagePrivate; - -class QTCREATOR_UTILS_EXPORT IWelcomePage : public QObject -{ - Q_OBJECT - -public: - IWelcomePage(); - virtual ~IWelcomePage(); - - virtual QWidget *page() = 0; - virtual QString title() const = 0; - virtual int priority() const { return 0; } - -private: - // not used atm - IWelcomePagePrivate *m_d; -}; - -} - -#endif // IWELCOMEPAGE_H diff --git a/libs/utils/linecolumnlabel.cpp b/libs/utils/linecolumnlabel.cpp deleted file mode 100644 index 1c59b1a0d7f75d7986112d577dcbf86827c16805..0000000000000000000000000000000000000000 --- a/libs/utils/linecolumnlabel.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - ****************************************************************************** - * - * @file linecolumnlabel.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "linecolumnlabel.h" - -namespace Utils { - -LineColumnLabel::LineColumnLabel(QWidget *parent) - : QLabel(parent), m_unused(0) -{ -} - -LineColumnLabel::~LineColumnLabel() -{ -} - -void LineColumnLabel::setText(const QString &text, const QString &maxText) -{ - QLabel::setText(text); - m_maxText = maxText; -} -QSize LineColumnLabel::sizeHint() const -{ - return fontMetrics().boundingRect(m_maxText).size(); -} - -QString LineColumnLabel::maxText() const -{ - return m_maxText; -} - -void LineColumnLabel::setMaxText(const QString &maxText) -{ - m_maxText = maxText; -} - -} // namespace Utils diff --git a/libs/utils/linecolumnlabel.h b/libs/utils/linecolumnlabel.h deleted file mode 100644 index 836598da23554a7ee455d383e6f4aca865ccb8eb..0000000000000000000000000000000000000000 --- a/libs/utils/linecolumnlabel.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - ****************************************************************************** - * - * @file linecolumnlabel.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef LINECOLUMNLABEL_H -#define LINECOLUMNLABEL_H - -#include "utils_global.h" -#include - -namespace Utils { - -/* A label suitable for displaying cursor positions, etc. with a fixed - * with derived from a sample text. */ - -class QTCREATOR_UTILS_EXPORT LineColumnLabel : public QLabel -{ - Q_DISABLE_COPY(LineColumnLabel) - Q_OBJECT - Q_PROPERTY(QString maxText READ maxText WRITE setMaxText DESIGNABLE true) - -public: - explicit LineColumnLabel(QWidget *parent = 0); - virtual ~LineColumnLabel(); - - void setText(const QString &text, const QString &maxText); - QSize sizeHint() const; - - QString maxText() const; - void setMaxText(const QString &maxText); - -private: - QString m_maxText; - void *m_unused; -}; - -} // namespace Utils - -#endif // LINECOLUMNLABEL_H diff --git a/libs/utils/listutils.h b/libs/utils/listutils.h deleted file mode 100644 index b3c079c02d7a70aeb09b0c83f9cfc8ba5de2fd91..0000000000000000000000000000000000000000 --- a/libs/utils/listutils.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - ****************************************************************************** - * - * @file listutils.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef LISTUTILS_H -#define LISTUTILS_H - -#include - -namespace Utils { - -template -QList qwConvertList(const QList &list) -{ - QList convertedList; - foreach (T2 listEntry, list) { - convertedList << qobject_cast(listEntry); - } - return convertedList; -} - -} // namespace Utils - -#endif // LISTUTILS_H diff --git a/libs/utils/newclasswidget.cpp b/libs/utils/newclasswidget.cpp deleted file mode 100644 index 61d7c52a432be4dbf0e535c59f176bc7d5cf4c3e..0000000000000000000000000000000000000000 --- a/libs/utils/newclasswidget.cpp +++ /dev/null @@ -1,510 +0,0 @@ -/** - ****************************************************************************** - * - * @file newclasswidget.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "newclasswidget.h" -#include "ui_newclasswidget.h" - -#include - -#include -#include -#include -#include -#include -#include - -enum { debugNewClassWidget = 0 }; - -namespace Utils { - -struct NewClassWidgetPrivate { - NewClassWidgetPrivate(); - - Ui::NewClassWidget m_ui; - QString m_headerExtension; - QString m_sourceExtension; - QString m_formExtension; - bool m_valid; - bool m_classEdited; - // Store the "visible" values to prevent the READ accessors from being - // fooled by a temporarily hidden widget - bool m_baseClassInputVisible; - bool m_formInputVisible; - bool m_pathInputVisible; - bool m_qobjectCheckBoxVisible; - bool m_formInputCheckable; -}; - -NewClassWidgetPrivate:: NewClassWidgetPrivate() : - m_headerExtension(QLatin1String("h")), - m_sourceExtension(QLatin1String("cpp")), - m_formExtension(QLatin1String("ui")), - m_valid(false), - m_classEdited(false), - m_baseClassInputVisible(true), - m_formInputVisible(true), - m_pathInputVisible(true), - m_qobjectCheckBoxVisible(false), - m_formInputCheckable(false) - -{ -} - -// --------------------- NewClassWidget -NewClassWidget::NewClassWidget(QWidget *parent) : - QWidget(parent), - m_d(new NewClassWidgetPrivate) -{ - m_d->m_ui.setupUi(this); - - m_d->m_ui.baseClassComboBox->setEditable(false); - - connect(m_d->m_ui.classLineEdit, SIGNAL(updateFileName(QString)), - this, SLOT(slotUpdateFileNames(QString))); - connect(m_d->m_ui.classLineEdit, SIGNAL(textEdited(QString)), - this, SLOT(classNameEdited())); - connect(m_d->m_ui.baseClassComboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(suggestClassNameFromBase())); - connect(m_d->m_ui.baseClassComboBox, SIGNAL(editTextChanged(QString)), - this, SLOT(slotValidChanged())); - connect(m_d->m_ui.classLineEdit, SIGNAL(validChanged()), - this, SLOT(slotValidChanged())); - connect(m_d->m_ui.headerFileLineEdit, SIGNAL(validChanged()), - this, SLOT(slotValidChanged())); - connect(m_d->m_ui.sourceFileLineEdit, SIGNAL(validChanged()), - this, SLOT(slotValidChanged())); - connect(m_d->m_ui.formFileLineEdit, SIGNAL(validChanged()), - this, SLOT(slotValidChanged())); - connect(m_d->m_ui.pathChooser, SIGNAL(validChanged()), - this, SLOT(slotValidChanged())); - - connect(m_d->m_ui.classLineEdit, SIGNAL(validReturnPressed()), - this, SLOT(slotActivated())); - connect(m_d->m_ui.headerFileLineEdit, SIGNAL(validReturnPressed()), - this, SLOT(slotActivated())); - connect(m_d->m_ui.sourceFileLineEdit, SIGNAL(validReturnPressed()), - this, SLOT(slotActivated())); - connect(m_d->m_ui.formFileLineEdit, SIGNAL(validReturnPressed()), - this, SLOT(slotActivated())); - connect(m_d->m_ui.formFileLineEdit, SIGNAL(validReturnPressed()), - this, SLOT(slotActivated())); - connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()), - this, SLOT(slotActivated())); - - connect(m_d->m_ui.generateFormCheckBox, SIGNAL(stateChanged(int)), - this, SLOT(slotFormInputChecked())); - - m_d->m_ui.generateFormCheckBox->setChecked(true); - setFormInputCheckable(false, true); - setClassType(NoClassType); -} - -NewClassWidget::~NewClassWidget() -{ - delete m_d; -} - -void NewClassWidget::classNameEdited() -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << m_d->m_headerExtension << m_d->m_sourceExtension; - m_d->m_classEdited = true; -} - -void NewClassWidget::suggestClassNameFromBase() -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << m_d->m_headerExtension << m_d->m_sourceExtension; - if (m_d->m_classEdited) - return; - // Suggest a class unless edited ("QMainWindow"->"MainWindow") - QString base = baseClassName(); - if (base.startsWith(QLatin1Char('Q'))) { - base.remove(0, 1); - setClassName(base); - } -} - -QStringList NewClassWidget::baseClassChoices() const -{ - QStringList rc; - const int count = m_d->m_ui.baseClassComboBox->count(); - for (int i = 0; i < count; i++) - rc.push_back(m_d->m_ui.baseClassComboBox->itemText(i)); - return rc; -} - -void NewClassWidget::setBaseClassChoices(const QStringList &choices) -{ - m_d->m_ui.baseClassComboBox->clear(); - m_d->m_ui.baseClassComboBox->addItems(choices); -} - -void NewClassWidget::setBaseClassInputVisible(bool visible) -{ - m_d->m_baseClassInputVisible = visible; - m_d->m_ui.baseClassLabel->setVisible(visible); - m_d->m_ui.baseClassComboBox->setVisible(visible); -} - -void NewClassWidget::setBaseClassEditable(bool editable) -{ - m_d->m_ui.baseClassComboBox->setEditable(editable); -} - -bool NewClassWidget::isBaseClassInputVisible() const -{ - return m_d->m_baseClassInputVisible; -} - -bool NewClassWidget::isBaseClassEditable() const -{ - return m_d->m_ui.baseClassComboBox->isEditable(); -} - -void NewClassWidget::setFormInputVisible(bool visible) -{ - m_d->m_formInputVisible = visible; - m_d->m_ui.formLabel->setVisible(visible); - m_d->m_ui.formFileLineEdit->setVisible(visible); -} - -bool NewClassWidget::isFormInputVisible() const -{ - return m_d->m_formInputVisible; -} - -void NewClassWidget::setFormInputCheckable(bool checkable) -{ - setFormInputCheckable(checkable, false); -} - -void NewClassWidget::setFormInputCheckable(bool checkable, bool force) -{ - if (!force && checkable == m_d->m_formInputCheckable) - return; - m_d->m_formInputCheckable = checkable; - m_d->m_ui.generateFormLabel->setVisible(checkable); - m_d->m_ui.generateFormCheckBox->setVisible(checkable); -} - -void NewClassWidget::setFormInputChecked(bool v) -{ - m_d->m_ui.generateFormCheckBox->setChecked(v); -} - -bool NewClassWidget::formInputCheckable() const -{ - return m_d->m_formInputCheckable; -} - -bool NewClassWidget::formInputChecked() const -{ - return m_d->m_ui.generateFormCheckBox->isChecked(); -} - -void NewClassWidget::slotFormInputChecked() -{ - const bool checked = formInputChecked(); - m_d->m_ui.formLabel->setEnabled(checked); - m_d->m_ui.formFileLineEdit->setEnabled(checked); -} - -void NewClassWidget::setPathInputVisible(bool visible) -{ - m_d->m_pathInputVisible = visible; - m_d->m_ui.pathLabel->setVisible(visible); - m_d->m_ui.pathChooser->setVisible(visible); -} - -bool NewClassWidget::isPathInputVisible() const -{ - return m_d->m_pathInputVisible; -} - -void NewClassWidget::setClassName(const QString &suggestedName) -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << suggestedName << m_d->m_headerExtension << m_d->m_sourceExtension; - m_d->m_ui.classLineEdit->setText(ClassNameValidatingLineEdit::createClassName(suggestedName)); -} - -QString NewClassWidget::className() const -{ - return m_d->m_ui.classLineEdit->text(); -} - -QString NewClassWidget::baseClassName() const -{ - return m_d->m_ui.baseClassComboBox->currentText(); -} - -void NewClassWidget::setBaseClassName(const QString &c) -{ - const int index = m_d->m_ui.baseClassComboBox->findText(c); - if (index != -1) { - m_d->m_ui.baseClassComboBox->setCurrentIndex(index); - suggestClassNameFromBase(); - } -} - -QString NewClassWidget::sourceFileName() const -{ - return m_d->m_ui.sourceFileLineEdit->text(); -} - -QString NewClassWidget::headerFileName() const -{ - return m_d->m_ui.headerFileLineEdit->text(); -} - -QString NewClassWidget::formFileName() const -{ - return m_d->m_ui.formFileLineEdit->text(); -} - -QString NewClassWidget::path() const -{ - return m_d->m_ui.pathChooser->path(); -} - -void NewClassWidget::setPath(const QString &path) -{ - m_d->m_ui.pathChooser->setPath(path); -} - -bool NewClassWidget::namespacesEnabled() const -{ - return m_d->m_ui.classLineEdit->namespacesEnabled(); -} - -void NewClassWidget::setNamespacesEnabled(bool b) -{ - m_d->m_ui.classLineEdit->setNamespacesEnabled(b); -} - -QString NewClassWidget::sourceExtension() const -{ - return m_d->m_sourceExtension; -} - -void NewClassWidget::setSourceExtension(const QString &e) -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << e; - m_d->m_sourceExtension = fixSuffix(e); -} - -QString NewClassWidget::headerExtension() const -{ - return m_d->m_headerExtension; -} - -void NewClassWidget::setHeaderExtension(const QString &e) -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << e; - m_d->m_headerExtension = fixSuffix(e); -} - -QString NewClassWidget::formExtension() const -{ - return m_d->m_formExtension; -} - -void NewClassWidget::setFormExtension(const QString &e) -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << e; - m_d->m_formExtension = fixSuffix(e); -} - -bool NewClassWidget::allowDirectories() const -{ - return m_d->m_ui.headerFileLineEdit->allowDirectories(); -} - -void NewClassWidget::setAllowDirectories(bool v) -{ - // We keep all in sync - if (allowDirectories() != v) { - m_d->m_ui.sourceFileLineEdit->setAllowDirectories(v); - m_d->m_ui.headerFileLineEdit->setAllowDirectories(v); - m_d->m_ui.formFileLineEdit->setAllowDirectories(v); - } -} - -bool NewClassWidget::lowerCaseFiles() const -{ - return m_d->m_ui.classLineEdit->lowerCaseFileName(); -} - -void NewClassWidget::setLowerCaseFiles(bool v) -{ - m_d->m_ui.classLineEdit->setLowerCaseFileName(v); -} - -NewClassWidget::ClassType NewClassWidget::classType() const -{ - return static_cast(m_d->m_ui.classTypeComboBox->currentIndex()); -} - -void NewClassWidget::setClassType(ClassType ct) -{ - m_d->m_ui.classTypeComboBox->setCurrentIndex(ct); -} - -bool NewClassWidget::isClassTypeComboVisible() const -{ - return m_d->m_ui.classTypeLabel->isVisible(); -} - -void NewClassWidget::setClassTypeComboVisible(bool v) -{ - m_d->m_ui.classTypeLabel->setVisible(v); - m_d->m_ui.classTypeComboBox->setVisible(v); -} - -void NewClassWidget::slotValidChanged() -{ - const bool newValid = isValid(); - if (newValid != m_d->m_valid) { - m_d->m_valid = newValid; - emit validChanged(); - } -} - -bool NewClassWidget::isValid(QString *error) const -{ - if (!m_d->m_ui.classLineEdit->isValid()) { - if (error) - *error = m_d->m_ui.classLineEdit->errorMessage(); - return false; - } - - if (isBaseClassInputVisible() && isBaseClassEditable()) { - // TODO: Should this be a ClassNameValidatingComboBox? - QRegExp classNameValidator(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*")); - const QString baseClass = m_d->m_ui.baseClassComboBox->currentText().trimmed(); - if (!baseClass.isEmpty() && !classNameValidator.exactMatch(baseClass)) { - if (error) - *error = tr("Invalid base class name"); - return false; - } - } - - if (!m_d->m_ui.headerFileLineEdit->isValid()) { - if (error) - *error = tr("Invalid header file name: '%1'").arg(m_d->m_ui.headerFileLineEdit->errorMessage()); - return false; - } - - if (!m_d->m_ui.sourceFileLineEdit->isValid()) { - if (error) - *error = tr("Invalid source file name: '%1'").arg(m_d->m_ui.sourceFileLineEdit->errorMessage()); - return false; - } - - if (isFormInputVisible()) { - if (!m_d->m_ui.formFileLineEdit->isValid()) { - if (error) - *error = tr("Invalid form file name: '%1'").arg(m_d->m_ui.formFileLineEdit->errorMessage()); - return false; - } - } - - if (isPathInputVisible()) { - if (!m_d->m_ui.pathChooser->isValid()) { - if (error) - *error = m_d->m_ui.pathChooser->errorMessage(); - return false; - } - } - return true; -} - -void NewClassWidget::triggerUpdateFileNames() -{ - m_d->m_ui.classLineEdit->triggerChanged(); -} - -void NewClassWidget::slotUpdateFileNames(const QString &baseName) -{ - if (debugNewClassWidget) - qDebug() << Q_FUNC_INFO << baseName << m_d->m_headerExtension << m_d->m_sourceExtension; - const QChar dot = QLatin1Char('.'); - m_d->m_ui.sourceFileLineEdit->setText(baseName + dot + m_d->m_sourceExtension); - m_d->m_ui.headerFileLineEdit->setText(baseName + dot + m_d->m_headerExtension); - m_d->m_ui.formFileLineEdit->setText(baseName + dot + m_d->m_formExtension); -} - -void NewClassWidget::slotActivated() -{ - if (m_d->m_valid) - emit activated(); -} - -QString NewClassWidget::fixSuffix(const QString &suffix) -{ - QString s = suffix; - if (s.startsWith(QLatin1Char('.'))) - s.remove(0, 1); - return s; -} - -// Utility to add a suffix to a file unless the user specified one -static QString ensureSuffix(QString f, const QString &extension) -{ - const QChar dot = QLatin1Char('.'); - if (f.contains(dot)) - return f; - f += dot; - f += extension; - return f; -} - -// If a non-empty name was passed, expand to directory and suffix -static QString expandFileName(const QDir &dir, const QString name, const QString &extension) -{ - if (name.isEmpty()) - return QString(); - return dir.absoluteFilePath(ensureSuffix(name, extension)); -} - -QStringList NewClassWidget::files() const -{ - QStringList rc; - const QDir dir = QDir(path()); - rc.push_back(expandFileName(dir, headerFileName(), headerExtension())); - rc.push_back(expandFileName(dir, sourceFileName(), sourceExtension())); - if (isFormInputVisible()) - rc.push_back(expandFileName(dir, formFileName(), formExtension())); - return rc; -} - -} // namespace Utils diff --git a/libs/utils/newclasswidget.h b/libs/utils/newclasswidget.h deleted file mode 100644 index 6b36553d1e312c403049166560c087fdf07b3ebe..0000000000000000000000000000000000000000 --- a/libs/utils/newclasswidget.h +++ /dev/null @@ -1,167 +0,0 @@ -/** - ****************************************************************************** - * - * @file newclasswidget.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef NEWCLASSWIDGET_H -#define NEWCLASSWIDGET_H - -#include "utils_global.h" - -#include - -QT_BEGIN_NAMESPACE -class QStringList; -QT_END_NAMESPACE - -namespace Utils { - -struct NewClassWidgetPrivate; - -/** - * NewClassWidget: Utility widget for 'New Class' wizards. Prompts the user - * to enter a class name (optionally derived from some base class) and file - * names for header, source and form files. Has some smart logic to derive - * the file names from the class name. - */ -class QTCREATOR_UTILS_EXPORT NewClassWidget : public QWidget -{ - Q_DISABLE_COPY(NewClassWidget) - Q_OBJECT - Q_PROPERTY(bool namespacesEnabled READ namespacesEnabled WRITE setNamespacesEnabled DESIGNABLE true) - Q_PROPERTY(bool baseClassInputVisible READ isBaseClassInputVisible WRITE setBaseClassInputVisible DESIGNABLE true) - Q_PROPERTY(bool baseClassEditable READ isBaseClassEditable WRITE setBaseClassEditable DESIGNABLE false) - Q_PROPERTY(bool formInputVisible READ isFormInputVisible WRITE setFormInputVisible DESIGNABLE true) - Q_PROPERTY(bool pathInputVisible READ isPathInputVisible WRITE setPathInputVisible DESIGNABLE true) - Q_PROPERTY(bool classTypeComboVisible READ isClassTypeComboVisible WRITE setClassTypeComboVisible DESIGNABLE true) - Q_PROPERTY(QString className READ className WRITE setClassName DESIGNABLE true) - Q_PROPERTY(QString baseClassName READ baseClassName WRITE setBaseClassName DESIGNABLE true) - Q_PROPERTY(QString sourceFileName READ sourceFileName DESIGNABLE false) - Q_PROPERTY(QString headerFileName READ headerFileName DESIGNABLE false) - Q_PROPERTY(QString formFileName READ formFileName DESIGNABLE false) - Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true) - Q_PROPERTY(QStringList baseClassChoices READ baseClassChoices WRITE setBaseClassChoices DESIGNABLE true) - Q_PROPERTY(QString sourceExtension READ sourceExtension WRITE setSourceExtension DESIGNABLE true) - Q_PROPERTY(QString headerExtension READ headerExtension WRITE setHeaderExtension DESIGNABLE true) - Q_PROPERTY(QString formExtension READ formExtension WRITE setFormExtension DESIGNABLE true) - Q_PROPERTY(bool formInputCheckable READ formInputCheckable WRITE setFormInputCheckable DESIGNABLE true) - Q_PROPERTY(bool formInputChecked READ formInputChecked WRITE setFormInputChecked DESIGNABLE true) - Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories) - Q_PROPERTY(bool lowerCaseFiles READ lowerCaseFiles WRITE setLowerCaseFiles) - Q_PROPERTY(ClassType classType READ classType WRITE setClassType) - // Utility "USER" property for wizards containing file names. - Q_PROPERTY(QStringList files READ files DESIGNABLE false USER true) - Q_ENUMS(ClassType) -public: - enum ClassType { NoClassType, ClassInheritsQObject, ClassInheritsQWidget }; - - explicit NewClassWidget(QWidget *parent = 0); - ~NewClassWidget(); - - bool namespacesEnabled() const; - bool isBaseClassInputVisible() const; - bool isBaseClassEditable() const; - bool isFormInputVisible() const; - bool isPathInputVisible() const; - bool formInputCheckable() const; - bool formInputChecked() const; - - QString className() const; - QString baseClassName() const; - QString sourceFileName() const; - QString headerFileName() const; - QString formFileName() const; - QString path() const; - QStringList baseClassChoices() const; - QString sourceExtension() const; - QString headerExtension() const; - QString formExtension() const; - bool allowDirectories() const; - bool lowerCaseFiles() const; - ClassType classType() const; - bool isClassTypeComboVisible() const; - - bool isValid(QString *error = 0) const; - - QStringList files() const; - -signals: - void validChanged(); - void activated(); - -public slots: - void setNamespacesEnabled(bool b); - void setBaseClassInputVisible(bool visible); - void setBaseClassEditable(bool editable); - void setFormInputVisible(bool visible); - void setPathInputVisible(bool visible); - void setFormInputCheckable(bool v); - void setFormInputChecked(bool v); - - /** - * The name passed into the new class widget will be reformatted to be a - * valid class name. - */ - void setClassName(const QString &suggestedName); - void setBaseClassName(const QString &); - void setPath(const QString &path); - void setBaseClassChoices(const QStringList &choices); - void setSourceExtension(const QString &e); - void setHeaderExtension(const QString &e); - void setFormExtension(const QString &e); - void setAllowDirectories(bool v); - void setLowerCaseFiles(bool v); - void setClassType(ClassType ct); - void setClassTypeComboVisible(bool v); - - /** - * Suggest a class name from the base class by stripping the leading 'Q' - * character. This will happen automagically if the base class combo - * changes until the class line edited is manually edited. - */ - void suggestClassNameFromBase(); - -public slots: - /** Trigger an update (after changing settings) */ - void triggerUpdateFileNames(); - -private slots: - void slotUpdateFileNames(const QString &t); - void slotValidChanged(); - void slotActivated(); - void classNameEdited(); - void slotFormInputChecked(); - -private: - void setFormInputCheckable(bool checkable, bool force); - - QString fixSuffix(const QString &suffix); - NewClassWidgetPrivate *m_d; -}; - -} // namespace Utils - -#endif // NEWCLASSWIDGET_H diff --git a/libs/utils/newclasswidget.ui b/libs/utils/newclasswidget.ui deleted file mode 100644 index 2e725644bc7d9600eedf1d9058f74e3b5501f6ab..0000000000000000000000000000000000000000 --- a/libs/utils/newclasswidget.ui +++ /dev/null @@ -1,181 +0,0 @@ - - - Utils::NewClassWidget - - - - 0 - 0 - 418 - 291 - - - - - QFormLayout::ExpandingFieldsGrow - - - 0 - - - - - Class name: - - - - - - - - - - Base class: - - - - - - - - 0 - 0 - - - - - - - - Type information: - - - - - - - - None - - - - - Inherits QObject - - - - - Inherits QWidget - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 0 - 0 - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 0 - 0 - - - - - - - - Header file: - - - - - - - - - - Source file: - - - - - - - - - - Generate form: - - - - - - - - - - - - - - Form file: - - - - - - - - - - Path: - - - - - - - - - - - Utils::ClassNameValidatingLineEdit - QLineEdit -
utils/classnamevalidatinglineedit.h
-
- - Utils::FileNameValidatingLineEdit - QLineEdit -
utils/filenamevalidatinglineedit.h
-
- - Utils::PathChooser - QWidget -
utils/pathchooser.h
- 1 -
-
- - -
diff --git a/libs/utils/parameteraction.cpp b/libs/utils/parameteraction.cpp deleted file mode 100644 index 88a145c6b12a15d71a91970f8dc98fa32e6510c9..0000000000000000000000000000000000000000 --- a/libs/utils/parameteraction.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - ****************************************************************************** - * - * @file parameteraction.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "parameteraction.h" - -namespace Utils { - -ParameterAction::ParameterAction(const QString &emptyText, - const QString ¶meterText, - EnablingMode mode, - QObject* parent) : - QAction(emptyText, parent), - m_emptyText(emptyText), - m_parameterText(parameterText), - m_enablingMode(mode) -{ -} - -QString ParameterAction::emptyText() const -{ - return m_emptyText; -} - -void ParameterAction::setEmptyText(const QString &t) -{ - m_emptyText = t; -} - -QString ParameterAction::parameterText() const -{ - return m_parameterText; -} - -void ParameterAction::setParameterText(const QString &t) -{ - m_parameterText = t; -} - -ParameterAction::EnablingMode ParameterAction::enablingMode() const -{ - return m_enablingMode; -} - -void ParameterAction::setEnablingMode(EnablingMode m) -{ - m_enablingMode = m; -} - -void ParameterAction::setParameter(const QString &p) -{ - const bool enabled = !p.isEmpty(); - if (enabled) { - setText(m_parameterText.arg(p)); - } else { - setText(m_emptyText); - } - if (m_enablingMode == EnabledWithParameter) - setEnabled(enabled); -} - -} diff --git a/libs/utils/parameteraction.h b/libs/utils/parameteraction.h deleted file mode 100644 index 599c53a5f254ba3d9b2a7eb1d3bcb90aa72458f0..0000000000000000000000000000000000000000 --- a/libs/utils/parameteraction.h +++ /dev/null @@ -1,82 +0,0 @@ -/** - ****************************************************************************** - * - * @file parameteraction.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PARAMETERACTION_H -#define PARAMETERACTION_H - -#include "utils_global.h" - -#include - -namespace Utils { - -/* ParameterAction: Intended for actions that act on a 'current', - * string-type parameter (typically file name) and have 2 states: - * 1) displaying "Do XX" (empty text) - * 2) displaying "Do XX with %1". - * Provides a slot to set the parameter, changing display - * and enabled state accordingly. - * The text passed in should already be translated; parameterText - * should contain a %1 where the parameter is to be inserted. */ - -class QTCREATOR_UTILS_EXPORT ParameterAction : public QAction -{ - Q_ENUMS(EnablingMode) - Q_PROPERTY(QString emptyText READ emptyText WRITE setEmptyText) - Q_PROPERTY(QString parameterText READ parameterText WRITE setParameterText) - Q_PROPERTY(EnablingMode enablingMode READ enablingMode WRITE setEnablingMode) - Q_OBJECT -public: - enum EnablingMode { AlwaysEnabled, EnabledWithParameter }; - - explicit ParameterAction(const QString &emptyText, - const QString ¶meterText, - EnablingMode em = AlwaysEnabled, - QObject* parent = 0); - - QString emptyText() const; - void setEmptyText(const QString &); - - QString parameterText() const; - void setParameterText(const QString &); - - EnablingMode enablingMode() const; - void setEnablingMode(EnablingMode m); - -public slots: - void setParameter(const QString &); - -private: - QString m_emptyText; - QString m_parameterText; - EnablingMode m_enablingMode; -}; - -} - -#endif // PARAMETERACTION_H diff --git a/libs/utils/pathchooser.cpp b/libs/utils/pathchooser.cpp deleted file mode 100644 index 426b8b84527860856b97f33fd0669b068a3af501..0000000000000000000000000000000000000000 --- a/libs/utils/pathchooser.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathchooser.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "pathchooser.h" - -#include "basevalidatinglineedit.h" -#include "qtcassert.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -/*static*/ const char * const Utils::PathChooser::browseButtonLabel = -#ifdef Q_WS_MAC - QT_TRANSLATE_NOOP("Utils::PathChooser", "Choose..."); -#else - QT_TRANSLATE_NOOP("Utils::PathChooser", "Browse..."); -#endif - -namespace Utils { - -// ------------------ PathValidatingLineEdit -class PathValidatingLineEdit : public BaseValidatingLineEdit -{ -public: - explicit PathValidatingLineEdit(PathChooser *chooser, QWidget *parent = 0); - -protected: - virtual bool validate(const QString &value, QString *errorMessage) const; - -private: - PathChooser *m_chooser; -}; - -PathValidatingLineEdit::PathValidatingLineEdit(PathChooser *chooser, QWidget *parent) : - BaseValidatingLineEdit(parent), - m_chooser(chooser) -{ - QTC_ASSERT(chooser, return); -} - -bool PathValidatingLineEdit::validate(const QString &value, QString *errorMessage) const -{ - return m_chooser->validatePath(value, errorMessage); -} - -// ------------------ PathChooserPrivate -struct PathChooserPrivate -{ - PathChooserPrivate(PathChooser *chooser); - - QHBoxLayout *m_hLayout; - PathValidatingLineEdit *m_lineEdit; - PathChooser::Kind m_acceptingKind; - QString m_dialogTitleOverride; - QString m_dialogFilter; - QString m_initialBrowsePathOverride; -}; - -PathChooserPrivate::PathChooserPrivate(PathChooser *chooser) : - m_hLayout(new QHBoxLayout), - m_lineEdit(new PathValidatingLineEdit(chooser)), - m_acceptingKind(PathChooser::Directory) -{ -} - -PathChooser::PathChooser(QWidget *parent) : - QWidget(parent), - m_d(new PathChooserPrivate(this)) -{ - - m_d->m_hLayout->setContentsMargins(0, 0, 0, 0); - - connect(m_d->m_lineEdit, SIGNAL(validReturnPressed()), this, SIGNAL(returnPressed())); - connect(m_d->m_lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(changed(QString))); - connect(m_d->m_lineEdit, SIGNAL(validChanged()), this, SIGNAL(validChanged())); - connect(m_d->m_lineEdit, SIGNAL(validChanged(bool)), this, SIGNAL(validChanged(bool))); - connect(m_d->m_lineEdit, SIGNAL(editingFinished()), this, SIGNAL(editingFinished())); - - m_d->m_lineEdit->setMinimumWidth(50); - m_d->m_hLayout->addWidget(m_d->m_lineEdit); - m_d->m_hLayout->setSizeConstraint(QLayout::SetMinimumSize); - - addButton(tr(browseButtonLabel), this, SLOT(slotBrowse())); - - setLayout(m_d->m_hLayout); - setFocusProxy(m_d->m_lineEdit); -} - -PathChooser::~PathChooser() -{ - delete m_d; -} - -void PathChooser::addButton(const QString &text, QObject *receiver, const char *slotFunc) -{ -#ifdef Q_WS_MAC - QPushButton *button = new QPushButton; -#else - QToolButton *button = new QToolButton; -#endif - button->setText(text); - connect(button, SIGNAL(clicked()), receiver, slotFunc); - m_d->m_hLayout->addWidget(button); -} - -QAbstractButton *PathChooser::buttonAtIndex(int index) const -{ - return findChildren().at(index); -} - -QString PathChooser::path() const -{ - return m_d->m_lineEdit->text(); -} - -void PathChooser::setPath(const QString &path) -{ - m_d->m_lineEdit->setText(QDir::toNativeSeparators(path)); -} - -void PathChooser::slotBrowse() -{ - emit beforeBrowsing(); - - QString predefined = path(); - if ((predefined.isEmpty() || !QFileInfo(predefined).isDir()) - && !m_d->m_initialBrowsePathOverride.isNull()) { - predefined = m_d->m_initialBrowsePathOverride; - if (!QFileInfo(predefined).isDir()) - predefined.clear(); - } - - if (predefined.startsWith(":")) - predefined.clear(); - - // Prompt for a file/dir - QString dialogTitle; - QString newPath; - switch (m_d->m_acceptingKind) { - case PathChooser::Directory: - newPath = QFileDialog::getExistingDirectory(this, - makeDialogTitle(tr("Choose a directory")), predefined); - break; - - case PathChooser::File: // fall through - case PathChooser::Command: - newPath = QFileDialog::getOpenFileName(this, - makeDialogTitle(tr("Choose a file")), predefined, - m_d->m_dialogFilter); - break; - - default: - ; - } - - // Delete trailing slashes unless it is "/"|"\\", only - if (!newPath.isEmpty()) { - newPath = QDir::toNativeSeparators(newPath); - if (newPath.size() > 1 && newPath.endsWith(QDir::separator())) - newPath.truncate(newPath.size() - 1); - setPath(newPath); - } - - emit browsingFinished(); -} - -bool PathChooser::isValid() const -{ - return m_d->m_lineEdit->isValid(); -} - -QString PathChooser::errorMessage() const -{ - return m_d->m_lineEdit->errorMessage(); -} - -bool PathChooser::validatePath(const QString &path, QString *errorMessage) -{ - if (path.isEmpty()) { - if (errorMessage) - *errorMessage = tr("The path must not be empty."); - return false; - } - - const QFileInfo fi(path); - const bool isDir = fi.isDir(); - - // Check if existing - switch (m_d->m_acceptingKind) { - case PathChooser::Directory: // fall through - case PathChooser::File: - if (!fi.exists()) { - if (errorMessage) - *errorMessage = tr("The path '%1' does not exist.").arg(path); - return false; - } - break; - - case PathChooser::Command: // fall through - default: - ; - } - - // Check expected kind - switch (m_d->m_acceptingKind) { - case PathChooser::Directory: - if (!isDir) { - if (errorMessage) - *errorMessage = tr("The path '%1' is not a directory.").arg(path); - return false; - } - break; - - case PathChooser::File: - if (isDir) { - if (errorMessage) - *errorMessage = tr("The path '%1' is not a file.").arg(path); - return false; - } - break; - - case PathChooser::Command: - // TODO do proper command validation - // i.e. search $PATH for a matching file - break; - - default: - ; - } - - return true; -} - -QString PathChooser::label() -{ - return tr("Path:"); -} - -QString PathChooser::homePath() -{ -#ifdef Q_OS_WIN - // Return 'users//Documents' on Windows, since Windows explorer - // does not let people actually display the contents of their home - // directory. Alternatively, create a QtCreator-specific directory? - return QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); -#else - return QDir::homePath(); -#endif -} - -void PathChooser::setExpectedKind(Kind expected) -{ - m_d->m_acceptingKind = expected; -} - -PathChooser::Kind PathChooser::expectedKind() const -{ - return m_d->m_acceptingKind; -} - -void PathChooser::setPromptDialogTitle(const QString &title) -{ - m_d->m_dialogTitleOverride = title; -} - -QString PathChooser::promptDialogTitle() const -{ - return m_d->m_dialogTitleOverride; -} - -void PathChooser::setPromptDialogFilter(const QString &filter) -{ - m_d->m_dialogFilter = filter; -} - -QString PathChooser::promptDialogFilter() const -{ - return m_d->m_dialogFilter; -} - -void PathChooser::setInitialBrowsePathBackup(const QString &path) -{ - m_d->m_initialBrowsePathOverride = path; -} - -QString PathChooser::makeDialogTitle(const QString &title) -{ - if (m_d->m_dialogTitleOverride.isNull()) - return title; - else - return m_d->m_dialogTitleOverride; -} - -} // namespace Utils diff --git a/libs/utils/pathchooser.h b/libs/utils/pathchooser.h deleted file mode 100644 index 54a85ed345e4784c2201a137665e325f69db164f..0000000000000000000000000000000000000000 --- a/libs/utils/pathchooser.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathchooser.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PATHCHOOSER_H -#define PATHCHOOSER_H - -#include "utils_global.h" - -#include -#include - -namespace Utils { - -struct PathChooserPrivate; - -/** - * A control that let's the user choose a path, consisting of a QLineEdit and - * a "Browse" button. Has some validation logic for embedding into QWizardPage. - */ -class QTCREATOR_UTILS_EXPORT PathChooser : public QWidget -{ - Q_DISABLE_COPY(PathChooser) - Q_OBJECT - Q_ENUMS(Kind) - Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true) - Q_PROPERTY(QString promptDialogTitle READ promptDialogTitle WRITE setPromptDialogTitle DESIGNABLE true) - Q_PROPERTY(Kind expectedKind READ expectedKind WRITE setExpectedKind DESIGNABLE true) - -public: - static const char * const browseButtonLabel; - - explicit PathChooser(QWidget *parent = 0); - virtual ~PathChooser(); - - enum Kind { - Directory, - File, - Command - // ,Any - }; - - // Default is - void setExpectedKind(Kind expected); - Kind expectedKind() const; - - void setPromptDialogTitle(const QString &title); - QString promptDialogTitle() const; - - void setPromptDialogFilter(const QString &filter); - QString promptDialogFilter() const; - - void setInitialBrowsePathBackup(const QString &path); - - bool isValid() const; - QString errorMessage() const; - - QString path() const; - - /** Returns the suggested label title when used in a form layout. */ - static QString label(); - - virtual bool validatePath(const QString &path, QString *errorMessage = 0); - - /** Return the home directory, which needs some fixing under Windows. */ - static QString homePath(); - - void addButton(const QString &text, QObject *receiver, const char *slotFunc); - QAbstractButton *buttonAtIndex(int index) const; - -private: - // Returns overridden title or the one from - QString makeDialogTitle(const QString &title); - -signals: - void validChanged(); - void validChanged(bool validState); - void changed(const QString &text); - void editingFinished(); - void beforeBrowsing(); - void browsingFinished(); - void returnPressed(); - -public slots: - void setPath(const QString &); - -private slots: - void slotBrowse(); - -private: - PathChooserPrivate *m_d; -}; - -} // namespace Utils - - -#endif // PATHCHOOSER_H diff --git a/libs/utils/pathlisteditor.cpp b/libs/utils/pathlisteditor.cpp deleted file mode 100644 index 9f14597279380b09ea0093442444254474dcdd3f..0000000000000000000000000000000000000000 --- a/libs/utils/pathlisteditor.cpp +++ /dev/null @@ -1,310 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathlisteditor.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "pathlisteditor.h" - -#include <QtGui/QVBoxLayout> -#include <QtGui/QHBoxLayout> -#include <QtGui/QPlainTextEdit> -#include <QtGui/QToolButton> -#include <QtGui/QSpacerItem> -#include <QtGui/QFileDialog> -#include <QtGui/QTextCursor> -#include <QtGui/QTextBlock> -#include <QtGui/QMenu> -#include <QtGui/QAction> - -#include <QtCore/QSignalMapper> -#include <QtCore/QMimeData> -#include <QtCore/QSharedPointer> -#include <QtCore/QDir> -#include <QtCore/QDebug> - -namespace Utils { - -// ------------ PathListPlainTextEdit: -// Replaces the platform separator ';',':' by '\n' -// when inserting, allowing for pasting in paths -// from the terminal or such. - -class PathListPlainTextEdit : public QPlainTextEdit { -public: - explicit PathListPlainTextEdit(QWidget *parent = 0); -protected: - virtual void insertFromMimeData (const QMimeData *source); -}; - -PathListPlainTextEdit::PathListPlainTextEdit(QWidget *parent) : - QPlainTextEdit(parent) -{ - // No wrapping, scroll at all events - setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - setLineWrapMode(QPlainTextEdit::NoWrap); -} - -void PathListPlainTextEdit::insertFromMimeData(const QMimeData *source) -{ - if (source->hasText()) { - // replace separator - QString text = source->text().trimmed(); - text.replace(PathListEditor::separator(), QLatin1Char('\n')); - QSharedPointer<QMimeData> fixed(new QMimeData); - fixed->setText(text); - QPlainTextEdit::insertFromMimeData(fixed.data()); - } else { - QPlainTextEdit::insertFromMimeData(source); - } -} - -// ------------ PathListEditorPrivate -struct PathListEditorPrivate { - PathListEditorPrivate(); - - QHBoxLayout *layout; - QVBoxLayout *buttonLayout; - QToolButton *toolButton; - QMenu *buttonMenu; - QPlainTextEdit *edit; - QSignalMapper *envVarMapper; - QString fileDialogTitle; -}; - -PathListEditorPrivate::PathListEditorPrivate() : - layout(new QHBoxLayout), - buttonLayout(new QVBoxLayout), - toolButton(new QToolButton), - buttonMenu(new QMenu), - edit(new PathListPlainTextEdit), - envVarMapper(0) -{ - layout->setMargin(0); - layout->addWidget(edit); - buttonLayout->addWidget(toolButton); - buttonLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); - layout->addLayout(buttonLayout); -} - -PathListEditor::PathListEditor(QWidget *parent) : - QWidget(parent), - m_d(new PathListEditorPrivate) -{ - setLayout(m_d->layout); - m_d->toolButton->setPopupMode(QToolButton::MenuButtonPopup); - m_d->toolButton->setText(tr("Insert...")); - m_d->toolButton->setMenu(m_d->buttonMenu); - connect(m_d->toolButton, SIGNAL(clicked()), this, SLOT(slotInsert())); - - addAction(tr("Add..."), this, SLOT(slotAdd())); - addAction(tr("Delete line"), this, SLOT(deletePathAtCursor())); - addAction(tr("Clear"), this, SLOT(clear())); -} - -PathListEditor::~PathListEditor() -{ - delete m_d; -} - -static inline QAction *createAction(QObject *parent, const QString &text, QObject * receiver, const char *slotFunc) -{ - QAction *rc = new QAction(text, parent); - QObject::connect(rc, SIGNAL(triggered()), receiver, slotFunc); - return rc; -} - -QAction *PathListEditor::addAction(const QString &text, QObject * receiver, const char *slotFunc) -{ - QAction *rc = createAction(this, text, receiver, slotFunc); - m_d->buttonMenu->addAction(rc); - return rc; -} - -QAction *PathListEditor::insertAction(int index /* -1 */, const QString &text, QObject * receiver, const char *slotFunc) -{ - // Find the 'before' action - QAction *beforeAction = 0; - if (index >= 0) { - const QList<QAction*> actions = m_d->buttonMenu->actions(); - if (index < actions.size()) - beforeAction = actions.at(index); - } - QAction *rc = createAction(this, text, receiver, slotFunc); - if (beforeAction) { - m_d->buttonMenu->insertAction(beforeAction, rc); - } else { - m_d->buttonMenu->addAction(rc); - } - return rc; -} - -int PathListEditor::lastAddActionIndex() -{ - return 0; // Insert/Add -} - -QString PathListEditor::pathListString() const -{ - return pathList().join(separator()); -} - -QStringList PathListEditor::pathList() const -{ - const QString text = m_d->edit->toPlainText().trimmed(); - if (text.isEmpty()) - return QStringList(); - // trim each line - QStringList rc = text.split(QLatin1Char('\n'), QString::SkipEmptyParts); - const QStringList::iterator end = rc.end(); - for (QStringList::iterator it = rc.begin(); it != end; ++it) - *it = it->trimmed(); - return rc; -} - -void PathListEditor::setPathList(const QStringList &l) -{ - m_d->edit->setPlainText(l.join(QString(QLatin1Char('\n')))); -} - -void PathListEditor::setPathList(const QString &pathString) -{ - if (pathString.isEmpty()) { - clear(); - } else { - setPathList(pathString.split(separator(), QString::SkipEmptyParts)); - } -} - -void PathListEditor::setPathListFromEnvVariable(const QString &var) -{ - setPathList(qgetenv(var.toLocal8Bit())); -} - -QString PathListEditor::fileDialogTitle() const -{ - return m_d->fileDialogTitle; -} - -void PathListEditor::setFileDialogTitle(const QString &l) -{ - m_d->fileDialogTitle = l; -} - -void PathListEditor::clear() -{ - m_d->edit->clear(); -} - -void PathListEditor::slotAdd() -{ - const QString dir = QFileDialog::getExistingDirectory(this, m_d->fileDialogTitle); - if (!dir.isEmpty()) - appendPath(QDir::toNativeSeparators(dir)); -} - -void PathListEditor::slotInsert() -{ - const QString dir = QFileDialog::getExistingDirectory(this, m_d->fileDialogTitle); - if (!dir.isEmpty()) - insertPathAtCursor(QDir::toNativeSeparators(dir)); -} - -QChar PathListEditor::separator() -{ -#ifdef Q_OS_WIN - static const QChar rc(QLatin1Char(';')); -#else - static const QChar rc(QLatin1Char(':')); -#endif - return rc; -} - -// Add a button "Import from 'Path'" -void PathListEditor::addEnvVariableImportAction(const QString &var) -{ - if (!m_d->envVarMapper) { - m_d->envVarMapper = new QSignalMapper(this); - connect(m_d->envVarMapper, SIGNAL(mapped(QString)), this, SLOT(setPathListFromEnvVariable(QString))); - } - - QAction *a = insertAction(lastAddActionIndex() + 1, - tr("From \"%1\"").arg(var), m_d->envVarMapper, SLOT(map())); - m_d->envVarMapper->setMapping(a, var); -} - -QString PathListEditor::text() const -{ - return m_d->edit->toPlainText(); -} - -void PathListEditor::setText(const QString &t) -{ - m_d->edit->setPlainText(t); -} - -void PathListEditor::insertPathAtCursor(const QString &path) -{ - // If the cursor is at an empty line or at end(), - // just insert. Else insert line before - QTextCursor cursor = m_d->edit->textCursor(); - QTextBlock block = cursor.block(); - const bool needNewLine = !block.text().isEmpty(); - if (needNewLine) { - cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); - cursor.insertBlock(); - cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor); - } - cursor.insertText(path); - if (needNewLine) { - cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); - m_d->edit->setTextCursor(cursor); - } -} - -void PathListEditor::appendPath(const QString &path) -{ - QString paths = text().trimmed(); - if (!paths.isEmpty()) - paths += QLatin1Char('\n'); - paths += path; - setText(paths); -} - -void PathListEditor::deletePathAtCursor() -{ - // Delete current line - QTextCursor cursor = m_d->edit->textCursor(); - if (cursor.block().isValid()) { - cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); - // Select down or until end of [last] line - if (!cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor)) - cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); - cursor.removeSelectedText(); - m_d->edit->setTextCursor(cursor); - } -} - -} // namespace Utils diff --git a/libs/utils/pathlisteditor.h b/libs/utils/pathlisteditor.h deleted file mode 100644 index edd3dbbcbf91d417f21079b9600ec1394f1e07f0..0000000000000000000000000000000000000000 --- a/libs/utils/pathlisteditor.h +++ /dev/null @@ -1,107 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathlisteditor.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PATHLISTEDITOR_H -#define PATHLISTEDITOR_H - -#include "utils_global.h" - -#include <QtGui/QWidget> -#include <QtCore/QStringList> - -QT_BEGIN_NAMESPACE -class QAction; -QT_END_NAMESPACE - -namespace Utils { - -struct PathListEditorPrivate; - -/** - * A control that let's the user edit a list of (directory) paths - * using the platform separator (';',':'). Typically used for - * path lists controlled by environment variables, such as - * PATH. It is based on a QPlainTextEdit as it should - * allow for convenient editing and non-directory type elements like - * "etc/mydir1:$SPECIAL_SYNTAX:/etc/mydir2". - * When pasting text into it, the platform separator will be replaced - * by new line characters for convenience. - */ - -class QTCREATOR_UTILS_EXPORT PathListEditor : public QWidget -{ - Q_DISABLE_COPY(PathListEditor) - Q_OBJECT - Q_PROPERTY(QStringList pathList READ pathList WRITE setPathList DESIGNABLE true) - Q_PROPERTY(QString fileDialogTitle READ fileDialogTitle WRITE setFileDialogTitle DESIGNABLE true) - -public: - explicit PathListEditor(QWidget *parent = 0); - virtual ~PathListEditor(); - - QString pathListString() const; - QStringList pathList() const; - QString fileDialogTitle() const; - - static QChar separator(); - - // Add a convenience action "Import from 'Path'" (environment variable) - void addEnvVariableImportAction(const QString &var); - -public slots: - void clear(); - void setPathList(const QStringList &l); - void setPathList(const QString &pathString); - void setPathListFromEnvVariable(const QString &var); - void setFileDialogTitle(const QString &l); - -protected: - // Index after which to insert further "Add" actions - static int lastAddActionIndex(); - QAction *insertAction(int index /* -1 */, const QString &text, QObject * receiver, const char *slotFunc); - QAction *addAction(const QString &text, QObject * receiver, const char *slotFunc); - - QString text() const; - void setText(const QString &); - -protected slots: - void insertPathAtCursor(const QString &); - void deletePathAtCursor(); - void appendPath(const QString &); - -private slots: - void slotAdd(); - void slotInsert(); - -private: - PathListEditorPrivate *m_d; -}; - -} // namespace Utils - -#endif // PATHLISTEDITOR_H diff --git a/libs/utils/pathutils.cpp b/libs/utils/pathutils.cpp deleted file mode 100644 index 0227b91b390c492f6f236375061b4d49d242f555..0000000000000000000000000000000000000000 --- a/libs/utils/pathutils.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathutils.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * @brief Utilities to find the location of openpilot GCS files: - * - Plugins Share directory path - * - * @see The GNU Public License (GPL) Version 3 - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "pathutils.h" -#include "xmlconfig.h" -#include <stdint.h> -#include <QDebug> - - -namespace Utils { - - PathUtils::PathUtils() - { - - } - - /** - Returns the base path of the share directory. - - Path is in Qt/Unix conventions, separated by "/". - */ -QString PathUtils::GetDataPath() -{ - // This routine works with "/" as the standard: - // Figure out root: Up one from 'bin' - QDir rootDir = QApplication::applicationDirPath(); - rootDir.cdUp(); - const QString rootDirPath = rootDir.canonicalPath(); - QString dataPath = rootDirPath; - dataPath += QLatin1Char('/'); - // FIXME XXX -#ifdef EXTERNAL_USE - dataPath += QLatin1String("data"); -#else - dataPath += QLatin1String(GCS_DATA_BASENAME); -#endif - dataPath += QLatin1Char('/'); - return dataPath; -} - -/** - Cuts the standard data path from the 'path' argument. If path does not start -with the standard data path, then do nothing. - - Always returns a path converted to "/". - */ -QString PathUtils::RemoveDataPath(QString path) -{ - // Depending on the platform, we might get either "/" or "\" - // so we need to go to the standard ("/") - QString goodPath = QDir::fromNativeSeparators(path); - if (goodPath.startsWith(GetDataPath())) { - int i = goodPath.length()- GetDataPath().length(); - return QString("%%DATAPATH%%") + goodPath.right(i); - } else - return goodPath; -} - -/** - Inserts the data path (only if the path starts with %%DATAPATH%%) - - Returns a "/" or "\" separated path depending on platform conventions. - */ -QString PathUtils::InsertDataPath(QString path) -{ - if (path.startsWith(QString("%%DATAPATH%%"))) - { - QString newPath = GetDataPath(); - newPath += path.right(path.length()-12); - return QDir::toNativeSeparators(newPath); - } - return QDir::toNativeSeparators(path); -} - -/** - Gets a standard user-writable location for the system - */ -QString PathUtils::GetStoragePath() -{ - // This routine works with "/" as the standard: - // Work out where the settings are stored on the machine - QSettings set(XmlConfig::XmlSettingsFormat, QSettings::UserScope,QLatin1String("OpenPilot"), QLatin1String("OpenPilotGCS")); - QFileInfo f(set.fileName()); - QDir dir(f.absoluteDir()); - - const QString homeDirPath = dir.canonicalPath(); - QString storagePath = homeDirPath; - storagePath += QLatin1Char('/'); - // storagePath += QLatin1String("OpenPilot"); - // storagePath += QLatin1Char('/'); - return storagePath; -} - -/** - Removes the standard storage path and replace with a tag - */ -QString PathUtils::RemoveStoragePath(QString path) -{ - // Depending on the platform, we might get either "/" or "\" - // so we need to go to the standard ("/") - QString goodPath = QDir::fromNativeSeparators(path); - if (goodPath.startsWith(GetStoragePath())) { - int i = goodPath.length()- GetStoragePath().length(); - return QString("%%STOREPATH%%") + goodPath.right(i); - } else - return goodPath; -} - -/** - Inserts the standard storage path is there is a storage path tag - */ -QString PathUtils::InsertStoragePath(QString path) -{ - if (path.startsWith(QString("%%STOREPATH%%"))) - { - QString newPath = GetStoragePath(); - newPath += path.right(path.length()-13); - return QDir::toNativeSeparators(newPath); - } - return QDir::toNativeSeparators(path); - -} - -} diff --git a/libs/utils/pathutils.h b/libs/utils/pathutils.h deleted file mode 100644 index c818703cb04247598189a0fd35b21704b2bceea3..0000000000000000000000000000000000000000 --- a/libs/utils/pathutils.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - ****************************************************************************** - * - * @file pathutils.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PATHUTILS_H -#define PATHUTILS_H - -#include "utils_global.h" -#ifndef EXTERNAL_USE -#include "../extensionsystem/pluginmanager.h" -#endif -#include <QDir> -#include <QApplication> -#include <QSettings> - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT PathUtils -{ -public: - PathUtils(); - QString GetDataPath(); - QString RemoveDataPath(QString path); - QString InsertDataPath(QString path); - - QString GetStoragePath(); - QString RemoveStoragePath(QString path); - QString InsertStoragePath(QString path); - -}; - -} - -#endif /* PATHUTILS_H */ diff --git a/libs/utils/projectintropage.cpp b/libs/utils/projectintropage.cpp deleted file mode 100644 index 93be86a8c3ac9027b2d80f921fb6627d8500b34b..0000000000000000000000000000000000000000 --- a/libs/utils/projectintropage.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/** - ****************************************************************************** - * - * @file projectintropage.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "projectintropage.h" -#include "filewizardpage.h" -#include "ui_projectintropage.h" - -#include <QtGui/QMessageBox> -#include <QtCore/QDir> -#include <QtCore/QFileInfo> - -namespace Utils { - -struct ProjectIntroPagePrivate -{ - ProjectIntroPagePrivate(); - Ui::ProjectIntroPage m_ui; - bool m_complete; - // Status label style sheets - const QString m_errorStyleSheet; - const QString m_warningStyleSheet; - const QString m_hintStyleSheet; -}; - -ProjectIntroPagePrivate:: ProjectIntroPagePrivate() : - m_complete(false), - m_errorStyleSheet(QLatin1String("background : red;")), - m_warningStyleSheet(QLatin1String("background : yellow;")), - m_hintStyleSheet() -{ -} - -ProjectIntroPage::ProjectIntroPage(QWidget *parent) : - QWizardPage(parent), - m_d(new ProjectIntroPagePrivate) -{ - m_d->m_ui.setupUi(this); - hideStatusLabel(); - m_d->m_ui.nameLineEdit->setInitialText(tr("<Enter_Name>")); - m_d->m_ui.nameLineEdit->setFocus(Qt::TabFocusReason); - connect(m_d->m_ui.pathChooser, SIGNAL(changed(QString)), this, SLOT(slotChanged())); - connect(m_d->m_ui.nameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(slotChanged())); - connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()), this, SLOT(slotActivated())); - connect(m_d->m_ui.nameLineEdit, SIGNAL(validReturnPressed()), this, SLOT(slotActivated())); -} - -void ProjectIntroPage::insertControl(int row, QWidget *label, QWidget *control) -{ - m_d->m_ui.formLayout->insertRow(row, label, control); -} - -ProjectIntroPage::~ProjectIntroPage() -{ - delete m_d; -} - -QString ProjectIntroPage::name() const -{ - return m_d->m_ui.nameLineEdit->text(); -} - -QString ProjectIntroPage::path() const -{ - return m_d->m_ui.pathChooser->path(); -} - -void ProjectIntroPage::setPath(const QString &path) -{ - m_d->m_ui.pathChooser->setPath(path); -} - -void ProjectIntroPage::setName(const QString &name) -{ - m_d->m_ui.nameLineEdit->setText(name); -} - -QString ProjectIntroPage::description() const -{ - return m_d->m_ui.descriptionLabel->text(); -} - -void ProjectIntroPage::setDescription(const QString &description) -{ - m_d->m_ui.descriptionLabel->setText(description); -} - -void ProjectIntroPage::changeEvent(QEvent *e) -{ - QWizardPage::changeEvent(e); - switch (e->type()) { - case QEvent::LanguageChange: - m_d->m_ui.retranslateUi(this); - break; - default: - break; - } -} - -bool ProjectIntroPage::isComplete() const -{ - return m_d->m_complete; -} - -bool ProjectIntroPage::validate() -{ - // Validate and display status - if (!m_d->m_ui.pathChooser->isValid()) { - displayStatusMessage(Error, m_d->m_ui.pathChooser->errorMessage()); - return false; - } - - // Name valid? Ignore 'DisplayingInitialText' state. - bool nameValid = false; - switch (m_d->m_ui.nameLineEdit->state()) { - case BaseValidatingLineEdit::Invalid: - displayStatusMessage(Error, m_d->m_ui.nameLineEdit->errorMessage()); - return false; - case BaseValidatingLineEdit::DisplayingInitialText: - break; - case BaseValidatingLineEdit::Valid: - nameValid = true; - break; - } - - // Check existence of the directory - QString projectDir = path(); - projectDir += QDir::separator(); - projectDir += m_d->m_ui.nameLineEdit->text(); - const QFileInfo projectDirFile(projectDir); - if (!projectDirFile.exists()) { // All happy - hideStatusLabel(); - return nameValid; - } - - if (projectDirFile.isDir()) { - displayStatusMessage(Warning, tr("The project already exists.")); - return nameValid;; - } - // Not a directory, but something else, likely causing directory creation to fail - displayStatusMessage(Error, tr("A file with that name already exists.")); - return false; -} - -void ProjectIntroPage::slotChanged() -{ - const bool newComplete = validate(); - if (newComplete != m_d->m_complete) { - m_d->m_complete = newComplete; - emit completeChanged(); - } -} - -void ProjectIntroPage::slotActivated() -{ - if (m_d->m_complete) - emit activated(); -} - -bool ProjectIntroPage::validateProjectDirectory(const QString &name, QString *errorMessage) -{ - return ProjectNameValidatingLineEdit::validateProjectName(name, errorMessage); -} - -void ProjectIntroPage::displayStatusMessage(StatusLabelMode m, const QString &s) -{ - switch (m) { - case Error: - m_d->m_ui.stateLabel->setStyleSheet(m_d->m_errorStyleSheet); - break; - case Warning: - m_d->m_ui.stateLabel->setStyleSheet(m_d->m_warningStyleSheet); - break; - case Hint: - m_d->m_ui.stateLabel->setStyleSheet(m_d->m_hintStyleSheet); - break; - } - m_d->m_ui.stateLabel->setText(s); -} - -void ProjectIntroPage::hideStatusLabel() -{ - displayStatusMessage(Hint, QString()); -} - -} // namespace Utils diff --git a/libs/utils/projectintropage.h b/libs/utils/projectintropage.h deleted file mode 100644 index eee66c8067cc813d3ca0f9b5fcca831491611357..0000000000000000000000000000000000000000 --- a/libs/utils/projectintropage.h +++ /dev/null @@ -1,103 +0,0 @@ -/** - ****************************************************************************** - * - * @file projectintropage.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PROJECTINTROPAGE_H -#define PROJECTINTROPAGE_H - -#include "utils_global.h" - -#include <QtGui/QWizardPage> - -namespace Utils { - -struct ProjectIntroPagePrivate; - -/* Standard wizard page for a single file letting the user choose name - * and path. Looks similar to FileWizardPage, but provides additional - * functionality: - * - Description label at the top for displaying introductory text - * - It does on the fly validation (connected to changed()) and displays - * warnings/errors in a status label at the bottom (the page is complete - * when fully validated, validatePage() is thus not implemented). - * - * Note: Careful when changing projectintropage.ui. It must have main - * geometry cleared and QLayout::SetMinimumSize constraint on the main - * layout, otherwise, QWizard will squeeze it due to its strange expanding - * hacks. */ - -class QTCREATOR_UTILS_EXPORT ProjectIntroPage : public QWizardPage -{ - Q_OBJECT - Q_DISABLE_COPY(ProjectIntroPage) - Q_PROPERTY(QString description READ description WRITE setPath DESIGNABLE true) - Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true) - Q_PROPERTY(QString name READ name WRITE setName DESIGNABLE true) -public: - explicit ProjectIntroPage(QWidget *parent = 0); - virtual ~ProjectIntroPage(); - - QString name() const; - QString path() const; - QString description() const; - - // Insert an additional control into the form layout for the target. - void insertControl(int row, QWidget *label, QWidget *control); - - virtual bool isComplete() const; - - // Validate a project directory name entry field - static bool validateProjectDirectory(const QString &name, QString *errorMessage); - -signals: - void activated(); - -public slots: - void setPath(const QString &path); - void setName(const QString &name); - void setDescription(const QString &description); - -private slots: - void slotChanged(); - void slotActivated(); - -protected: - virtual void changeEvent(QEvent *e); - -private: - enum StatusLabelMode { Error, Warning, Hint }; - - bool validate(); - void displayStatusMessage(StatusLabelMode m, const QString &); - void hideStatusLabel(); - - ProjectIntroPagePrivate *m_d; -}; - -} // namespace Utils - -#endif // PROJECTINTROPAGE_H diff --git a/libs/utils/projectintropage.ui b/libs/utils/projectintropage.ui deleted file mode 100644 index a37da218c3e0c764fc2c99c4bf0ef58643d0a330..0000000000000000000000000000000000000000 --- a/libs/utils/projectintropage.ui +++ /dev/null @@ -1,116 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>Utils::ProjectIntroPage</class> - <widget class="QWizardPage" name="Utils::ProjectIntroPage"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>208</width> - <height>143</height> - </rect> - </property> - <property name="title"> - <string>Introduction and project location</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <property name="sizeConstraint"> - <enum>QLayout::SetMinimumSize</enum> - </property> - <item> - <widget class="QLabel" name="descriptionLabel"> - <property name="wordWrap"> - <bool>true</bool> - </property> - </widget> - </item> - <item> - <spacer name="verticalSpacer"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::MinimumExpanding</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>0</width> - <height>0</height> - </size> - </property> - </spacer> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <widget class="QFrame" name="frame"> - <property name="frameShape"> - <enum>QFrame::StyledPanel</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> - </property> - <layout class="QFormLayout" name="formLayout"> - <item row="0" column="0"> - <widget class="QLabel" name="nameLabel"> - <property name="text"> - <string>Name:</string> - </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="Utils::ProjectNameValidatingLineEdit" name="nameLineEdit"/> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="pathLabel"> - <property name="text"> - <string>Create in:</string> - </property> - </widget> - </item> - <item row="1" column="1"> - <widget class="Utils::PathChooser" name="pathChooser" native="true"/> - </item> - </layout> - </widget> - </item> - <item> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>0</width> - <height>0</height> - </size> - </property> - </spacer> - </item> - </layout> - </item> - <item> - <widget class="QLabel" name="stateLabel"> - <property name="wordWrap"> - <bool>true</bool> - </property> - </widget> - </item> - </layout> - </widget> - <customwidgets> - <customwidget> - <class>Utils::PathChooser</class> - <extends>QWidget</extends> - <header>pathchooser.h</header> - <container>1</container> - </customwidget> - <customwidget> - <class>Utils::ProjectNameValidatingLineEdit</class> - <extends>QLineEdit</extends> - <header>projectnamevalidatinglineedit.h</header> - </customwidget> - </customwidgets> - <resources/> - <connections/> -</ui> diff --git a/libs/utils/projectnamevalidatinglineedit.cpp b/libs/utils/projectnamevalidatinglineedit.cpp deleted file mode 100644 index 5819c384d59b202c0e8d2479af96900445d180dc..0000000000000000000000000000000000000000 --- a/libs/utils/projectnamevalidatinglineedit.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - ****************************************************************************** - * - * @file projectnamevalidatinglineedit.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "projectnamevalidatinglineedit.h" -#include "filenamevalidatinglineedit.h" - -namespace Utils { - -ProjectNameValidatingLineEdit::ProjectNameValidatingLineEdit(QWidget *parent) - : BaseValidatingLineEdit(parent) -{ -} - -bool ProjectNameValidatingLineEdit::validateProjectName(const QString &name, QString *errorMessage /* = 0*/) -{ - // Validation is file name + checking for dots - if (!FileNameValidatingLineEdit::validateFileName(name, false, errorMessage)) - return false; - - // We don't want dots in the directory name for some legacy Windows - // reason. Since we are cross-platform, we generally disallow it. - if (name.contains(QLatin1Char('.'))) { - if (errorMessage) - *errorMessage = tr("The name must not contain the '.'-character."); - return false; - } - return true; -} - -bool ProjectNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const -{ - return validateProjectName(value, errorMessage); -} - -} // namespace Utils diff --git a/libs/utils/projectnamevalidatinglineedit.h b/libs/utils/projectnamevalidatinglineedit.h deleted file mode 100644 index 1e587c50af75e83f60f5804bfab1cbecd9357091..0000000000000000000000000000000000000000 --- a/libs/utils/projectnamevalidatinglineedit.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - ****************************************************************************** - * - * @file projectnamevalidatinglineedit.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef PROJECTNAMEVALIDATINGLINEEDIT_H -#define PROJECTNAMEVALIDATINGLINEEDIT_H - -#include "basevalidatinglineedit.h" - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT ProjectNameValidatingLineEdit : public BaseValidatingLineEdit -{ - Q_OBJECT - Q_DISABLE_COPY(ProjectNameValidatingLineEdit) - -public: - explicit ProjectNameValidatingLineEdit(QWidget *parent = 0); - - static bool validateProjectName(const QString &name, QString *errorMessage /* = 0*/); - -protected: - virtual bool validate(const QString &value, QString *errorMessage) const; -}; - -} // namespace Utils - -#endif // PROJECTNAMEVALIDATINGLINEEDIT_H diff --git a/libs/utils/qtcassert.h b/libs/utils/qtcassert.h deleted file mode 100644 index 01b10345ba2fdfb8de90b0cc06c810ed5b139395..0000000000000000000000000000000000000000 --- a/libs/utils/qtcassert.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - ****************************************************************************** - * - * @file qtcassert.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef QTC_ASSERT_H -#define QTC_ASSERT_H - -#include <QtCore/QDebug> - -#define QTC_ASSERT_STRINGIFY_INTERNAL(x) #x -#define QTC_ASSERT_STRINGIFY(x) QTC_ASSERT_STRINGIFY_INTERNAL(x) - -// we do not use the 'do {...} while (0)' idiom here to be able to use -// 'break' and 'continue' as 'actions'. - -#define QTC_ASSERT(cond, action) \ - if(cond){}else{qDebug()<<"ASSERTION " #cond " FAILED AT " __FILE__ ":" QTC_ASSERT_STRINGIFY(__LINE__);action;} - -#endif // QTC_ASSERT_H - diff --git a/libs/utils/qtcolorbutton.cpp b/libs/utils/qtcolorbutton.cpp deleted file mode 100644 index 3f38a0177ee934a8c189eca50aea2b34e0d0031b..0000000000000000000000000000000000000000 --- a/libs/utils/qtcolorbutton.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/** - ****************************************************************************** - * - * @file qtcolorbutton.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "qtcolorbutton.h" - -#include <QtCore/QMimeData> -#include <QtGui/QApplication> -#include <QtGui/QColorDialog> -#include <QtGui/QDragEnterEvent> -#include <QtGui/QPainter> - -namespace Utils { - -class QtColorButtonPrivate -{ - QtColorButton *q_ptr; - Q_DECLARE_PUBLIC(QtColorButton) -public: - QColor m_color; -#ifndef QT_NO_DRAGANDDROP - QColor m_dragColor; - QPoint m_dragStart; - bool m_dragging; -#endif - bool m_backgroundCheckered; - bool m_alphaAllowed; - - void slotEditColor(); - QColor shownColor() const; - QPixmap generatePixmap() const; -}; - -void QtColorButtonPrivate::slotEditColor() -{ - QColor newColor; - if (m_alphaAllowed) { - bool ok; - const QRgb rgba = QColorDialog::getRgba(m_color.rgba(), &ok, q_ptr); - if (!ok) - return; - newColor = QColor::fromRgba(rgba); - } else { - newColor = QColorDialog::getColor(m_color, q_ptr); - if (!newColor.isValid()) - return; - } - if (newColor == q_ptr->color()) - return; - q_ptr->setColor(newColor); - emit q_ptr->colorChanged(m_color); -} - -QColor QtColorButtonPrivate::shownColor() const -{ -#ifndef QT_NO_DRAGANDDROP - if (m_dragging) - return m_dragColor; -#endif - return m_color; -} - -QPixmap QtColorButtonPrivate::generatePixmap() const -{ - QPixmap pix(24, 24); - - int pixSize = 20; - QBrush br(shownColor()); - - QPixmap pm(2 * pixSize, 2 * pixSize); - QPainter pmp(&pm); - pmp.fillRect(0, 0, pixSize, pixSize, Qt::lightGray); - pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::lightGray); - pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::darkGray); - pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::darkGray); - pmp.fillRect(0, 0, 2 * pixSize, 2 * pixSize, shownColor()); - br = QBrush(pm); - - QPainter p(&pix); - int corr = 1; - QRect r = pix.rect().adjusted(corr, corr, -corr, -corr); - p.setBrushOrigin((r.width() % pixSize + pixSize) / 2 + corr, (r.height() % pixSize + pixSize) / 2 + corr); - p.fillRect(r, br); - - p.fillRect(r.width() / 4 + corr, r.height() / 4 + corr, - r.width() / 2, r.height() / 2, - QColor(shownColor().rgb())); - p.drawRect(pix.rect().adjusted(0, 0, -1, -1)); - - return pix; -} - -/////////////// - -QtColorButton::QtColorButton(QWidget *parent) - : QToolButton(parent) -{ - d_ptr = new QtColorButtonPrivate; - d_ptr->q_ptr = this; - d_ptr->m_dragging = false; - d_ptr->m_backgroundCheckered = true; - d_ptr->m_alphaAllowed = true; - - setAcceptDrops(true); - - connect(this, SIGNAL(clicked()), this, SLOT(slotEditColor())); - setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); -} - -QtColorButton::~QtColorButton() -{ - delete d_ptr; -} - -void QtColorButton::setColor(const QColor &color) -{ - if (d_ptr->m_color == color) - return; - d_ptr->m_color = color; - update(); -} - -QColor QtColorButton::color() const -{ - return d_ptr->m_color; -} - -void QtColorButton::setBackgroundCheckered(bool checkered) -{ - if (d_ptr->m_backgroundCheckered == checkered) - return; - d_ptr->m_backgroundCheckered = checkered; - update(); -} - -bool QtColorButton::isBackgroundCheckered() const -{ - return d_ptr->m_backgroundCheckered; -} - -void QtColorButton::setAlphaAllowed(bool allowed) -{ - d_ptr->m_alphaAllowed = allowed; -} - -bool QtColorButton::isAlphaAllowed() const -{ - return d_ptr->m_alphaAllowed; -} - -void QtColorButton::paintEvent(QPaintEvent *event) -{ - QToolButton::paintEvent(event); - if (!isEnabled()) - return; - - const int pixSize = 10; - QBrush br(d_ptr->shownColor()); - if (d_ptr->m_backgroundCheckered) { - QPixmap pm(2 * pixSize, 2 * pixSize); - QPainter pmp(&pm); - pmp.fillRect(0, 0, pixSize, pixSize, Qt::white); - pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::white); - pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::black); - pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::black); - pmp.fillRect(0, 0, 2 * pixSize, 2 * pixSize, d_ptr->shownColor()); - br = QBrush(pm); - } - - QPainter p(this); - const int corr = 5; - QRect r = rect().adjusted(corr, corr, -corr, -corr); - p.setBrushOrigin((r.width() % pixSize + pixSize) / 2 + corr, (r.height() % pixSize + pixSize) / 2 + corr); - p.fillRect(r, br); - - //const int adjX = qRound(r.width() / 4.0); - //const int adjY = qRound(r.height() / 4.0); - //p.fillRect(r.adjusted(adjX, adjY, -adjX, -adjY), - // QColor(d_ptr->shownColor().rgb())); - /* - p.fillRect(r.adjusted(0, r.height() * 3 / 4, 0, 0), - QColor(d_ptr->shownColor().rgb())); - p.fillRect(r.adjusted(0, 0, 0, -r.height() * 3 / 4), - QColor(d_ptr->shownColor().rgb())); - */ - /* - const QColor frameColor0(0, 0, 0, qRound(0.2 * (0xFF - d_ptr->shownColor().alpha()))); - p.setPen(frameColor0); - p.drawRect(r.adjusted(adjX, adjY, -adjX - 1, -adjY - 1)); - */ - - const QColor frameColor1(0, 0, 0, 26); - p.setPen(frameColor1); - p.drawRect(r.adjusted(1, 1, -2, -2)); - const QColor frameColor2(0, 0, 0, 51); - p.setPen(frameColor2); - p.drawRect(r.adjusted(0, 0, -1, -1)); -} - -void QtColorButton::mousePressEvent(QMouseEvent *event) -{ -#ifndef QT_NO_DRAGANDDROP - if (event->button() == Qt::LeftButton) - d_ptr->m_dragStart = event->pos(); -#endif - QToolButton::mousePressEvent(event); -} - -void QtColorButton::mouseMoveEvent(QMouseEvent *event) -{ -#ifndef QT_NO_DRAGANDDROP - if (event->buttons() & Qt::LeftButton && - (d_ptr->m_dragStart - event->pos()).manhattanLength() > QApplication::startDragDistance()) { - QMimeData *mime = new QMimeData; - mime->setColorData(color()); - QDrag *drg = new QDrag(this); - drg->setMimeData(mime); - drg->setPixmap(d_ptr->generatePixmap()); - setDown(false); - event->accept(); - drg->start(); - return; - } -#endif - QToolButton::mouseMoveEvent(event); -} - -#ifndef QT_NO_DRAGANDDROP -void QtColorButton::dragEnterEvent(QDragEnterEvent *event) -{ - const QMimeData *mime = event->mimeData(); - if (!mime->hasColor()) - return; - - event->accept(); - d_ptr->m_dragColor = qvariant_cast<QColor>(mime->colorData()); - d_ptr->m_dragging = true; - update(); -} - -void QtColorButton::dragLeaveEvent(QDragLeaveEvent *event) -{ - event->accept(); - d_ptr->m_dragging = false; - update(); -} - -void QtColorButton::dropEvent(QDropEvent *event) -{ - event->accept(); - d_ptr->m_dragging = false; - if (d_ptr->m_dragColor == color()) - return; - setColor(d_ptr->m_dragColor); - emit colorChanged(color()); -} -#endif - -} // namespace Utils - -// It is unclear why this include directly access the MOC output? - -#include "moc_qtcolorbutton.cpp" diff --git a/libs/utils/qtcolorbutton.h b/libs/utils/qtcolorbutton.h deleted file mode 100644 index 6dd5f50683b03f7d2e073084968b451746c89898..0000000000000000000000000000000000000000 --- a/libs/utils/qtcolorbutton.h +++ /dev/null @@ -1,78 +0,0 @@ -/** - ****************************************************************************** - * - * @file qtcolorbutton.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef QTCOLORBUTTON_H -#define QTCOLORBUTTON_H - -#include "utils_global.h" - -#include <QtGui/QToolButton> - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT QtColorButton : public QToolButton -{ - Q_OBJECT - Q_PROPERTY(bool backgroundCheckered READ isBackgroundCheckered WRITE setBackgroundCheckered) - Q_PROPERTY(bool alphaAllowed READ isAlphaAllowed WRITE setAlphaAllowed) -public: - QtColorButton(QWidget *parent = 0); - ~QtColorButton(); - - bool isBackgroundCheckered() const; - void setBackgroundCheckered(bool checkered); - - bool isAlphaAllowed() const; - void setAlphaAllowed(bool allowed); - - QColor color() const; - -public slots: - void setColor(const QColor &color); - -signals: - void colorChanged(const QColor &color); -protected: - void paintEvent(QPaintEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); -#ifndef QT_NO_DRAGANDDROP - void dragEnterEvent(QDragEnterEvent *event); - void dragLeaveEvent(QDragLeaveEvent *event); - void dropEvent(QDropEvent *event); -#endif -private: - class QtColorButtonPrivate *d_ptr; - friend class QtColorButtonPrivate; - Q_DISABLE_COPY(QtColorButton) - Q_PRIVATE_SLOT(d_ptr, void slotEditColor()) -}; - -} // namespace Utils - -#endif // QTCOLORBUTTON_H diff --git a/libs/utils/qwineventnotifier_p.h b/libs/utils/qwineventnotifier_p.h deleted file mode 100644 index 459cd6730f3934a2170fd6f159f22c87eccf4f24..0000000000000000000000000000000000000000 --- a/libs/utils/qwineventnotifier_p.h +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Commercial License Agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINEVENTNOTIFIER_P_H -#define QWINEVENTNOTIFIER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "QtCore/qobject.h" -#include "QtCore/qt_windows.h" - -QT_BEGIN_NAMESPACE - -class Q_CORE_EXPORT QWinEventNotifier : public QObject -{ - Q_OBJECT - Q_DECLARE_PRIVATE(QObject) - -public: - explicit QWinEventNotifier(QObject *parent = 0); - explicit QWinEventNotifier(HANDLE hEvent, QObject *parent = 0); - ~QWinEventNotifier(); - - void setHandle(HANDLE hEvent); - HANDLE handle() const; - - bool isEnabled() const; - -public Q_SLOTS: - void setEnabled(bool enable); - -Q_SIGNALS: - void activated(HANDLE hEvent); - -protected: - bool event(QEvent * e); - -private: - Q_DISABLE_COPY(QWinEventNotifier) - - HANDLE handleToEvent; - bool enabled; -}; - -QT_END_NAMESPACE - -#endif // QWINEVENTNOTIFIER_P_H diff --git a/libs/utils/reloadpromptutils.cpp b/libs/utils/reloadpromptutils.cpp deleted file mode 100644 index 80b237d6bac0cf8649be65cc273a7839fc1b8a93..0000000000000000000000000000000000000000 --- a/libs/utils/reloadpromptutils.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - ****************************************************************************** - * - * @file reloadpromptutils.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "reloadpromptutils.h" - -#include <QtGui/QMessageBox> -#include <QtCore/QCoreApplication> -#include <QtCore/QDir> - -using namespace Utils; - -QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer - Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent) -{ - - const QString title = QCoreApplication::translate("Utils::reloadPrompt", "File Changed"); - QString msg; - - if (modified) - msg = QCoreApplication::translate("Utils::reloadPrompt", - "The unsaved file %1 has been changed outside Qt Creator. Do you want to reload it and discard your changes?").arg(QDir::toNativeSeparators(fileName)); - else - msg = QCoreApplication::translate("Utils::reloadPrompt", - "The file %1 has changed outside Qt Creator. Do you want to reload it?").arg(QDir::toNativeSeparators(fileName)); - return reloadPrompt(title, msg, parent); -} - -QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer - Utils::reloadPrompt(const QString &title, const QString &prompt, QWidget *parent) -{ - switch (QMessageBox::question(parent, title, prompt, - QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::No|QMessageBox::NoToAll, - QMessageBox::YesToAll)) { - case QMessageBox::Yes: - return ReloadCurrent; - case QMessageBox::YesToAll: - return ReloadAll; - case QMessageBox::No: - return ReloadSkipCurrent; - default: - break; - } - return ReloadNone; -} diff --git a/libs/utils/reloadpromptutils.h b/libs/utils/reloadpromptutils.h deleted file mode 100644 index 4c6e328d4925984f553e0da783ffad39bce219ce..0000000000000000000000000000000000000000 --- a/libs/utils/reloadpromptutils.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - ****************************************************************************** - * - * @file reloadpromptutils.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef RELOADPROMPTUTILS_H -#define RELOADPROMPTUTILS_H - -#include "utils_global.h" - -QT_BEGIN_NAMESPACE -class QString; -class QWidget; -QT_END_NAMESPACE - -namespace Utils { - -enum ReloadPromptAnswer { ReloadCurrent, ReloadAll, ReloadSkipCurrent, ReloadNone }; - -QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName, bool modified, QWidget *parent); -QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title, const QString &prompt, QWidget *parent); - -} // namespace Utils - -#endif // RELOADPROMPTUTILS_H diff --git a/libs/utils/savedaction.cpp b/libs/utils/savedaction.cpp deleted file mode 100644 index fdc4c38f5291938dc003e54d340bc7ab0b30b465..0000000000000000000000000000000000000000 --- a/libs/utils/savedaction.cpp +++ /dev/null @@ -1,437 +0,0 @@ -/** - ****************************************************************************** - * - * @file savedaction.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include <utils/savedaction.h> - -#include <utils/qtcassert.h> -#include <utils/pathchooser.h> - -#include <QtCore/QDebug> -#include <QtCore/QSettings> - -#include <QtGui/QAbstractButton> -#include <QtGui/QAction> -#include <QtGui/QActionGroup> -#include <QtGui/QCheckBox> -#include <QtGui/QLineEdit> -#include <QtGui/QRadioButton> -#include <QtGui/QSpinBox> - - -using namespace Utils; - - -////////////////////////////////////////////////////////////////////////// -// -// SavedAction -// -////////////////////////////////////////////////////////////////////////// - -/*! - \class Utils::SavedAction - - \brief The SavedAction class is a helper class for actions with persistent - state. - - \ingroup utils - -*/ - -SavedAction::SavedAction(QObject *parent) - : QAction(parent) -{ - m_widget = 0; - connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool))); -} - - -/*! - Returns the current value of the object. - - \sa setValue() -*/ -QVariant SavedAction::value() const -{ - return m_value; -} - - -/*! - Sets the current value of the object. If the value changed and - \a doemit is true, the \c valueChanged() signal will be emitted. - - \sa value() -*/ -void SavedAction::setValue(const QVariant &value, bool doemit) -{ - if (value == m_value) - return; - m_value = value; - if (this->isCheckable()) - this->setChecked(m_value.toBool()); - if (doemit) - emit valueChanged(m_value); -} - - -/*! - Returns the default value to be used when the item does not exist yet - in the settings. - - \sa setDefaultValue() -*/ -QVariant SavedAction::defaultValue() const -{ - return m_defaultValue; -} - - -/*! - Sets the default value to be used when the item does not exist yet - in the settings. - - \sa defaultValue() -*/ -void SavedAction::setDefaultValue(const QVariant &value) -{ - m_defaultValue = value; -} - - -/*! - Returns the key to be used when accessing the settings. - - \sa settingsKey() -*/ -QString SavedAction::settingsKey() const -{ - return m_settingsKey; -} - - -/*! - Sets the key to be used when accessing the settings. - - \sa settingsKey() -*/ -void SavedAction::setSettingsKey(const QString &key) -{ - m_settingsKey = key; -} - - -/*! - Sets the key and group to be used when accessing the settings. - - \sa settingsKey() -*/ -void SavedAction::setSettingsKey(const QString &group, const QString &key) -{ - m_settingsKey = key; - m_settingsGroup = group; -} - - -/*! - Sets the key to be used when accessing the settings. - - \sa settingsKey() -*/ -QString SavedAction::settingsGroup() const -{ - return m_settingsGroup; -} - -/*! - Sets the group to be used when accessing the settings. - - \sa settingsGroup() -*/ -void SavedAction::setSettingsGroup(const QString &group) -{ - m_settingsGroup = group; -} - -QString SavedAction::textPattern() const -{ - return m_textPattern; -} - -void SavedAction::setTextPattern(const QString &value) -{ - m_textPattern = value; -} - -QString SavedAction::toString() const -{ - return QLatin1String("value: ") + m_value.toString() - + QLatin1String(" defaultvalue: ") + m_defaultValue.toString() - + QLatin1String(" settingskey: ") + m_settingsGroup - + '/' + m_settingsKey; -} - -/*! - \fn QAction *SavedAction::updatedAction(const QString &text) - - Adjust the \c text() of the underlying action. - - This can be used to update the item shortly before e.g. a menu is shown. - - If the item's \c textPattern() is empty the \a text will be used - verbatim. - - Otherwise, the behaviour depends on \a text: if it is non-empty, - \c QString(textPattern()).arg(text), otherwise, \c textPattern() - with the "%1" placeholder removed will be used. - - \sa textPattern(), setTextPattern() -*/ -QAction *SavedAction::updatedAction(const QString &text0) -{ - QString text = text0; - bool enabled = true; - if (!m_textPattern.isEmpty()) { - if (text.isEmpty()) { - text = m_textPattern; - text.remove("\"%1\""); - text.remove("%1"); - enabled = false; - } else { - text = m_textPattern.arg(text0); - } - } - this->setEnabled(enabled); - this->setData(text0); - this->setText(text); - return this; -} - -/* - Uses \c settingsGroup() and \c settingsKey() to restore the - item from \a settings, - - \sa settingsKey(), settingsGroup(), writeSettings() -*/ -void SavedAction::readSettings(QSettings *settings) -{ - if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty()) - return; - settings->beginGroup(m_settingsGroup); - QVariant var = settings->value(m_settingsKey, m_defaultValue); - // work around old ini files containing @Invalid() entries - if (isCheckable() && !var.isValid()) - var = false; - setValue(var); - //qDebug() << "READING: " << var.isValid() << m_settingsKey << " -> " << m_value - // << " (default: " << m_defaultValue << ")" << var; - settings->endGroup(); -} - -/* - Uses \c settingsGroup() and \c settingsKey() to write the - item to \a settings, - - \sa settingsKey(), settingsGroup(), readSettings() -*/ -void SavedAction::writeSettings(QSettings *settings) -{ - if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty()) - return; - settings->beginGroup(m_settingsGroup); - settings->setValue(m_settingsKey, m_value); - //qDebug() << "WRITING: " << m_settingsKey << " -> " << toString(); - settings->endGroup(); -} - -/* - A \c SavedAction can be connected to a widget, typically a - checkbox, radiobutton, or a lineedit in some configuration dialog. - - The widget will retrieve its contents from the SavedAction's - value, and - depending on the \a ApplyMode - either write - changes back immediately, or when \s SavedAction::apply() - is called explicitly. - - \sa apply(), disconnectWidget() -*/ -void SavedAction::connectWidget(QWidget *widget, ApplyMode applyMode) -{ - QTC_ASSERT(!m_widget, - qDebug() << "ALREADY CONNECTED: " << widget << m_widget << toString(); return); - m_widget = widget; - m_applyMode = applyMode; - - if (QAbstractButton *button = qobject_cast<QAbstractButton *>(widget)) { - if (button->isCheckable()) { - button->setChecked(m_value.toBool()); - connect(button, SIGNAL(clicked(bool)), - this, SLOT(checkableButtonClicked(bool))); - } else { - connect(button, SIGNAL(clicked()), - this, SLOT(uncheckableButtonClicked())); - } - } else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(widget)) { - spinBox->setValue(m_value.toInt()); - //qDebug() << "SETTING VALUE" << spinBox->value(); - connect(spinBox, SIGNAL(valueChanged(int)), - this, SLOT(spinBoxValueChanged(int))); - connect(spinBox, SIGNAL(valueChanged(QString)), - this, SLOT(spinBoxValueChanged(QString))); - } else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) { - lineEdit->setText(m_value.toString()); - //qDebug() << "SETTING TEXT" << lineEdit->text(); - connect(lineEdit, SIGNAL(editingFinished()), - this, SLOT(lineEditEditingFinished())); - } else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(widget)) { - pathChooser->setPath(m_value.toString()); - connect(pathChooser, SIGNAL(editingFinished()), - this, SLOT(pathChooserEditingFinished())); - connect(pathChooser, SIGNAL(browsingFinished()), - this, SLOT(pathChooserEditingFinished())); - } else { - qDebug() << "Cannot connect widget " << widget << toString(); - } -} - -/* - Disconnects the \c SavedAction from a widget. - - \sa apply(), connectWidget() -*/ -void SavedAction::disconnectWidget() -{ - m_widget = 0; -} - -void SavedAction::apply(QSettings *s) -{ - if (QAbstractButton *button = qobject_cast<QAbstractButton *>(m_widget)) - setValue(button->isChecked()); - else if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(m_widget)) - setValue(lineEdit->text()); - else if (QSpinBox *spinBox = qobject_cast<QSpinBox *>(m_widget)) - setValue(spinBox->value()); - else if (PathChooser *pathChooser = qobject_cast<PathChooser *>(m_widget)) - setValue(pathChooser->path()); - if (s) - writeSettings(s); -} - -void SavedAction::uncheckableButtonClicked() -{ - QAbstractButton *button = qobject_cast<QAbstractButton *>(sender()); - QTC_ASSERT(button, return); - //qDebug() << "UNCHECKABLE BUTTON: " << sender(); - QAction::trigger(); -} - -void SavedAction::checkableButtonClicked(bool) -{ - QAbstractButton *button = qobject_cast<QAbstractButton *>(sender()); - QTC_ASSERT(button, return); - //qDebug() << "CHECKABLE BUTTON: " << sender(); - if (m_applyMode == ImmediateApply) - setValue(button->isChecked()); -} - -void SavedAction::lineEditEditingFinished() -{ - QLineEdit *lineEdit = qobject_cast<QLineEdit *>(sender()); - QTC_ASSERT(lineEdit, return); - if (m_applyMode == ImmediateApply) - setValue(lineEdit->text()); -} - -void SavedAction::spinBoxValueChanged(int value) -{ - QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender()); - QTC_ASSERT(spinBox, return); - if (m_applyMode == ImmediateApply) - setValue(value); -} - -void SavedAction::spinBoxValueChanged(QString value) -{ - QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender()); - QTC_ASSERT(spinBox, return); - if (m_applyMode == ImmediateApply) - setValue(value); -} - -void SavedAction::pathChooserEditingFinished() -{ - PathChooser *pathChooser = qobject_cast<PathChooser *>(sender()); - QTC_ASSERT(pathChooser, return); - if (m_applyMode == ImmediateApply) - setValue(pathChooser->path()); -} - -void SavedAction::actionTriggered(bool) -{ - if (isCheckable()) - setValue(isChecked()); - if (actionGroup() && actionGroup()->isExclusive()) { - // FIXME: should be taken care of more directly - foreach (QAction *act, actionGroup()->actions()) - if (SavedAction *dact = qobject_cast<SavedAction *>(act)) - dact->setValue(bool(act == this)); - } -} - -void SavedAction::trigger(const QVariant &data) -{ - setData(data); - QAction::trigger(); -} - - -////////////////////////////////////////////////////////////////////////// -// -// SavedActionSet -// -////////////////////////////////////////////////////////////////////////// - -void SavedActionSet::insert(SavedAction *action, QWidget *widget) -{ - m_list.append(action); - if (widget) - action->connectWidget(widget); -} - -void SavedActionSet::apply(QSettings *settings) -{ - foreach (SavedAction *action, m_list) - action->apply(settings); -} - -void SavedActionSet::finish() -{ - foreach (SavedAction *action, m_list) - action->disconnectWidget(); -} - diff --git a/libs/utils/savedaction.h b/libs/utils/savedaction.h deleted file mode 100644 index 144b7a12d8d2fb81600763af851f6cc063efa592..0000000000000000000000000000000000000000 --- a/libs/utils/savedaction.h +++ /dev/null @@ -1,123 +0,0 @@ -/** - ****************************************************************************** - * - * @file savedaction.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef SAVED_ACTION_H -#define SAVED_ACTION_H - -#include "utils_global.h" - -#include <QtCore/QString> -#include <QtCore/QVariant> -#include <QtCore/QList> - -#include <QtGui/QAction> - -QT_BEGIN_NAMESPACE -class QSettings; -QT_END_NAMESPACE - -namespace Utils { - -enum ApplyMode { ImmediateApply, DeferedApply }; - -class QTCREATOR_UTILS_EXPORT SavedAction : public QAction -{ - Q_OBJECT - -public: - SavedAction(QObject *parent = 0); - - virtual QVariant value() const; - Q_SLOT virtual void setValue(const QVariant &value, bool doemit = true); - - virtual QVariant defaultValue() const; - Q_SLOT virtual void setDefaultValue(const QVariant &value); - - virtual QAction *updatedAction(const QString &newText); - Q_SLOT virtual void trigger(const QVariant &data); - - // used for persistency - virtual QString settingsKey() const; - Q_SLOT virtual void setSettingsKey(const QString &key); - Q_SLOT virtual void setSettingsKey(const QString &group, const QString &key); - - virtual QString settingsGroup() const; - Q_SLOT virtual void setSettingsGroup(const QString &group); - - virtual void readSettings(QSettings *settings); - Q_SLOT virtual void writeSettings(QSettings *settings); - - virtual void connectWidget(QWidget *widget, ApplyMode applyMode = DeferedApply); - virtual void disconnectWidget(); - Q_SLOT virtual void apply(QSettings *settings); - - virtual QString textPattern() const; - Q_SLOT virtual void setTextPattern(const QString &value); - - QString toString() const; - -signals: - void valueChanged(const QVariant &newValue); - -private: - Q_SLOT void uncheckableButtonClicked(); - Q_SLOT void checkableButtonClicked(bool); - Q_SLOT void lineEditEditingFinished(); - Q_SLOT void pathChooserEditingFinished(); - Q_SLOT void actionTriggered(bool); - Q_SLOT void spinBoxValueChanged(int); - Q_SLOT void spinBoxValueChanged(QString); - - QVariant m_value; - QVariant m_defaultValue; - QString m_settingsKey; - QString m_settingsGroup; - QString m_textPattern; - QString m_textData; - QWidget *m_widget; - ApplyMode m_applyMode; -}; - -class QTCREATOR_UTILS_EXPORT SavedActionSet -{ -public: - SavedActionSet() {} - ~SavedActionSet() {} - - void insert(SavedAction *action, QWidget *widget); - void apply(QSettings *settings); - void finish(); - void clear() { m_list.clear(); } - -private: - QList<SavedAction *> m_list; -}; - -} // namespace Utils - -#endif // SAVED_ACTION_H diff --git a/libs/utils/settingsutils.cpp b/libs/utils/settingsutils.cpp deleted file mode 100644 index 4f3180254f5df3885de2e0430a247fd08ebbb128..0000000000000000000000000000000000000000 --- a/libs/utils/settingsutils.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/** - ****************************************************************************** - * - * @file settingsutils.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "settingsutils.h" - -#include <QtCore/QString> - -namespace Utils { - -QTCREATOR_UTILS_EXPORT QString settingsKey(const QString &category) -{ - QString rc(category); - const QChar underscore = QLatin1Char('_'); - const int size = rc.size(); - for (int i = 0; i < size; i++) { - const QChar c = rc.at(i); - if (!c.isLetterOrNumber() && c != underscore) - rc[i] = underscore; - } - return rc; -} - -} // namespace Utils diff --git a/libs/utils/settingsutils.h b/libs/utils/settingsutils.h deleted file mode 100644 index 49b93cb694cfd38b010bb08e70498edffe101400..0000000000000000000000000000000000000000 --- a/libs/utils/settingsutils.h +++ /dev/null @@ -1,42 +0,0 @@ -/** - ****************************************************************************** - * - * @file settingsutils.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef SETTINGSTUTILS_H -#define SETTINGSTUTILS_H - -#include "utils_global.h" - -namespace Utils { - -// Create a usable settings key from a category, -// for example Editor|C++ -> Editor_C__ -QTCREATOR_UTILS_EXPORT QString settingsKey(const QString &category); - -} // namespace Utils - -#endif // SETTINGSTUTILS_H diff --git a/libs/utils/styledbar.cpp b/libs/utils/styledbar.cpp deleted file mode 100644 index 63a27b77628fac7e803df2f4a0d313515825ca45..0000000000000000000000000000000000000000 --- a/libs/utils/styledbar.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - ****************************************************************************** - * - * @file styledbar.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "styledbar.h" - -#include "stylehelper.h" - -#include <QtCore/QVariant> -#include <QtGui/QPainter> -#include <QtGui/QPixmapCache> -#include <QtGui/QStyle> -#include <QtGui/QStyleOption> - -using namespace Utils; - -StyledBar::StyledBar(QWidget *parent) - : QWidget(parent) -{ - setProperty("panelwidget", true); - setProperty("panelwidget_singlerow", true); -} - -void StyledBar::setSingleRow(bool singleRow) -{ - setProperty("panelwidget_singlerow", singleRow); -} - -bool StyledBar::isSingleRow() const -{ - return property("panelwidget_singlerow").toBool(); -} - -void StyledBar::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event) - QPainter painter(this); - QStyleOption option; - option.rect = rect(); - option.state = QStyle::State_Horizontal; - style()->drawControl(QStyle::CE_ToolBar, &option, &painter, this); -} - -StyledSeparator::StyledSeparator(QWidget *parent) - : QWidget(parent) -{ - setFixedWidth(10); -} - -void StyledSeparator::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event) - QPainter painter(this); - QStyleOption option; - option.rect = rect(); - option.state = QStyle::State_Horizontal; - option.palette = palette(); - style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &option, &painter, this); -} diff --git a/libs/utils/styledbar.h b/libs/utils/styledbar.h deleted file mode 100644 index a1b178bedcb57c452c8efba5a2f665cf63c20b6e..0000000000000000000000000000000000000000 --- a/libs/utils/styledbar.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - ****************************************************************************** - * - * @file styledbar.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef STYLEDBAR_H -#define STYLEDBAR_H - -#include "utils_global.h" - -#include <QtGui/QWidget> - -namespace Utils { - -class QTCREATOR_UTILS_EXPORT StyledBar : public QWidget -{ -public: - StyledBar(QWidget *parent = 0); - void setSingleRow(bool singleRow); - bool isSingleRow() const; -protected: - void paintEvent(QPaintEvent *event); -}; - -class QTCREATOR_UTILS_EXPORT StyledSeparator : public QWidget -{ -public: - StyledSeparator(QWidget *parent = 0); -protected: - void paintEvent(QPaintEvent *event); -}; - -} // Utils - -#endif // STYLEDBAR_H diff --git a/libs/utils/stylehelper.cpp b/libs/utils/stylehelper.cpp deleted file mode 100644 index 879a0b9b3983bf6af17ded91fd0e98e5291769a0..0000000000000000000000000000000000000000 --- a/libs/utils/stylehelper.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/** - ****************************************************************************** - * - * @file stylehelper.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "stylehelper.h" - -#include <QtGui/QPixmapCache> -#include <QtGui/QWidget> -#include <QtCore/QRect> -#include <QtGui/QPainter> -#include <QtGui/QApplication> -#include <QtGui/QPalette> - -// Clamps float color values within (0, 255) -static int clamp(float x) -{ - const int val = x > 255 ? 255 : static_cast<int>(x); - return val < 0 ? 0 : val; -} - -// Clamps float color values within (0, 255) -/* -static int range(float x, int min, int max) -{ - int val = x > max ? max : x; - return val < min ? min : val; -} -*/ - -namespace Utils { - -QColor StyleHelper::mergedColors(const QColor &colorA, const QColor &colorB, int factor) -{ - const int maxFactor = 100; - QColor tmp = colorA; - tmp.setRed((tmp.red() * factor) / maxFactor + (colorB.red() * (maxFactor - factor)) / maxFactor); - tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor); - tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor); - return tmp; -} - -qreal StyleHelper::sidebarFontSize() -{ -#if defined(Q_WS_MAC) - return 9; -#else - return 7.5; -#endif -} - -QPalette StyleHelper::sidebarFontPalette(const QPalette &original) -{ - QPalette palette = original; - palette.setColor(QPalette::Active, QPalette::Text, panelTextColor()); - palette.setColor(QPalette::Active, QPalette::WindowText, panelTextColor()); - palette.setColor(QPalette::Inactive, QPalette::Text, panelTextColor().darker()); - palette.setColor(QPalette::Inactive, QPalette::WindowText, panelTextColor().darker()); - return palette; -} - -QColor StyleHelper::panelTextColor() -{ - //qApp->palette().highlightedText().color(); - return Qt::white; -} - -QColor StyleHelper::m_baseColor(0x666666); - -QColor StyleHelper::baseColor() -{ - return m_baseColor; -} - -QColor StyleHelper::highlightColor() -{ - QColor result = baseColor(); - result.setHsv(result.hue(), - clamp(result.saturation()), - clamp(result.value() * 1.16)); - return result; -} - -QColor StyleHelper::shadowColor() -{ - QColor result = baseColor(); - result.setHsv(result.hue(), - clamp(result.saturation() * 1.1), - clamp(result.value() * 0.70)); - return result; -} - -QColor StyleHelper::borderColor() -{ - QColor result = baseColor(); - result.setHsv(result.hue(), - result.saturation(), - result.value() / 2); - return result; -} - -void StyleHelper::setBaseColor(const QColor &color) -{ - if (color.isValid() && color != m_baseColor) { - m_baseColor = color; - foreach (QWidget *w, QApplication::topLevelWidgets()) - w->update(); - } -} - -static void verticalGradientHelper(QPainter *p, const QRect &spanRect, const QRect &rect) -{ - QColor base = StyleHelper::baseColor(); - QLinearGradient grad(spanRect.topRight(), spanRect.topLeft()); - grad.setColorAt(0, StyleHelper::highlightColor()); - grad.setColorAt(0.301, base); - grad.setColorAt(1, StyleHelper::shadowColor()); - p->fillRect(rect, grad); - - QColor light(255, 255, 255, 80); - p->setPen(light); - p->drawLine(rect.topRight() - QPoint(1, 0), rect.bottomRight() - QPoint(1, 0)); -} - -void StyleHelper::verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect) -{ - if (StyleHelper::usePixmapCache()) { - QString key; - key.sprintf("mh_vertical %d %d %d %d %d", - spanRect.width(), spanRect.height(), clipRect.width(), - clipRect.height(), StyleHelper::baseColor().rgb());; - - QPixmap pixmap; - if (!QPixmapCache::find(key, pixmap)) { - pixmap = QPixmap(clipRect.size()); - QPainter p(&pixmap); - QRect rect(0, 0, clipRect.width(), clipRect.height()); - verticalGradientHelper(&p, spanRect, rect); - p.end(); - QPixmapCache::insert(key, pixmap); - } - - painter->drawPixmap(clipRect.topLeft(), pixmap); - } else { - verticalGradientHelper(painter, spanRect, clipRect); - } -} - -static void horizontalGradientHelper(QPainter *p, const QRect &spanRect, const -QRect &rect) -{ - QColor base = StyleHelper::baseColor(); - QLinearGradient grad(rect.topLeft(), rect.bottomLeft()); - grad.setColorAt(0, StyleHelper::highlightColor().lighter(120)); - if (rect.height() == StyleHelper::navigationWidgetHeight()) { - grad.setColorAt(0.4, StyleHelper::highlightColor()); - grad.setColorAt(0.401, base); - } - grad.setColorAt(1, StyleHelper::shadowColor()); - p->fillRect(rect, grad); - - QLinearGradient shadowGradient(spanRect.topLeft(), spanRect.topRight()); - shadowGradient.setColorAt(0, QColor(0, 0, 0, 30)); - QColor highlight = StyleHelper::highlightColor().lighter(130); - highlight.setAlpha(100); - shadowGradient.setColorAt(0.7, highlight); - shadowGradient.setColorAt(1, QColor(0, 0, 0, 40)); - p->fillRect(rect, shadowGradient); - -} - -void StyleHelper::horizontalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect) -{ - if (StyleHelper::usePixmapCache()) { - QString key; - key.sprintf("mh_horizontal %d %d %d %d %d", - spanRect.width(), spanRect.height(), clipRect.width(), - clipRect.height(), StyleHelper::baseColor().rgb()); - - QPixmap pixmap; - if (!QPixmapCache::find(key, pixmap)) { - pixmap = QPixmap(clipRect.size()); - QPainter p(&pixmap); - QRect rect = QRect(0, 0, clipRect.width(), clipRect.height()); - horizontalGradientHelper(&p, spanRect, rect); - p.end(); - QPixmapCache::insert(key, pixmap); - } - - painter->drawPixmap(clipRect.topLeft(), pixmap); - - } else { - horizontalGradientHelper(painter, spanRect, clipRect); - } -} - -static void menuGradientHelper(QPainter *p, const QRect &spanRect, const QRect &rect) -{ - QLinearGradient grad(spanRect.topLeft(), spanRect.bottomLeft()); - QColor menuColor = StyleHelper::mergedColors(StyleHelper::baseColor(), QColor(244, 244, 244), 25); - grad.setColorAt(0, menuColor.lighter(112)); - grad.setColorAt(1, menuColor); - p->fillRect(rect, grad); -} - -void StyleHelper::menuGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect) -{ - if (StyleHelper::usePixmapCache()) { - QString key; - key.sprintf("mh_menu %d %d %d %d %d", - spanRect.width(), spanRect.height(), clipRect.width(), - clipRect.height(), StyleHelper::baseColor().rgb()); - - QPixmap pixmap; - if (!QPixmapCache::find(key, pixmap)) { - pixmap = QPixmap(clipRect.size()); - QPainter p(&pixmap); - QRect rect = QRect(0, 0, clipRect.width(), clipRect.height()); - menuGradientHelper(&p, spanRect, rect); - p.end(); - QPixmapCache::insert(key, pixmap); - } - - painter->drawPixmap(clipRect.topLeft(), pixmap); - } else { - menuGradientHelper(painter, spanRect, clipRect); - } -} - -} // namespace Utils diff --git a/libs/utils/stylehelper.h b/libs/utils/stylehelper.h deleted file mode 100644 index c0973827eca568acede42621b691224b0dd29456..0000000000000000000000000000000000000000 --- a/libs/utils/stylehelper.h +++ /dev/null @@ -1,78 +0,0 @@ -/** - ****************************************************************************** - * - * @file stylehelper.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef STYLEHELPER_H -#define STYLEHELPER_H - -#include "utils_global.h" - -#include <QtGui/QColor> - -QT_BEGIN_NAMESPACE -class QPalette; -class QPainter; -class QRect; -QT_END_NAMESPACE - -// Helper class holding all custom color values - -namespace Utils { -class QTCREATOR_UTILS_EXPORT StyleHelper -{ -public: - // Height of the project explorer navigation bar - static int navigationWidgetHeight() { return 24; } - static qreal sidebarFontSize(); - static QPalette sidebarFontPalette(const QPalette &original); - - // This is our color table, all colors derive from baseColor - static QColor baseColor(); - static QColor panelTextColor(); - static QColor highlightColor(); - static QColor shadowColor(); - static QColor borderColor(); - static QColor buttonTextColor() { return QColor(0x4c4c4c); } - static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50); - - // Sets the base color and makes sure all top level widgets are updated - static void setBaseColor(const QColor &color); - - // Gradients used for panels - static void horizontalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect); - static void verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect); - static void menuGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect); - - // Pixmap cache should only be enabled for X11 due to slow gradients - static bool usePixmapCache() { return true; } - -private: - static QColor m_baseColor; -}; - -} // namespace Utils -#endif // STYLEHELPER_H diff --git a/libs/utils/submiteditorwidget.cpp b/libs/utils/submiteditorwidget.cpp deleted file mode 100644 index 44cdb1d90b1efeb6de21b5fb0bc7b39f8d28fb25..0000000000000000000000000000000000000000 --- a/libs/utils/submiteditorwidget.cpp +++ /dev/null @@ -1,507 +0,0 @@ -/** - ****************************************************************************** - * - * @file submiteditorwidget.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "submiteditorwidget.h" -#include "submitfieldwidget.h" -#include "ui_submiteditorwidget.h" - -#include <QtCore/QDebug> -#include <QtCore/QPointer> -#include <QtCore/QTimer> - -#include <QtGui/QPushButton> -#include <QtGui/QMenu> -#include <QtGui/QHBoxLayout> -#include <QtGui/QToolButton> -#include <QtGui/QSpacerItem> - -enum { debug = 0 }; -enum { defaultLineWidth = 72 }; - -namespace Utils { - -// QActionPushButton: A push button tied to an action -// (similar to a QToolButton) -class QActionPushButton : public QPushButton -{ - Q_OBJECT -public: - explicit QActionPushButton(QAction *a); - -private slots: - void actionChanged(); -}; - -QActionPushButton::QActionPushButton(QAction *a) : - QPushButton(a->icon(), a->text()) -{ - connect(a, SIGNAL(changed()), this, SLOT(actionChanged())); - connect(this, SIGNAL(clicked()), a, SLOT(trigger())); - setEnabled(a->isEnabled()); -} - -void QActionPushButton::actionChanged() -{ - if (const QAction *a = qobject_cast<QAction*>(sender())) - setEnabled(a->isEnabled()); -} - -// Helpers to retrieve model data -static inline bool listModelChecked(const QAbstractItemModel *model, int row, int column = 0) -{ - const QModelIndex checkableIndex = model->index(row, column, QModelIndex()); - return model->data(checkableIndex, Qt::CheckStateRole).toInt() == Qt::Checked; -} - -static inline QString listModelText(const QAbstractItemModel *model, int row, int column) -{ - const QModelIndex index = model->index(row, column, QModelIndex()); - return model->data(index, Qt::DisplayRole).toString(); -} - -// Find a check item in a model -static bool listModelContainsCheckedItem(const QAbstractItemModel *model) -{ - const int count = model->rowCount(); - for (int i = 0; i < count; i++) - if (listModelChecked(model, i, 0)) - return true; - return false; -} - -// Convenience to extract a list of selected indexes -QList<int> selectedRows(const QAbstractItemView *view) -{ - const QModelIndexList indexList = view->selectionModel()->selectedRows(0); - if (indexList.empty()) - return QList<int>(); - QList<int> rc; - const QModelIndexList::const_iterator cend = indexList.constEnd(); - for (QModelIndexList::const_iterator it = indexList.constBegin(); it != cend; ++it) - rc.push_back(it->row()); - return rc; -} - -// ----------- SubmitEditorWidgetPrivate - -struct SubmitEditorWidgetPrivate -{ - // A pair of position/action to extend context menus - typedef QPair<int, QPointer<QAction> > AdditionalContextMenuAction; - - SubmitEditorWidgetPrivate(); - - Ui::SubmitEditorWidget m_ui; - bool m_filesSelected; - bool m_filesChecked; - int m_fileNameColumn; - int m_activatedRow; - - QList<AdditionalContextMenuAction> descriptionEditContextMenuActions; - QVBoxLayout *m_fieldLayout; - QList<SubmitFieldWidget *> m_fieldWidgets; - int m_lineWidth; -}; - -SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() : - m_filesSelected(false), - m_filesChecked(false), - m_fileNameColumn(1), - m_activatedRow(-1), - m_fieldLayout(0), - m_lineWidth(defaultLineWidth) -{ -} - -SubmitEditorWidget::SubmitEditorWidget(QWidget *parent) : - QWidget(parent), - m_d(new SubmitEditorWidgetPrivate) -{ - m_d->m_ui.setupUi(this); - m_d->m_ui.description->setContextMenuPolicy(Qt::CustomContextMenu); - m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap); - m_d->m_ui.description->setWordWrapMode(QTextOption::WordWrap); - connect(m_d->m_ui.description, SIGNAL(customContextMenuRequested(QPoint)), - this, SLOT(editorCustomContextMenuRequested(QPoint))); - - // File List - m_d->m_ui.fileView->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_d->m_ui.fileView->setRootIsDecorated(false); - connect(m_d->m_ui.fileView, SIGNAL(doubleClicked(QModelIndex)), - this, SLOT(diffActivated(QModelIndex))); - - setFocusPolicy(Qt::StrongFocus); - setFocusProxy(m_d->m_ui.description); -} - -SubmitEditorWidget::~SubmitEditorWidget() -{ - delete m_d; -} - -void SubmitEditorWidget::registerActions(QAction *editorUndoAction, QAction *editorRedoAction, - QAction *submitAction, QAction *diffAction) -{ - if (editorUndoAction) { - editorUndoAction->setEnabled(m_d->m_ui.description->document()->isUndoAvailable()); - connect(m_d->m_ui.description, SIGNAL(undoAvailable(bool)), editorUndoAction, SLOT(setEnabled(bool))); - connect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo())); - } - if (editorRedoAction) { - editorRedoAction->setEnabled(m_d->m_ui.description->document()->isRedoAvailable()); - connect(m_d->m_ui.description, SIGNAL(redoAvailable(bool)), editorRedoAction, SLOT(setEnabled(bool))); - connect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo())); - } - - if (submitAction) { - if (debug) { - int count = 0; - if (const QAbstractItemModel *model = m_d->m_ui.fileView->model()) - count = model->rowCount(); - qDebug() << Q_FUNC_INFO << submitAction << count << "items" << m_d->m_filesChecked; - } - submitAction->setEnabled(m_d->m_filesChecked); - connect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool))); - m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(submitAction)); - } - if (diffAction) { - if (debug) - qDebug() << diffAction << m_d->m_filesSelected; - diffAction->setEnabled(m_d->m_filesSelected); - connect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool))); - connect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected())); - m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(diffAction)); - } -} - -void SubmitEditorWidget::unregisterActions(QAction *editorUndoAction, QAction *editorRedoAction, - QAction *submitAction, QAction *diffAction) -{ - if (editorUndoAction) { - disconnect(m_d->m_ui.description, SIGNAL(undoAvailableChanged(bool)), editorUndoAction, SLOT(setEnabled(bool))); - disconnect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo())); - } - if (editorRedoAction) { - disconnect(m_d->m_ui.description, SIGNAL(redoAvailableChanged(bool)), editorRedoAction, SLOT(setEnabled(bool))); - disconnect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo())); - } - - if (submitAction) - disconnect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool))); - - if (diffAction) { - disconnect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool))); - disconnect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected())); - } -} - -// Make sure we have one terminating NL -static inline QString trimMessageText(const QString &t) -{ - QString rc = t.trimmed(); - rc += QLatin1Char('\n'); - return rc; -} - -// Extract the wrapped text from a text edit, which performs -// the wrapping only optically. -static QString wrappedText(const QTextEdit *e) -{ - const QChar newLine = QLatin1Char('\n'); - QString rc; - QTextCursor cursor(e->document()); - cursor.movePosition(QTextCursor::Start); - while (!cursor.atEnd()) { - cursor.select(QTextCursor::LineUnderCursor); - rc += cursor.selectedText(); - rc += newLine; - cursor.movePosition(QTextCursor::EndOfLine); // Mac needs it - cursor.movePosition(QTextCursor::Right); - } - return rc; -} - -QString SubmitEditorWidget::descriptionText() const -{ - QString rc = trimMessageText(lineWrap() ? wrappedText(m_d->m_ui.description) : m_d->m_ui.description->toPlainText()); - // append field entries - foreach(const SubmitFieldWidget *fw, m_d->m_fieldWidgets) - rc += fw->fieldValues(); - return rc; -} - -void SubmitEditorWidget::setDescriptionText(const QString &text) -{ - m_d->m_ui.description->setPlainText(text); -} - -bool SubmitEditorWidget::lineWrap() const -{ - return m_d->m_ui.description->lineWrapMode() != QTextEdit::NoWrap; -} - -void SubmitEditorWidget::setLineWrap(bool v) -{ - if (debug) - qDebug() << Q_FUNC_INFO << v; - if (v) { - m_d->m_ui.description->setLineWrapColumnOrWidth(m_d->m_lineWidth); - m_d->m_ui.description->setLineWrapMode(QTextEdit::FixedColumnWidth); - } else { - m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap); - } -} - -int SubmitEditorWidget::lineWrapWidth() const -{ - return m_d->m_lineWidth; -} - -void SubmitEditorWidget::setLineWrapWidth(int v) -{ - if (debug) - qDebug() << Q_FUNC_INFO << v << lineWrap(); - if (m_d->m_lineWidth == v) - return; - m_d->m_lineWidth = v; - if (lineWrap()) - m_d->m_ui.description->setLineWrapColumnOrWidth(v); -} - -int SubmitEditorWidget::fileNameColumn() const -{ - return m_d->m_fileNameColumn; -} - -void SubmitEditorWidget::setFileNameColumn(int c) -{ - m_d->m_fileNameColumn = c; -} - -QAbstractItemView::SelectionMode SubmitEditorWidget::fileListSelectionMode() const -{ - return m_d->m_ui.fileView->selectionMode(); -} - -void SubmitEditorWidget::setFileListSelectionMode(QAbstractItemView::SelectionMode sm) -{ - m_d->m_ui.fileView->setSelectionMode(sm); -} - -void SubmitEditorWidget::setFileModel(QAbstractItemModel *model) -{ - m_d->m_ui.fileView->clearSelection(); // trigger the change signals - - m_d->m_ui.fileView->setModel(model); - - if (model->rowCount()) { - const int columnCount = model->columnCount(); - for (int c = 0; c < columnCount; c++) - m_d->m_ui.fileView->resizeColumnToContents(c); - } - - connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), - this, SLOT(updateSubmitAction())); - connect(model, SIGNAL(modelReset()), - this, SLOT(updateSubmitAction())); - connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(updateSubmitAction())); - connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), - this, SLOT(updateSubmitAction())); - connect(m_d->m_ui.fileView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(updateDiffAction())); - updateActions(); -} - -QAbstractItemModel *SubmitEditorWidget::fileModel() const -{ - return m_d->m_ui.fileView->model(); -} - -QStringList SubmitEditorWidget::selectedFiles() const -{ - const QList<int> selection = selectedRows(m_d->m_ui.fileView); - if (selection.empty()) - return QStringList(); - - QStringList rc; - const QAbstractItemModel *model = m_d->m_ui.fileView->model(); - const int count = selection.size(); - for (int i = 0; i < count; i++) - rc.push_back(listModelText(model, selection.at(i), fileNameColumn())); - return rc; -} - -QStringList SubmitEditorWidget::checkedFiles() const -{ - QStringList rc; - const QAbstractItemModel *model = m_d->m_ui.fileView->model(); - if (!model) - return rc; - const int count = model->rowCount(); - for (int i = 0; i < count; i++) - if (listModelChecked(model, i, 0)) - rc.push_back(listModelText(model, i, fileNameColumn())); - return rc; -} - -QTextEdit *SubmitEditorWidget::descriptionEdit() const -{ - return m_d->m_ui.description; -} - -void SubmitEditorWidget::triggerDiffSelected() -{ - const QStringList sel = selectedFiles(); - if (!sel.empty()) - emit diffSelected(sel); -} - -void SubmitEditorWidget::diffActivatedDelayed() -{ - const QStringList files = QStringList(listModelText(m_d->m_ui.fileView->model(), m_d->m_activatedRow, fileNameColumn())); - emit diffSelected(files); -} - -void SubmitEditorWidget::diffActivated(const QModelIndex &index) -{ - // We need to delay the signal, otherwise, the diff editor will not - // be in the foreground. - m_d->m_activatedRow = index.row(); - QTimer::singleShot(0, this, SLOT(diffActivatedDelayed())); -} - -void SubmitEditorWidget::updateActions() -{ - updateSubmitAction(); - updateDiffAction(); -} - -// Enable submit depending on having checked files -void SubmitEditorWidget::updateSubmitAction() -{ - const bool newFilesCheckedState = hasCheckedFiles(); - if (m_d->m_filesChecked != newFilesCheckedState) { - m_d->m_filesChecked = newFilesCheckedState; - emit fileCheckStateChanged(m_d->m_filesChecked); - } -} - -// Enable diff depending on selected files -void SubmitEditorWidget::updateDiffAction() -{ - const bool filesSelected = hasSelection(); - if (m_d->m_filesSelected != filesSelected) { - m_d->m_filesSelected = filesSelected; - emit fileSelectionChanged(m_d->m_filesSelected); - } -} - -bool SubmitEditorWidget::hasSelection() const -{ - // Not present until model is set - if (const QItemSelectionModel *sm = m_d->m_ui.fileView->selectionModel()) - return sm->hasSelection(); - return false; -} - -bool SubmitEditorWidget::hasCheckedFiles() const -{ - if (const QAbstractItemModel *model = m_d->m_ui.fileView->model()) - return listModelContainsCheckedItem(model); - return false; -} - -void SubmitEditorWidget::changeEvent(QEvent *e) -{ - QWidget::changeEvent(e); - switch (e->type()) { - case QEvent::LanguageChange: - m_d->m_ui.retranslateUi(this); - break; - default: - break; - } -} - -void SubmitEditorWidget::insertTopWidget(QWidget *w) -{ - m_d->m_ui.vboxLayout->insertWidget(0, w); -} - -void SubmitEditorWidget::addSubmitFieldWidget(SubmitFieldWidget *f) -{ - if (!m_d->m_fieldLayout) { - // VBox with horizontal, expanding spacer - m_d->m_fieldLayout = new QVBoxLayout; - QHBoxLayout *outerLayout = new QHBoxLayout; - outerLayout->addLayout(m_d->m_fieldLayout); - outerLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored)); - QBoxLayout *descrLayout = qobject_cast<QBoxLayout*>(m_d->m_ui.descriptionBox->layout()); - Q_ASSERT(descrLayout); - descrLayout->addLayout(outerLayout); - } - m_d->m_fieldLayout->addWidget(f); - m_d->m_fieldWidgets.push_back(f); -} - -QList<SubmitFieldWidget *> SubmitEditorWidget::submitFieldWidgets() const -{ - return m_d->m_fieldWidgets; -} - -void SubmitEditorWidget::addDescriptionEditContextMenuAction(QAction *a) -{ - m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(-1, a)); -} - -void SubmitEditorWidget::insertDescriptionEditContextMenuAction(int pos, QAction *a) -{ - m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(pos, a)); -} - -void SubmitEditorWidget::editorCustomContextMenuRequested(const QPoint &pos) -{ - QMenu *menu = m_d->m_ui.description->createStandardContextMenu(); - // Extend - foreach (const SubmitEditorWidgetPrivate::AdditionalContextMenuAction &a, m_d->descriptionEditContextMenuActions) { - if (a.second) { - if (a.first >= 0) { - menu->insertAction(menu->actions().at(a.first), a.second); - } else { - menu->addAction(a.second); - } - } - } - menu->exec(m_d->m_ui.description->mapToGlobal(pos)); - delete menu; -} - -} // namespace Utils - -#include "submiteditorwidget.moc" diff --git a/libs/utils/submiteditorwidget.h b/libs/utils/submiteditorwidget.h deleted file mode 100644 index 969b562bae913c8689d1d2f0e8eff220910e8b85..0000000000000000000000000000000000000000 --- a/libs/utils/submiteditorwidget.h +++ /dev/null @@ -1,146 +0,0 @@ -/** - ****************************************************************************** - * - * @file submiteditorwidget.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef SUBMITEDITORWIDGET_H -#define SUBMITEDITORWIDGET_H - -#include "utils_global.h" - -#include <QtGui/QWidget> -#include <QtGui/QAbstractItemView> - -QT_BEGIN_NAMESPACE -class QTextEdit; -class QListWidgetItem; -class QAction; -class QAbstractItemModel; -class QModelIndex; -class QLineEdit; -QT_END_NAMESPACE - -namespace Utils { - -class SubmitFieldWidget; -struct SubmitEditorWidgetPrivate; - -/* The submit editor presents the commit message in a text editor and an - * checkable list of modified files in a list window. The user can delete - * files from the list by unchecking them or diff the selection - * by doubleclicking. A list model which contains the file in a column - * specified by fileNameColumn should be set using setFileModel(). - * - * Additionally, standard creator actions can be registered: - * Undo/redo will be set up to work with the description editor. - * Submit will be set up to be enabled according to checkstate. - * Diff will be set up to trigger diffSelected(). - * - * Note that the actions are connected by signals; in the rare event that there - * are several instances of the SubmitEditorWidget belonging to the same - * context active, the actions must be registered/unregistered in the editor - * change event. - * Care should be taken to ensure the widget is deleted properly when the - * editor closes. */ - -class QTCREATOR_UTILS_EXPORT SubmitEditorWidget : public QWidget -{ - Q_OBJECT - Q_DISABLE_COPY(SubmitEditorWidget) - Q_PROPERTY(QString descriptionText READ descriptionText WRITE setDescriptionText DESIGNABLE true) - Q_PROPERTY(int fileNameColumn READ fileNameColumn WRITE setFileNameColumn DESIGNABLE false) - Q_PROPERTY(QAbstractItemView::SelectionMode fileListSelectionMode READ fileListSelectionMode WRITE setFileListSelectionMode DESIGNABLE true) - Q_PROPERTY(bool lineWrap READ lineWrap WRITE setLineWrap DESIGNABLE true) - Q_PROPERTY(int lineWrapWidth READ lineWrapWidth WRITE setLineWrapWidth DESIGNABLE true) -public: - explicit SubmitEditorWidget(QWidget *parent = 0); - virtual ~SubmitEditorWidget(); - - void registerActions(QAction *editorUndoAction, QAction *editorRedoAction, - QAction *submitAction = 0, QAction *diffAction = 0); - void unregisterActions(QAction *editorUndoAction, QAction *editorRedoAction, - QAction *submitAction = 0, QAction *diffAction = 0); - - QString descriptionText() const; - void setDescriptionText(const QString &text); - - int fileNameColumn() const; - void setFileNameColumn(int c); - - bool lineWrap() const; - void setLineWrap(bool); - - int lineWrapWidth() const; - void setLineWrapWidth(int); - - QAbstractItemView::SelectionMode fileListSelectionMode() const; - void setFileListSelectionMode(QAbstractItemView::SelectionMode sm); - - void setFileModel(QAbstractItemModel *model); - QAbstractItemModel *fileModel() const; - - // Files to be included in submit - QStringList checkedFiles() const; - - // Selected files for diff - QStringList selectedFiles() const; - - QTextEdit *descriptionEdit() const; - - void addDescriptionEditContextMenuAction(QAction *a); - void insertDescriptionEditContextMenuAction(int pos, QAction *a); - - void addSubmitFieldWidget(SubmitFieldWidget *f); - QList<SubmitFieldWidget *> submitFieldWidgets() const; - -signals: - void diffSelected(const QStringList &); - void fileSelectionChanged(bool someFileSelected); - void fileCheckStateChanged(bool someFileChecked); - -protected: - virtual void changeEvent(QEvent *e); - void insertTopWidget(QWidget *w); - -private slots: - void triggerDiffSelected(); - void diffActivated(const QModelIndex &index); - void diffActivatedDelayed(); - void updateActions(); - void updateSubmitAction(); - void updateDiffAction(); - void editorCustomContextMenuRequested(const QPoint &); - -private: - bool hasSelection() const; - bool hasCheckedFiles() const; - - SubmitEditorWidgetPrivate *m_d; -}; - -} // namespace Utils - -#endif // SUBMITEDITORWIDGET_H diff --git a/libs/utils/submiteditorwidget.ui b/libs/utils/submiteditorwidget.ui deleted file mode 100644 index 957210e40a5f7199ba1bd69bd4551479f7e38ff9..0000000000000000000000000000000000000000 --- a/libs/utils/submiteditorwidget.ui +++ /dev/null @@ -1,72 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>Utils::SubmitEditorWidget</class> - <widget class="QWidget" name="Utils::SubmitEditorWidget"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>582</width> - <height>502</height> - </rect> - </property> - <property name="windowTitle"> - <string>Subversion Submit</string> - </property> - <layout class="QVBoxLayout"> - <item> - <widget class="QGroupBox" name="descriptionBox"> - <property name="title"> - <string>Des&cription</string> - </property> - <property name="flat"> - <bool>true</bool> - </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QTextEdit" name="description"> - <property name="acceptRichText"> - <bool>false</bool> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QGroupBox" name="groupBox"> - <property name="title"> - <string>F&iles</string> - </property> - <property name="flat"> - <bool>true</bool> - </property> - <layout class="QVBoxLayout" name="verticalLayout_2"> - <item> - <widget class="QTreeView" name="fileView"/> - </item> - </layout> - </widget> - </item> - <item> - <layout class="QHBoxLayout" name="buttonLayout"> - <item> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - </layout> - </item> - </layout> - </widget> - <resources/> - <connections/> -</ui> diff --git a/libs/utils/submitfieldwidget.cpp b/libs/utils/submitfieldwidget.cpp deleted file mode 100644 index 93b73f195cc9a79c1c8d00d7e0a6f434bc4473e7..0000000000000000000000000000000000000000 --- a/libs/utils/submitfieldwidget.cpp +++ /dev/null @@ -1,370 +0,0 @@ -/** - ****************************************************************************** - * - * @file submitfieldwidget.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "submitfieldwidget.h" - -#include <QtGui/QComboBox> -#include <QtGui/QHBoxLayout> -#include <QtGui/QVBoxLayout> -#include <QtGui/QLineEdit> -#include <QtGui/QToolButton> -#include <QtGui/QCompleter> -#include <QtGui/QIcon> -#include <QtGui/QToolBar> - -#include <QtCore/QList> -#include <QtCore/QDebug> - -enum { debug = 0 }; -enum { spacing = 2 }; - -static void inline setComboBlocked(QComboBox *cb, int index) -{ - const bool blocked = cb->blockSignals(true); - cb->setCurrentIndex(index); - cb->blockSignals(blocked); -} - -namespace Utils { - -// Field/Row entry -struct FieldEntry { - FieldEntry(); - void createGui(const QIcon &removeIcon); - void deleteGuiLater(); - - QComboBox *combo; - QHBoxLayout *layout; - QLineEdit *lineEdit; - QToolBar *toolBar; - QToolButton *clearButton; - QToolButton *browseButton; - int comboIndex; -}; - -FieldEntry::FieldEntry() : - combo(0), - layout(0), - lineEdit(0), - toolBar(0), - clearButton(0), - browseButton(0), - comboIndex(0) -{ -} - -void FieldEntry::createGui(const QIcon &removeIcon) -{ - layout = new QHBoxLayout; - layout->setMargin(0); - layout ->setSpacing(spacing); - combo = new QComboBox; - layout->addWidget(combo); - lineEdit = new QLineEdit; - layout->addWidget(lineEdit); - toolBar = new QToolBar; - toolBar->setProperty("_q_custom_style_disabled", QVariant(true)); - layout->addWidget(toolBar); - clearButton = new QToolButton; - clearButton->setIcon(removeIcon); - toolBar->addWidget(clearButton); - browseButton = new QToolButton; - browseButton->setText(QLatin1String("...")); - toolBar->addWidget(browseButton); -} - -void FieldEntry::deleteGuiLater() -{ - clearButton->deleteLater(); - browseButton->deleteLater(); - toolBar->deleteLater(); - lineEdit->deleteLater(); - combo->deleteLater(); - layout->deleteLater(); -} - -// ------- SubmitFieldWidgetPrivate -struct SubmitFieldWidgetPrivate { - SubmitFieldWidgetPrivate(); - - int findSender(const QObject *o) const; - int findField(const QString &f, int excluded = -1) const; - inline QString fieldText(int) const; - inline QString fieldValue(int) const; - inline void focusField(int); - - const QIcon removeFieldIcon; - QStringList fields; - QCompleter *completer; - bool hasBrowseButton; - bool allowDuplicateFields; - - QList <FieldEntry> fieldEntries; - QVBoxLayout *layout; -}; - -SubmitFieldWidgetPrivate::SubmitFieldWidgetPrivate() : - removeFieldIcon(QLatin1String(":/utils/images/removesubmitfield.png")), - completer(0), - hasBrowseButton(false), - allowDuplicateFields(false), - layout(0) -{ -} - -int SubmitFieldWidgetPrivate::findSender(const QObject *o) const -{ - const int count = fieldEntries.size(); - for (int i = 0; i < count; i++) { - const FieldEntry &fe = fieldEntries.at(i); - if (fe.combo == o || fe.browseButton == o || fe.clearButton == o || fe.lineEdit == o) - return i; - } - return -1; -} - -int SubmitFieldWidgetPrivate::findField(const QString &ft, int excluded) const -{ - const int count = fieldEntries.size(); - for (int i = 0; i < count; i++) - if (i != excluded && fieldText(i) == ft) - return i; - return -1; -} - -QString SubmitFieldWidgetPrivate::fieldText(int pos) const -{ - return fieldEntries.at(pos).combo->currentText(); -} - -QString SubmitFieldWidgetPrivate::fieldValue(int pos) const -{ - return fieldEntries.at(pos).lineEdit->text(); -} - -void SubmitFieldWidgetPrivate::focusField(int pos) -{ - fieldEntries.at(pos).lineEdit->setFocus(Qt::TabFocusReason); -} - -// SubmitFieldWidget -SubmitFieldWidget::SubmitFieldWidget(QWidget *parent) : - QWidget(parent), - m_d(new SubmitFieldWidgetPrivate) -{ - m_d->layout = new QVBoxLayout; - m_d->layout->setMargin(0); - m_d->layout->setSpacing(spacing); - setLayout(m_d->layout); -} - -SubmitFieldWidget::~SubmitFieldWidget() -{ - delete m_d; -} - -void SubmitFieldWidget::setFields(const QStringList & f) -{ - // remove old fields - for (int i = m_d->fieldEntries.size() - 1 ; i >= 0 ; i--) - removeField(i); - - m_d->fields = f; - if (!f.empty()) - createField(f.front()); -} - -QStringList SubmitFieldWidget::fields() const -{ - return m_d->fields; -} - -bool SubmitFieldWidget::hasBrowseButton() const -{ - return m_d->hasBrowseButton; -} - -void SubmitFieldWidget::setHasBrowseButton(bool d) -{ - if (m_d->hasBrowseButton == d) - return; - m_d->hasBrowseButton = d; - foreach(const FieldEntry &fe, m_d->fieldEntries) - fe.browseButton->setVisible(d); -} - -bool SubmitFieldWidget::allowDuplicateFields() const -{ - return m_d->allowDuplicateFields; -} - -void SubmitFieldWidget::setAllowDuplicateFields(bool v) -{ - m_d->allowDuplicateFields = v; -} - -QCompleter *SubmitFieldWidget::completer() const -{ - return m_d->completer; -} - -void SubmitFieldWidget::setCompleter(QCompleter *c) -{ - if (c == m_d->completer) - return; - m_d->completer = c; - foreach(const FieldEntry &fe, m_d->fieldEntries) - fe.lineEdit->setCompleter(c); -} - -QString SubmitFieldWidget::fieldValue(int pos) const -{ - return m_d->fieldValue(pos); -} - -void SubmitFieldWidget::setFieldValue(int pos, const QString &value) -{ - m_d->fieldEntries.at(pos).lineEdit->setText(value); -} - -QString SubmitFieldWidget::fieldValues() const -{ - const QChar blank = QLatin1Char(' '); - const QChar newLine = QLatin1Char('\n'); - // Format as "RevBy: value\nSigned-Off: value\n" - QString rc; - foreach(const FieldEntry &fe, m_d->fieldEntries) { - const QString value = fe.lineEdit->text().trimmed(); - if (!value.isEmpty()) { - rc += fe.combo->currentText(); - rc += blank; - rc += value; - rc += newLine; - } - } - return rc; -} - -void SubmitFieldWidget::createField(const QString &f) -{ - FieldEntry fe; - fe.createGui(m_d->removeFieldIcon); - fe.combo->addItems(m_d->fields); - if (!f.isEmpty()) { - const int index = fe.combo->findText(f); - if (index != -1) { - setComboBlocked(fe.combo, index); - fe.comboIndex = index; - } - } - - connect(fe.browseButton, SIGNAL(clicked()), this, SLOT(slotBrowseButtonClicked())); - if (!m_d->hasBrowseButton) - fe.browseButton->setVisible(false); - - if (m_d->completer) - fe.lineEdit->setCompleter(m_d->completer); - - connect(fe.combo, SIGNAL(currentIndexChanged(int)), - this, SLOT(slotComboIndexChanged(int))); - connect(fe.clearButton, SIGNAL(clicked()), - this, SLOT(slotRemove())); - m_d->layout->addLayout(fe.layout); - m_d->fieldEntries.push_back(fe); -} - -void SubmitFieldWidget::slotRemove() -{ - // Never remove first entry - const int index = m_d->findSender(sender()); - switch (index) { - case -1: - break; - case 0: - m_d->fieldEntries.front().lineEdit->clear(); - break; - default: - removeField(index); - break; - } -} - -void SubmitFieldWidget::removeField(int index) -{ - FieldEntry fe = m_d->fieldEntries.takeAt(index); - QLayoutItem * item = m_d->layout->takeAt(index); - fe.deleteGuiLater(); - delete item; -} - -void SubmitFieldWidget::slotComboIndexChanged(int comboIndex) -{ - const int pos = m_d->findSender(sender()); - if (debug) - qDebug() << '>' << Q_FUNC_INFO << pos; - if (pos == -1) - return; - // Accept new index or reset combo to previous value? - int &previousIndex = m_d->fieldEntries[pos].comboIndex; - if (comboIndexChange(pos, comboIndex)) { - previousIndex = comboIndex; - } else { - setComboBlocked(m_d->fieldEntries.at(pos).combo, previousIndex); - } - if (debug) - qDebug() << '<' << Q_FUNC_INFO << pos; -} - -// Handle change of a combo. Return "false" if the combo -// is to be reset (refuse new field). -bool SubmitFieldWidget::comboIndexChange(int pos, int index) -{ - const QString newField = m_d->fieldEntries.at(pos).combo->itemText(index); - // If the field is visible elsewhere: focus the existing one and refuse - if (!m_d->allowDuplicateFields) { - const int existingFieldIndex = m_d->findField(newField, pos); - if (existingFieldIndex != -1) { - m_d->focusField(existingFieldIndex); - return false; - } - } - // Empty value: just change the field - if (m_d->fieldValue(pos).isEmpty()) - return true; - // Non-empty: Create a new field and reset the triggering combo - createField(newField); - return false; -} - -void SubmitFieldWidget::slotBrowseButtonClicked() -{ - const int pos = m_d->findSender(sender()); - emit browseButtonClicked(pos, m_d->fieldText(pos)); -} - -} diff --git a/libs/utils/submitfieldwidget.h b/libs/utils/submitfieldwidget.h deleted file mode 100644 index 10154fffd3957a03d95edc5829ed944ce0ea7ed8..0000000000000000000000000000000000000000 --- a/libs/utils/submitfieldwidget.h +++ /dev/null @@ -1,97 +0,0 @@ -/** - ****************************************************************************** - * - * @file submitfieldwidget.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef SUBMITFIELDWIDGET_H -#define SUBMITFIELDWIDGET_H - -#include "utils_global.h" - -#include <QtGui/QWidget> - -QT_BEGIN_NAMESPACE -class QCompleter; -QT_END_NAMESPACE - -namespace Utils { - -struct SubmitFieldWidgetPrivate; - -/* A widget for editing submit message fields like "reviewed-by:", - * "signed-off-by:". It displays them in a vertical row of combo/line edit fields - * that is modeled after the target address controls of mail clients. - * When choosing a different field in the combo, a new row is opened if text - * has been entered for the current field. Optionally, a "Browse..." button and - * completer can be added. */ -class QTCREATOR_UTILS_EXPORT SubmitFieldWidget : public QWidget -{ - Q_OBJECT - Q_PROPERTY(QStringList fields READ fields WRITE setFields DESIGNABLE true) - Q_PROPERTY(bool hasBrowseButton READ hasBrowseButton WRITE setHasBrowseButton DESIGNABLE true) - Q_PROPERTY(bool allowDuplicateFields READ allowDuplicateFields WRITE setAllowDuplicateFields DESIGNABLE true) - -public: - explicit SubmitFieldWidget(QWidget *parent = 0); - virtual ~SubmitFieldWidget(); - - QStringList fields() const; - void setFields(const QStringList&); - - bool hasBrowseButton() const; - void setHasBrowseButton(bool d); - - // Allow several entries for fields ("reviewed-by: a", "reviewed-by: b") - bool allowDuplicateFields() const; - void setAllowDuplicateFields(bool); - - QCompleter *completer() const; - void setCompleter(QCompleter *c); - - QString fieldValue(int pos) const; - void setFieldValue(int pos, const QString &value); - - QString fieldValues() const; - -signals: - void browseButtonClicked(int pos, const QString &field); - -private slots: - void slotRemove(); - void slotComboIndexChanged(int); - void slotBrowseButtonClicked(); - -private: - void removeField(int index); - bool comboIndexChange(int fieldNumber, int index); - void createField(const QString &f); - - SubmitFieldWidgetPrivate *m_d; -}; - -} - -#endif // SUBMITFIELDWIDGET_H diff --git a/libs/utils/synchronousprocess.cpp b/libs/utils/synchronousprocess.cpp deleted file mode 100644 index 332c60f64e66151b08da60a1fca1c84c9299a409..0000000000000000000000000000000000000000 --- a/libs/utils/synchronousprocess.cpp +++ /dev/null @@ -1,493 +0,0 @@ -/** - ****************************************************************************** - * - * @file synchronousprocess.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "synchronousprocess.h" - -#include <QtCore/QDebug> -#include <QtCore/QTimer> -#include <QtCore/QEventLoop> -#include <QtCore/QTextCodec> -#include <QtCore/QFileInfo> -#include <QtCore/QDir> - -#include <QtGui/QApplication> - -#include <limits.h> - -enum { debug = 0 }; - -enum { defaultMaxHangTimerCount = 10 }; - -namespace Utils { - -// ----------- SynchronousProcessResponse -SynchronousProcessResponse::SynchronousProcessResponse() : - result(StartFailed), - exitCode(-1) -{ -} - -void SynchronousProcessResponse::clear() -{ - result = StartFailed; - exitCode = -1; - stdOut.clear(); - stdErr.clear(); -} - -QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse& r) -{ - QDebug nsp = str.nospace(); - nsp << "SynchronousProcessResponse: result=" << r.result << " ex=" << r.exitCode << '\n' - << r.stdOut.size() << " bytes stdout, stderr=" << r.stdErr << '\n'; - return str; -} - -// Data for one channel buffer (stderr/stdout) -struct ChannelBuffer { - ChannelBuffer(); - void clearForRun(); - QByteArray linesRead(); - - QByteArray data; - bool firstData; - bool bufferedSignalsEnabled; - bool firstBuffer; - int bufferPos; -}; - -ChannelBuffer::ChannelBuffer() : - firstData(true), - bufferedSignalsEnabled(false), - firstBuffer(true), - bufferPos(0) -{ -} - -void ChannelBuffer::clearForRun() -{ - firstData = true; - firstBuffer = true; - bufferPos = 0; -} - -/* Check for complete lines read from the device and return them, moving the - * buffer position. This is based on the assumption that '\n' is the new line - * marker in any sane codec. */ -QByteArray ChannelBuffer::linesRead() -{ - // Any new lines? - const int lastLineIndex = data.lastIndexOf('\n'); - if (lastLineIndex == -1 || lastLineIndex <= bufferPos) - return QByteArray(); - const int nextBufferPos = lastLineIndex + 1; - const QByteArray lines = data.mid(bufferPos, nextBufferPos - bufferPos); - bufferPos = nextBufferPos; - return lines; -} - -// ----------- SynchronousProcessPrivate -struct SynchronousProcessPrivate { - SynchronousProcessPrivate(); - void clearForRun(); - - QTextCodec *m_stdOutCodec; - QProcess m_process; - QTimer m_timer; - QEventLoop m_eventLoop; - SynchronousProcessResponse m_result; - int m_hangTimerCount; - int m_maxHangTimerCount; - bool m_startFailure; - - ChannelBuffer m_stdOut; - ChannelBuffer m_stdErr; -}; - -SynchronousProcessPrivate::SynchronousProcessPrivate() : - m_stdOutCodec(0), - m_hangTimerCount(0), - m_maxHangTimerCount(defaultMaxHangTimerCount), - m_startFailure(false) -{ -} - -void SynchronousProcessPrivate::clearForRun() -{ - m_hangTimerCount = 0; - m_stdOut.clearForRun(); - m_stdErr.clearForRun(); - m_result.clear(); - m_startFailure = false; -} - -// ----------- SynchronousProcess -SynchronousProcess::SynchronousProcess() : - m_d(new SynchronousProcessPrivate) -{ - m_d->m_timer.setInterval(1000); - connect(&m_d->m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout())); - connect(&m_d->m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); - connect(&m_d->m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); - connect(&m_d->m_process, SIGNAL(readyReadStandardOutput()), - this, SLOT(stdOutReady())); - connect(&m_d->m_process, SIGNAL(readyReadStandardError()), - this, SLOT(stdErrReady())); -} - -SynchronousProcess::~SynchronousProcess() -{ - delete m_d; -} - -void SynchronousProcess::setTimeout(int timeoutMS) -{ - if (timeoutMS >= 0) { - m_d->m_maxHangTimerCount = qMax(2, timeoutMS / 1000); - } else { - m_d->m_maxHangTimerCount = INT_MAX; - } -} - -int SynchronousProcess::timeout() const -{ - return m_d->m_maxHangTimerCount == INT_MAX ? -1 : 1000 * m_d->m_maxHangTimerCount; -} - -void SynchronousProcess::setStdOutCodec(QTextCodec *c) -{ - m_d->m_stdOutCodec = c; -} - -QTextCodec *SynchronousProcess::stdOutCodec() const -{ - return m_d->m_stdOutCodec; -} - -bool SynchronousProcess::stdOutBufferedSignalsEnabled() const -{ - return m_d->m_stdOut.bufferedSignalsEnabled; -} - -void SynchronousProcess::setStdOutBufferedSignalsEnabled(bool v) -{ - m_d->m_stdOut.bufferedSignalsEnabled = v; -} - -bool SynchronousProcess::stdErrBufferedSignalsEnabled() const -{ - return m_d->m_stdErr.bufferedSignalsEnabled; -} - -void SynchronousProcess::setStdErrBufferedSignalsEnabled(bool v) -{ - m_d->m_stdErr.bufferedSignalsEnabled = v; -} - -QStringList SynchronousProcess::environment() const -{ - return m_d->m_process.environment(); -} - -void SynchronousProcess::setEnvironment(const QStringList &e) -{ - m_d->m_process.setEnvironment(e); -} - -void SynchronousProcess::setWorkingDirectory(const QString &workingDirectory) -{ - m_d->m_process.setWorkingDirectory(workingDirectory); -} - -QString SynchronousProcess::workingDirectory() const -{ - return m_d->m_process.workingDirectory(); -} - -QProcess::ProcessChannelMode SynchronousProcess::processChannelMode () const -{ - return m_d->m_process.processChannelMode(); -} - -void SynchronousProcess::setProcessChannelMode(QProcess::ProcessChannelMode m) -{ - m_d->m_process.setProcessChannelMode(m); -} - -SynchronousProcessResponse SynchronousProcess::run(const QString &binary, - const QStringList &args) -{ - if (debug) - qDebug() << '>' << Q_FUNC_INFO << binary << args; - - m_d->clearForRun(); - - // On Windows, start failure is triggered immediately if the - // executable cannot be found in the path. Do not start the - // event loop in that case. - m_d->m_process.start(binary, args, QIODevice::ReadOnly); - if (!m_d->m_startFailure) { - m_d->m_timer.start(); - QApplication::setOverrideCursor(Qt::WaitCursor); - m_d->m_eventLoop.exec(QEventLoop::ExcludeUserInputEvents); - if (m_d->m_result.result == SynchronousProcessResponse::Finished || m_d->m_result.result == SynchronousProcessResponse::FinishedError) { - processStdOut(false); - processStdErr(false); - } - - m_d->m_result.stdOut = convertStdOut(m_d->m_stdOut.data); - m_d->m_result.stdErr = convertStdErr(m_d->m_stdErr.data); - - m_d->m_timer.stop(); - QApplication::restoreOverrideCursor(); - } - - if (debug) - qDebug() << '<' << Q_FUNC_INFO << binary << m_d->m_result; - return m_d->m_result; -} - -void SynchronousProcess::slotTimeout() -{ - if (++m_d->m_hangTimerCount > m_d->m_maxHangTimerCount) { - if (debug) - qDebug() << Q_FUNC_INFO << "HANG detected, killing"; - m_d->m_process.kill(); - m_d->m_result.result = SynchronousProcessResponse::Hang; - } else { - if (debug) - qDebug() << Q_FUNC_INFO << m_d->m_hangTimerCount; - } -} - -void SynchronousProcess::finished(int exitCode, QProcess::ExitStatus e) -{ - if (debug) - qDebug() << Q_FUNC_INFO << exitCode << e; - m_d->m_hangTimerCount = 0; - switch (e) { - case QProcess::NormalExit: - m_d->m_result.result = exitCode ? SynchronousProcessResponse::FinishedError : SynchronousProcessResponse::Finished; - m_d->m_result.exitCode = exitCode; - break; - case QProcess::CrashExit: - // Was hang detected before and killed? - if (m_d->m_result.result != SynchronousProcessResponse::Hang) - m_d->m_result.result = SynchronousProcessResponse::TerminatedAbnormally; - m_d->m_result.exitCode = -1; - break; - } - m_d->m_eventLoop.quit(); -} - -void SynchronousProcess::error(QProcess::ProcessError e) -{ - m_d->m_hangTimerCount = 0; - if (debug) - qDebug() << Q_FUNC_INFO << e; - // Was hang detected before and killed? - if (m_d->m_result.result != SynchronousProcessResponse::Hang) - m_d->m_result.result = SynchronousProcessResponse::StartFailed; - m_d->m_startFailure = true; - m_d->m_eventLoop.quit(); -} - -void SynchronousProcess::stdOutReady() -{ - m_d->m_hangTimerCount = 0; - processStdOut(true); -} - -void SynchronousProcess::stdErrReady() -{ - m_d->m_hangTimerCount = 0; - processStdErr(true); -} - -QString SynchronousProcess::convertStdErr(const QByteArray &ba) -{ - return QString::fromLocal8Bit(ba.constData(), ba.size()).remove(QLatin1Char('\r')); -} - -QString SynchronousProcess::convertStdOut(const QByteArray &ba) const -{ - QString stdOut = m_d->m_stdOutCodec ? m_d->m_stdOutCodec->toUnicode(ba) : QString::fromLocal8Bit(ba.constData(), ba.size()); - return stdOut.remove(QLatin1Char('\r')); -} - -void SynchronousProcess::processStdOut(bool emitSignals) -{ - // Handle binary data - const QByteArray ba = m_d->m_process.readAllStandardOutput(); - if (debug > 1) - qDebug() << Q_FUNC_INFO << emitSignals << ba; - if (!ba.isEmpty()) { - m_d->m_stdOut.data += ba; - if (emitSignals) { - // Emit binary signals - emit stdOut(ba, m_d->m_stdOut.firstData); - m_d->m_stdOut.firstData = false; - // Buffered. Emit complete lines? - if (m_d->m_stdOut.bufferedSignalsEnabled) { - const QByteArray lines = m_d->m_stdOut.linesRead(); - if (!lines.isEmpty()) { - emit stdOutBuffered(convertStdOut(lines), m_d->m_stdOut.firstBuffer); - m_d->m_stdOut.firstBuffer = false; - } - } - } - } -} - -void SynchronousProcess::processStdErr(bool emitSignals) -{ - // Handle binary data - const QByteArray ba = m_d->m_process.readAllStandardError(); - if (debug > 1) - qDebug() << Q_FUNC_INFO << emitSignals << ba; - if (!ba.isEmpty()) { - m_d->m_stdErr.data += ba; - if (emitSignals) { - // Emit binary signals - emit stdErr(ba, m_d->m_stdErr.firstData); - m_d->m_stdErr.firstData = false; - if (m_d->m_stdErr.bufferedSignalsEnabled) { - // Buffered. Emit complete lines? - const QByteArray lines = m_d->m_stdErr.linesRead(); - if (!lines.isEmpty()) { - emit stdErrBuffered(convertStdErr(lines), m_d->m_stdErr.firstBuffer); - m_d->m_stdErr.firstBuffer = false; - } - } - } - } -} - -// Path utilities - -enum OS_Type { OS_Mac, OS_Windows, OS_Unix }; - -#ifdef Q_OS_WIN -static const OS_Type pathOS = OS_Windows; -#else -# ifdef Q_OS_MAC -static const OS_Type pathOS = OS_Mac; -# else -static const OS_Type pathOS = OS_Unix; -# endif -#endif - -// Locate a binary in a directory, applying all kinds of -// extensions the operating system supports. -static QString checkBinary(const QDir &dir, const QString &binary) -{ - // naive UNIX approach - const QFileInfo info(dir.filePath(binary)); - if (info.isFile() && info.isExecutable()) - return info.absoluteFilePath(); - - // Does the OS have some weird extension concept or does the - // binary have a 3 letter extension? - if (pathOS == OS_Unix) - return QString(); - const int dotIndex = binary.lastIndexOf(QLatin1Char('.')); - if (dotIndex != -1 && dotIndex == binary.size() - 4) - return QString(); - - switch (pathOS) { - case OS_Unix: - break; - case OS_Windows: { - static const char *windowsExtensions[] = {".cmd", ".bat", ".exe", ".com" }; - // Check the Windows extensions using the order - const int windowsExtensionCount = sizeof(windowsExtensions)/sizeof(const char*); - for (int e = 0; e < windowsExtensionCount; e ++) { - const QFileInfo windowsBinary(dir.filePath(binary + QLatin1String(windowsExtensions[e]))); - if (windowsBinary.isFile() && windowsBinary.isExecutable()) - return windowsBinary.absoluteFilePath(); - } - } - break; - case OS_Mac: { - // Check for Mac app folders - const QFileInfo appFolder(dir.filePath(binary + QLatin1String(".app"))); - if (appFolder.isDir()) { - QString macBinaryPath = appFolder.absoluteFilePath(); - macBinaryPath += QLatin1String("/Contents/MacOS/"); - macBinaryPath += binary; - const QFileInfo macBinary(macBinaryPath); - if (macBinary.isFile() && macBinary.isExecutable()) - return macBinary.absoluteFilePath(); - } - } - break; - } - return QString(); -} - -QString SynchronousProcess::locateBinary(const QString &path, const QString &binary) -{ - // Absolute file? - const QFileInfo absInfo(binary); - if (absInfo.isAbsolute()) - return checkBinary(absInfo.dir(), absInfo.fileName()); - - // Windows finds binaries in the current directory - if (pathOS == OS_Windows) { - const QString currentDirBinary = checkBinary(QDir::current(), binary); - if (!currentDirBinary.isEmpty()) - return currentDirBinary; - } - - const QStringList paths = path.split(pathSeparator()); - if (paths.empty()) - return QString(); - const QStringList::const_iterator cend = paths.constEnd(); - for (QStringList::const_iterator it = paths.constBegin(); it != cend; ++it) { - const QDir dir(*it); - const QString rc = checkBinary(dir, binary); - if (!rc.isEmpty()) - return rc; - } - return QString(); -} - -QString SynchronousProcess::locateBinary(const QString &binary) -{ - const QByteArray path = qgetenv("PATH"); - return locateBinary(QString::fromLocal8Bit(path), binary); -} - -QChar SynchronousProcess::pathSeparator() -{ - if (pathOS == OS_Windows) - return QLatin1Char(';'); - return QLatin1Char(':'); -} - -} // namespace Utils diff --git a/libs/utils/synchronousprocess.h b/libs/utils/synchronousprocess.h deleted file mode 100644 index a3cf2df44a4baa7e17967ae93a52ddc3c1aa8f42..0000000000000000000000000000000000000000 --- a/libs/utils/synchronousprocess.h +++ /dev/null @@ -1,148 +0,0 @@ -/** - ****************************************************************************** - * - * @file synchronousprocess.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef SYNCHRONOUSPROCESS_H -#define SYNCHRONOUSPROCESS_H - -#include "utils_global.h" - -#include <QtCore/QObject> -#include <QtCore/QProcess> -#include <QtCore/QStringList> - -QT_BEGIN_NAMESPACE -class QTextCodec; -class QDebug; -class QByteArray; -QT_END_NAMESPACE - -namespace Utils { - -struct SynchronousProcessPrivate; - -/* Result of SynchronousProcess execution */ -struct QTCREATOR_UTILS_EXPORT SynchronousProcessResponse -{ - enum Result { - // Finished with return code 0 - Finished, - // Finished with return code != 0 - FinishedError, - // Process terminated abnormally (kill) - TerminatedAbnormally, - // Executable could not be started - StartFailed, - // Hang, no output after time out - Hang }; - - SynchronousProcessResponse(); - void clear(); - - Result result; - int exitCode; - QString stdOut; - QString stdErr; -}; - -QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse &); - -/* SynchronousProcess: Runs a synchronous process in its own event loop - * that blocks only user input events. Thus, it allows for the gui to - * repaint and append output to log windows. - * - * The stdOut(), stdErr() signals are emitted unbuffered as the process - * writes them. - * - * The stdOutBuffered(), stdErrBuffered() signals are emitted with complete - * lines based on the '\n' marker if they are enabled using - * stdOutBufferedSignalsEnabled()/setStdErrBufferedSignalsEnabled(). - * They would typically be used for log windows. */ - -class QTCREATOR_UTILS_EXPORT SynchronousProcess : public QObject -{ - Q_OBJECT -public: - SynchronousProcess(); - virtual ~SynchronousProcess(); - - /* Timeout for hanging processes (no reaction on stderr/stdout)*/ - void setTimeout(int timeoutMS); - int timeout() const; - - void setStdOutCodec(QTextCodec *c); - QTextCodec *stdOutCodec() const; - - QProcess::ProcessChannelMode processChannelMode () const; - void setProcessChannelMode(QProcess::ProcessChannelMode m); - - bool stdOutBufferedSignalsEnabled() const; - void setStdOutBufferedSignalsEnabled(bool); - - bool stdErrBufferedSignalsEnabled() const; - void setStdErrBufferedSignalsEnabled(bool); - - QStringList environment() const; - void setEnvironment(const QStringList &); - - void setWorkingDirectory(const QString &workingDirectory); - QString workingDirectory() const; - - SynchronousProcessResponse run(const QString &binary, const QStringList &args); - - // Helpers to find binaries. Do not use it for other path variables - // and file types. - static QString locateBinary(const QString &binary); - static QString locateBinary(const QString &path, const QString &binary); - static QChar pathSeparator(); - -signals: - void stdOut(const QByteArray &data, bool firstTime); - void stdErr(const QByteArray &data, bool firstTime); - - void stdOutBuffered(const QString &data, bool firstTime); - void stdErrBuffered(const QString &data, bool firstTime); - -private slots: - void slotTimeout(); - void finished(int exitCode, QProcess::ExitStatus e); - void error(QProcess::ProcessError); - void stdOutReady(); - void stdErrReady(); - -private: - void processStdOut(bool emitSignals); - void processStdErr(bool emitSignals); - static QString convertStdErr(const QByteArray &); - QString convertStdOut(const QByteArray &) const; - - SynchronousProcessPrivate *m_d; -}; - -} // namespace Utils - -#endif diff --git a/libs/utils/treewidgetcolumnstretcher.cpp b/libs/utils/treewidgetcolumnstretcher.cpp deleted file mode 100644 index c5dc21a15a1f2325bce7525ebf6a46350ea9246a..0000000000000000000000000000000000000000 --- a/libs/utils/treewidgetcolumnstretcher.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - ****************************************************************************** - * - * @file treewidgetcolumnstretcher.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "treewidgetcolumnstretcher.h" -#include <QtGui/QTreeWidget> -#include <QtGui/QHideEvent> -#include <QtGui/QHeaderView> -using namespace Utils; - -TreeWidgetColumnStretcher::TreeWidgetColumnStretcher(QTreeWidget *treeWidget, int columnToStretch) - : QObject(treeWidget->header()), m_columnToStretch(columnToStretch) -{ - parent()->installEventFilter(this); - QHideEvent fake; - TreeWidgetColumnStretcher::eventFilter(parent(), &fake); -} - -bool TreeWidgetColumnStretcher::eventFilter(QObject *obj, QEvent *ev) -{ - if (obj == parent()) { - if (ev->type() == QEvent::Show) { - QHeaderView *hv = qobject_cast<QHeaderView*>(obj); - for (int i = 0; i < hv->count(); ++i) - hv->setResizeMode(i, QHeaderView::Interactive); - } else if (ev->type() == QEvent::Hide) { - QHeaderView *hv = qobject_cast<QHeaderView*>(obj); - for (int i = 0; i < hv->count(); ++i) - hv->setResizeMode(i, i == m_columnToStretch ? QHeaderView::Stretch : QHeaderView::ResizeToContents); - } else if (ev->type() == QEvent::Resize) { - QHeaderView *hv = qobject_cast<QHeaderView*>(obj); - if (hv->resizeMode(m_columnToStretch) == QHeaderView::Interactive) { - QResizeEvent *re = static_cast<QResizeEvent*>(ev); - int diff = re->size().width() - re->oldSize().width() ; - hv->resizeSection(m_columnToStretch, qMax(32, hv->sectionSize(1) + diff)); - } - } - } - return false; -} diff --git a/libs/utils/treewidgetcolumnstretcher.h b/libs/utils/treewidgetcolumnstretcher.h deleted file mode 100644 index 7d6619b2c2a5f7dc53cd5a203875b414c30b169e..0000000000000000000000000000000000000000 --- a/libs/utils/treewidgetcolumnstretcher.h +++ /dev/null @@ -1,60 +0,0 @@ -/** - ****************************************************************************** - * - * @file treewidgetcolumnstretcher.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef TREEWIDGETCOLUMNSTRETCHER_H -#define TREEWIDGETCOLUMNSTRETCHER_H - -#include "utils_global.h" -#include <QObject> - -QT_BEGIN_NAMESPACE -class QTreeWidget; -QT_END_NAMESPACE - -namespace Utils { - -/* - -The class fixes QTreeWidget to resize all columns to contents, except one -stretching column. As opposed to standard QTreeWidget, all columns are -still interactively resizable. - -*/ - -class QTCREATOR_UTILS_EXPORT TreeWidgetColumnStretcher : public QObject -{ - int m_columnToStretch; -public: - TreeWidgetColumnStretcher(QTreeWidget *treeWidget, int columnToStretch); - - bool eventFilter(QObject *obj, QEvent *ev); -}; - -} // namespace Utils - -#endif // TREEWIDGETCOLUMNSTRETCHER_H diff --git a/libs/utils/uncommentselection.cpp b/libs/utils/uncommentselection.cpp deleted file mode 100644 index 64f7ddcf97c63720a727e0d3d8132b8af81781d7..0000000000000000000000000000000000000000 --- a/libs/utils/uncommentselection.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/** - ****************************************************************************** - * - * @file uncommentselection.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "uncommentselection.h" -#include <QtGui/QPlainTextEdit> -#include <QtGui/QTextCursor> -#include <QtGui/QTextBlock> -#include <QtGui/QTextDocument> - -void Utils::unCommentSelection(QPlainTextEdit *edit) -{ - QTextCursor cursor = edit->textCursor(); - QTextDocument *doc = cursor.document(); - cursor.beginEditBlock(); - - int pos = cursor.position(); - int anchor = cursor.anchor(); - int start = qMin(anchor, pos); - int end = qMax(anchor, pos); - bool anchorIsStart = (anchor == start); - - QTextBlock startBlock = doc->findBlock(start); - QTextBlock endBlock = doc->findBlock(end); - - if (end > start && endBlock.position() == end) { - --end; - endBlock = endBlock.previous(); - } - - bool doCStyleUncomment = false; - bool doCStyleComment = false; - bool doCppStyleUncomment = false; - - bool hasSelection = cursor.hasSelection(); - - if (hasSelection) { - QString startText = startBlock.text(); - int startPos = start - startBlock.position(); - bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty(); - if ((startPos >= 2 - && startText.at(startPos-2) == QLatin1Char('/') - && startText.at(startPos-1) == QLatin1Char('*'))) { - startPos -= 2; - start -= 2; - } - - bool hasSelStart = (startPos < startText.length() - 2 - && startText.at(startPos) == QLatin1Char('/') - && startText.at(startPos+1) == QLatin1Char('*')); - - - QString endText = endBlock.text(); - int endPos = end - endBlock.position(); - bool hasTrailingCharacters = !endText.left(endPos).remove(QLatin1String("//")).trimmed().isEmpty() - && !endText.mid(endPos).trimmed().isEmpty(); - if ((endPos <= endText.length() - 2 - && endText.at(endPos) == QLatin1Char('*') - && endText.at(endPos+1) == QLatin1Char('/'))) { - endPos += 2; - end += 2; - } - - bool hasSelEnd = (endPos >= 2 - && endText.at(endPos-2) == QLatin1Char('*') - && endText.at(endPos-1) == QLatin1Char('/')); - - doCStyleUncomment = hasSelStart && hasSelEnd; - doCStyleComment = !doCStyleUncomment && (hasLeadingCharacters || hasTrailingCharacters); - } - - if (doCStyleUncomment) { - cursor.setPosition(end); - cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, 2); - cursor.removeSelectedText(); - cursor.setPosition(start); - cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2); - cursor.removeSelectedText(); - } else if (doCStyleComment) { - cursor.setPosition(end); - cursor.insertText(QLatin1String("*/")); - cursor.setPosition(start); - cursor.insertText(QLatin1String("/*")); - } else { - endBlock = endBlock.next(); - doCppStyleUncomment = true; - for (QTextBlock block = startBlock; block != endBlock; block = block.next()) { - QString text = block.text(); - if (!text.trimmed().startsWith(QLatin1String("//"))) { - doCppStyleUncomment = false; - break; - } - } - for (QTextBlock block = startBlock; block != endBlock; block = block.next()) { - if (doCppStyleUncomment) { - QString text = block.text(); - int i = 0; - while (i < text.size() - 1) { - if (text.at(i) == QLatin1Char('/') - && text.at(i + 1) == QLatin1Char('/')) { - cursor.setPosition(block.position() + i); - cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2); - cursor.removeSelectedText(); - break; - } - if (!text.at(i).isSpace()) - break; - ++i; - } - } else { - cursor.setPosition(block.position()); - cursor.insertText(QLatin1String("//")); - } - } - } - - // adjust selection when commenting out - if (hasSelection && !doCStyleUncomment && !doCppStyleUncomment) { - cursor = edit->textCursor(); - if (!doCStyleComment) - start = startBlock.position(); // move the double slashes into the selection - int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor(); - if (anchorIsStart) { - cursor.setPosition(start); - cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor); - } else { - cursor.setPosition(lastSelPos); - cursor.setPosition(start, QTextCursor::KeepAnchor); - } - edit->setTextCursor(cursor); - } - - cursor.endEditBlock(); -} - diff --git a/libs/utils/uncommentselection.h b/libs/utils/uncommentselection.h deleted file mode 100644 index 6be0dca0803278615f643bc21279e4d490a763f9..0000000000000000000000000000000000000000 --- a/libs/utils/uncommentselection.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - ****************************************************************************** - * - * @file uncommentselection.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef UNCOMMENTSELECTION_H -#define UNCOMMENTSELECTION_H - -#include "utils_global.h" - -QT_BEGIN_NAMESPACE -class QPlainTextEdit; -QT_END_NAMESPACE - -namespace Utils { - -QTCREATOR_UTILS_EXPORT void unCommentSelection(QPlainTextEdit *edit); - -} // end of namespace Utils - -#endif // UNCOMMENTSELECTION_H diff --git a/libs/utils/utils.pri b/libs/utils/utils.pri deleted file mode 100644 index 5f35399b906293fe2ab89c6c51814becd1fa715e..0000000000000000000000000000000000000000 --- a/libs/utils/utils.pri +++ /dev/null @@ -1,9 +0,0 @@ -macx { - CONFIG(debug, debug|release):LIBS *= -lUtils_debug - else:LIBS *= -lUtils -} else:win32 { - CONFIG(debug, debug|release):LIBS *= -lUtilsd - else:LIBS *= -lUtils -} else { - LIBS += -l$$qtLibraryTarget(Utils) -} diff --git a/libs/utils/utils.pro b/libs/utils/utils.pro deleted file mode 100644 index 2e21056f2efbaacff2c9a35786600df440be3e9a..0000000000000000000000000000000000000000 --- a/libs/utils/utils.pro +++ /dev/null @@ -1,108 +0,0 @@ -TEMPLATE = lib -TARGET = Utils - -QT += gui \ - network \ - xml - -DEFINES += QTCREATOR_UTILS_LIB - -include(../../openpilotgcslibrary.pri) - -SOURCES += reloadpromptutils.cpp \ - settingsutils.cpp \ - filesearch.cpp \ - pathchooser.cpp \ - pathlisteditor.cpp \ - filewizardpage.cpp \ - filewizarddialog.cpp \ - projectintropage.cpp \ - basevalidatinglineedit.cpp \ - filenamevalidatinglineedit.cpp \ - projectnamevalidatinglineedit.cpp \ - codegeneration.cpp \ - newclasswidget.cpp \ - classnamevalidatinglineedit.cpp \ - linecolumnlabel.cpp \ - fancylineedit.cpp \ - qtcolorbutton.cpp \ - savedaction.cpp \ - submiteditorwidget.cpp \ - synchronousprocess.cpp \ - submitfieldwidget.cpp \ - consoleprocess.cpp \ - uncommentselection.cpp \ - parameteraction.cpp \ - treewidgetcolumnstretcher.cpp \ - checkablemessagebox.cpp \ - styledbar.cpp \ - stylehelper.cpp \ - welcomemodetreewidget.cpp \ - iwelcomepage.cpp \ - fancymainwindow.cpp \ - detailsbutton.cpp \ - detailswidget.cpp \ - coordinateconversions.cpp \ - pathutils.cpp \ - worldmagmodel.cpp \ - homelocationutil.cpp -SOURCES += xmlconfig.cpp - -win32 { - SOURCES += abstractprocess_win.cpp \ - consoleprocess_win.cpp \ - winutils.cpp - HEADERS += winutils.h -} -else:SOURCES += consoleprocess_unix.cpp - -HEADERS += utils_global.h \ - reloadpromptutils.h \ - settingsutils.h \ - filesearch.h \ - listutils.h \ - pathchooser.h \ - pathlisteditor.h \ - filewizardpage.h \ - filewizarddialog.h \ - projectintropage.h \ - basevalidatinglineedit.h \ - filenamevalidatinglineedit.h \ - projectnamevalidatinglineedit.h \ - codegeneration.h \ - newclasswidget.h \ - classnamevalidatinglineedit.h \ - linecolumnlabel.h \ - fancylineedit.h \ - qtcolorbutton.h \ - savedaction.h \ - submiteditorwidget.h \ - abstractprocess.h \ - consoleprocess.h \ - synchronousprocess.h \ - submitfieldwidget.h \ - uncommentselection.h \ - parameteraction.h \ - treewidgetcolumnstretcher.h \ - checkablemessagebox.h \ - qtcassert.h \ - styledbar.h \ - stylehelper.h \ - welcomemodetreewidget.h \ - iwelcomepage.h \ - fancymainwindow.h \ - detailsbutton.h \ - detailswidget.h \ - coordinateconversions.h \ - pathutils.h \ - worldmagmodel.h \ - homelocationutil.h -HEADERS += xmlconfig.h - -FORMS += filewizardpage.ui \ - projectintropage.ui \ - newclasswidget.ui \ - submiteditorwidget.ui \ - checkablemessagebox.ui - -RESOURCES += utils.qrc diff --git a/libs/utils/utils.qrc b/libs/utils/utils.qrc deleted file mode 100644 index ef180b21fe096b2b982b152b1dabf16beb260e15..0000000000000000000000000000000000000000 --- a/libs/utils/utils.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/utils" > - <file>images/removesubmitfield.png</file> - </qresource> -</RCC> diff --git a/libs/utils/utils_external.pri b/libs/utils/utils_external.pri deleted file mode 100644 index dd78de62f1b4f6f534e42e1a96424426bfd72205..0000000000000000000000000000000000000000 --- a/libs/utils/utils_external.pri +++ /dev/null @@ -1,123 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) Mi Jun 22 00:51:09 2011 -###################################################################### - -DEPENDPATH += . \ - ../. -INCLUDEPATH += . \ - ../. - -# HACK! BIG TIME! -DEFINES += EXTERNAL_USE - -DEFINES += QTCREATOR_UTILS_LIB - -# submiteditorwidget.h \ -# qtcolorbutton.h \ - -# Input -HEADERS += utils_global.h \ - reloadpromptutils.h \ - settingsutils.h \ - filesearch.h \ - listutils.h \ - pathchooser.h \ - pathlisteditor.h \ - filewizardpage.h \ - filewizarddialog.h \ - projectintropage.h \ - basevalidatinglineedit.h \ - filenamevalidatinglineedit.h \ - projectnamevalidatinglineedit.h \ - codegeneration.h \ - newclasswidget.h \ - classnamevalidatinglineedit.h \ - linecolumnlabel.h \ - fancylineedit.h \ - savedaction.h \ - abstractprocess.h \ - consoleprocess.h \ - synchronousprocess.h \ - submitfieldwidget.h \ - uncommentselection.h \ - parameteraction.h \ - treewidgetcolumnstretcher.h \ - checkablemessagebox.h \ - qtcassert.h \ - styledbar.h \ - stylehelper.h \ - welcomemodetreewidget.h \ - iwelcomepage.h \ - fancymainwindow.h \ - detailsbutton.h \ - detailswidget.h \ - coordinateconversions.h \ - pathutils.h \ - worldmagmodel.h \ - homelocationutil.h \ - xmlconfig.h - -win32 { -HEADERS += winutils.h -} - -FORMS += checkablemessagebox.ui \ - filewizardpage.ui \ - newclasswidget.ui \ - projectintropage.ui \ - submiteditorwidget.ui - -win32 { -SOURCES += abstractprocess_win.cpp \ - consoleprocess_win.cpp \ - winutils.cpp -} - -macx { -SOURCES += consoleprocess_unix.cpp -} - -linux-g++|linux-g++-64 { -SOURCES += consoleprocess_unix.cpp -} - -# submiteditorwidget.cpp \ -# qtcolorbutton.cpp \ - -SOURCES += reloadpromptutils.cpp \ - settingsutils.cpp \ - filesearch.cpp \ - pathchooser.cpp \ - pathlisteditor.cpp \ - filewizardpage.cpp \ - filewizarddialog.cpp \ - projectintropage.cpp \ - basevalidatinglineedit.cpp \ - filenamevalidatinglineedit.cpp \ - projectnamevalidatinglineedit.cpp \ - codegeneration.cpp \ - newclasswidget.cpp \ - classnamevalidatinglineedit.cpp \ - linecolumnlabel.cpp \ - fancylineedit.cpp \ - savedaction.cpp \ - synchronousprocess.cpp \ - submitfieldwidget.cpp \ - consoleprocess.cpp \ - uncommentselection.cpp \ - parameteraction.cpp \ - treewidgetcolumnstretcher.cpp \ - checkablemessagebox.cpp \ - styledbar.cpp \ - stylehelper.cpp \ - welcomemodetreewidget.cpp \ - iwelcomepage.cpp \ - fancymainwindow.cpp \ - detailsbutton.cpp \ - detailswidget.cpp \ - coordinateconversions.cpp \ - pathutils.cpp \ - worldmagmodel.cpp \ - homelocationutil.cpp \ - xmlconfig.cpp -RESOURCES += utils.qrc diff --git a/libs/utils/utils_global.h b/libs/utils/utils_global.h deleted file mode 100644 index 45bbf5b45ffb5f36eaf28d7836056207a7a033fd..0000000000000000000000000000000000000000 --- a/libs/utils/utils_global.h +++ /dev/null @@ -1,42 +0,0 @@ -/** - ****************************************************************************** - * - * @file utils_global.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef UTILS_GLOBAL_H -#define UTILS_GLOBAL_H - -#include <QtCore/qglobal.h> - -#if defined(QTCREATOR_UTILS_LIB) -# define QTCREATOR_UTILS_EXPORT Q_DECL_EXPORT -#elif defined(QTCREATOR_UTILS_STATIC_LIB) // Abuse single files for manual tests -# define QTCREATOR_UTILS_EXPORT -#else -# define QTCREATOR_UTILS_EXPORT Q_DECL_IMPORT -#endif - -#endif // UTILS_GLOBAL_H diff --git a/libs/utils/welcomemodetreewidget.cpp b/libs/utils/welcomemodetreewidget.cpp deleted file mode 100644 index 1cb0d1e7389d60c0dc46adc4ca7c10e81e1069e7..0000000000000000000000000000000000000000 --- a/libs/utils/welcomemodetreewidget.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - ****************************************************************************** - * - * @file welcomemodetreewidget.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "welcomemodetreewidget.h" - -#include <QtGui/QLabel> -#include <QtGui/QAction> -#include <QtGui/QBoxLayout> -#include <QtGui/QHeaderView> - -namespace Utils { - -void WelcomeModeLabel::setStyledText(const QString &text) -{ - QString rc = QLatin1String( - "<html><head><style type=\"text/css\">p, li { white-space: pre-wrap; }</style></head>" - "<body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">" - "<p style=\" margin-top:16px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">" - "<span style=\" font-size:x-large; color:#555555;\">"); - rc += text; - rc += QLatin1String("</span></p><hr/></body></html>"); - setText(rc); -} - -struct WelcomeModeTreeWidgetPrivate -{ - WelcomeModeTreeWidgetPrivate() {} - QIcon bullet; -}; - -WelcomeModeTreeWidget::WelcomeModeTreeWidget(QWidget *parent) : - QTreeWidget(parent), m_d(new WelcomeModeTreeWidgetPrivate) -{ - m_d->bullet = QIcon(QLatin1String(":/welcome/images/list_bullet_arrow.png")); - connect(this, SIGNAL(itemClicked(QTreeWidgetItem *, int)), - SLOT(slotItemClicked(QTreeWidgetItem *))); - - viewport()->setAutoFillBackground(false); -} - -WelcomeModeTreeWidget::~WelcomeModeTreeWidget() -{ - delete m_d; -} - -QSize WelcomeModeTreeWidget::minimumSizeHint() const -{ - return QSize(); -} - -QSize WelcomeModeTreeWidget::sizeHint() const -{ - return QSize(QTreeWidget::sizeHint().width(), 30 * topLevelItemCount()); -} - -QTreeWidgetItem *WelcomeModeTreeWidget::addItem(const QString &label, const QString &data, const QString &toolTip) -{ - QTreeWidgetItem *item = new QTreeWidgetItem(this); - item->setIcon(0, m_d->bullet); - item->setSizeHint(0, QSize(24, 30)); - QLabel *lbl = new QLabel(label); - lbl->setTextInteractionFlags(Qt::NoTextInteraction); - lbl->setCursor(QCursor(Qt::PointingHandCursor)); - lbl->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - QBoxLayout *lay = new QVBoxLayout; - lay->setContentsMargins(3, 2, 0, 0); - lay->addWidget(lbl); - QWidget *wdg = new QWidget; - wdg->setLayout(lay); - setItemWidget(item, 1, wdg); - item->setData(0, Qt::UserRole, data); - if (!toolTip.isEmpty()) - wdg->setToolTip(toolTip); - return item; - -} - -void WelcomeModeTreeWidget::slotAddNewsItem(const QString &title, const QString &description, const QString &link) -{ - int itemWidth = width()-header()->sectionSize(0); - QFont f = font(); - QString elidedText = QFontMetrics(f).elidedText(description, Qt::ElideRight, itemWidth); - f.setBold(true); - QString elidedTitle = QFontMetrics(f).elidedText(title, Qt::ElideRight, itemWidth); - QString data = QString::fromLatin1("<b>%1</b><br />%2").arg(elidedTitle).arg(elidedText); - addTopLevelItem(addItem(data, link, link)); -} - -void WelcomeModeTreeWidget::slotItemClicked(QTreeWidgetItem *item) -{ - emit activated(item->data(0, Qt::UserRole).toString()); -} - -} diff --git a/libs/utils/welcomemodetreewidget.h b/libs/utils/welcomemodetreewidget.h deleted file mode 100644 index d97cfd0c1ab938d8ecca8c03e6e7e1e75fc2e44b..0000000000000000000000000000000000000000 --- a/libs/utils/welcomemodetreewidget.h +++ /dev/null @@ -1,79 +0,0 @@ -/** - ****************************************************************************** - * - * @file welcomemodetreewidget.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef WELCOMEMODETREEWIDGET_H -#define WELCOMEMODETREEWIDGET_H - -#include "utils_global.h" - -#include <QtGui/QTreeWidget> -#include <QtGui/QLabel> - -namespace Utils { - -struct WelcomeModeTreeWidgetPrivate; -struct WelcomeModeLabelPrivate; - -class QTCREATOR_UTILS_EXPORT WelcomeModeLabel : public QLabel -{ - Q_OBJECT -public: - WelcomeModeLabel(QWidget *parent) : QLabel(parent) {}; - void setStyledText(const QString &text); - WelcomeModeLabelPrivate *m_d; -}; - -class QTCREATOR_UTILS_EXPORT WelcomeModeTreeWidget : public QTreeWidget -{ - Q_OBJECT - -public: - WelcomeModeTreeWidget(QWidget *parent = 0); - ~WelcomeModeTreeWidget(); - QTreeWidgetItem *addItem(const QString &label, const QString &data,const QString &toolTip = QString::null); - -public slots: - void slotAddNewsItem(const QString &title, const QString &description, const QString &link); - -signals: - void activated(const QString &data); - -protected: - virtual QSize minimumSizeHint() const; - virtual QSize sizeHint() const; - -private slots: - void slotItemClicked(QTreeWidgetItem *item); - -private: - WelcomeModeTreeWidgetPrivate *m_d; -}; - -} - -#endif // WELCOMEMODETREEWIDGET_H diff --git a/libs/utils/winutils.cpp b/libs/utils/winutils.cpp deleted file mode 100644 index ae80f26efc3dd12b8acdf50a62b0d6201bf30b87..0000000000000000000000000000000000000000 --- a/libs/utils/winutils.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/** - ****************************************************************************** - * - * @file winutils.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "winutils.h" -#include <windows.h> - -#include <QtCore/QString> -#include <QtCore/QVector> -#include <QtCore/QDebug> -#include <QtCore/QLibrary> -#include <QtCore/QTextStream> - -namespace Utils { - -QTCREATOR_UTILS_EXPORT QString winErrorMessage(unsigned long error) -{ - QString rc = QString::fromLatin1("#%1: ").arg(error); - ushort *lpMsgBuf; - - const int len = FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error, 0, (LPTSTR)&lpMsgBuf, 0, NULL); - if (len) { - rc = QString::fromUtf16(lpMsgBuf, len); - LocalFree(lpMsgBuf); - } else { - rc += QString::fromLatin1("<unknown error>"); - } - return rc; -} - -QTCREATOR_UTILS_EXPORT QString winGetDLLVersion(WinDLLVersionType t, - const QString &name, - QString *errorMessage) -{ - // Resolve required symbols from the version.dll - typedef DWORD (APIENTRY *GetFileVersionInfoSizeProtoType)(LPCTSTR, LPDWORD); - typedef BOOL (APIENTRY *GetFileVersionInfoWProtoType)(LPCWSTR, DWORD, DWORD, LPVOID); - typedef BOOL (APIENTRY *VerQueryValueWProtoType)(const LPVOID, LPWSTR lpSubBlock, LPVOID, PUINT); - - const char *versionDLLC = "version.dll"; - QLibrary versionLib(QLatin1String(versionDLLC), 0); - if (!versionLib.load()) { - *errorMessage = QString::fromLatin1("Unable load %1: %2").arg(QLatin1String(versionDLLC), versionLib.errorString()); - return QString(); - } - // MinGW requires old-style casts - GetFileVersionInfoSizeProtoType getFileVersionInfoSizeW = (GetFileVersionInfoSizeProtoType)(versionLib.resolve("GetFileVersionInfoSizeW")); - GetFileVersionInfoWProtoType getFileVersionInfoW = (GetFileVersionInfoWProtoType)(versionLib.resolve("GetFileVersionInfoW")); - VerQueryValueWProtoType verQueryValueW = (VerQueryValueWProtoType)(versionLib.resolve("VerQueryValueW")); - if (!getFileVersionInfoSizeW || !getFileVersionInfoW || !verQueryValueW) { - *errorMessage = QString::fromLatin1("Unable to resolve all required symbols in %1").arg(QLatin1String(versionDLLC)); - return QString(); - } - - // Now go ahead, read version info resource - DWORD dummy = 0; - const LPCTSTR fileName = reinterpret_cast<LPCTSTR>(name.utf16()); // MinGWsy - const DWORD infoSize = (*getFileVersionInfoSizeW)(fileName, &dummy); - if (infoSize == 0) { - *errorMessage = QString::fromLatin1("Unable to determine the size of the version information of %1: %2").arg(name, winErrorMessage(GetLastError())); - return QString(); - } - QByteArray dataV(infoSize + 1, '\0'); - char *data = dataV.data(); - if (!(*getFileVersionInfoW)(fileName, dummy, infoSize, data)) { - *errorMessage = QString::fromLatin1("Unable to determine the version information of %1: %2").arg(name, winErrorMessage(GetLastError())); - return QString(); - } - VS_FIXEDFILEINFO *versionInfo; - UINT len = 0; - if (!(*verQueryValueW)(data, TEXT("\\"), &versionInfo, &len)) { - *errorMessage = QString::fromLatin1("Unable to determine version string of %1: %2").arg(name, winErrorMessage(GetLastError())); - return QString(); - } - QString rc; - switch (t) { - case WinDLLFileVersion: - QTextStream(&rc) << HIWORD(versionInfo->dwFileVersionMS) << '.' << LOWORD(versionInfo->dwFileVersionMS); - break; - case WinDLLProductVersion: - QTextStream(&rc) << HIWORD(versionInfo->dwProductVersionMS) << '.' << LOWORD(versionInfo->dwProductVersionMS); - break; - } - return rc; -} - -} // namespace Utils diff --git a/libs/utils/winutils.h b/libs/utils/winutils.h deleted file mode 100644 index acd8fe506ee6e499524d5862ff1100441050494e..0000000000000000000000000000000000000000 --- a/libs/utils/winutils.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - ****************************************************************************** - * - * @file winutils.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef WINUTILS_H -#define WINUTILS_H - -#include "utils_global.h" - -QT_BEGIN_NAMESPACE -class QString; -QT_END_NAMESPACE - -namespace Utils { - -// Helper to format a Windows error message, taking the -// code as returned by the GetLastError()-API. -QTCREATOR_UTILS_EXPORT QString winErrorMessage(unsigned long error); - -// Determine a DLL version -enum WinDLLVersionType { WinDLLFileVersion, WinDLLProductVersion }; -QTCREATOR_UTILS_EXPORT QString winGetDLLVersion(WinDLLVersionType t, - const QString &name, - QString *errorMessage); -} // namespace Utils -#endif // WINUTILS_H diff --git a/libs/utils/worldmagmodel.cpp b/libs/utils/worldmagmodel.cpp deleted file mode 100644 index fe969dc0ec7f740892013fb81fbb86f9e416eb86..0000000000000000000000000000000000000000 --- a/libs/utils/worldmagmodel.cpp +++ /dev/null @@ -1,1077 +0,0 @@ -/** - ****************************************************************************** - * - * @file worldmagmodel.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * @brief Utilities to find the location of openpilot GCS files: - * - Plugins Share directory path - * - * @brief Source file for the World Magnetic Model - * This is a port of code available from the US NOAA. - * - * The hard coded coefficients should be valid until 2015. - * - * Updated coeffs from .. - * http://www.ngdc.noaa.gov/geomag/WMM/wmm_ddownload.shtml - * - * NASA C source code .. - * http://www.ngdc.noaa.gov/geomag/WMM/wmm_wdownload.shtml - * - * Major changes include: - * - No geoid model (altitude must be geodetic WGS-84) - * - Floating point calculation (not double precision) - * - Hard coded coefficients for model - * - Elimination of user interface - * - Elimination of dynamic memory allocation - * - * @see The GNU Public License (GPL) Version 3 - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include "worldmagmodel.h" - -#include <stdint.h> -#include <QDebug> -#include <math.h> -#include <qmath.h> - -#define RAD2DEG(rad) ((rad) * (180.0 / M_PI)) -#define DEG2RAD(deg) ((deg) * (M_PI / 180.0)) - -// updated coeffs available from http://www.ngdc.noaa.gov/geomag/WMM/wmm_ddownload.shtml -const double CoeffFile[91][6] = { - {0, 0, 0, 0, 0, 0}, - {1, 0, -29496.6, 0.0, 11.6, 0.0}, - {1, 1, -1586.3, 4944.4, 16.5, -25.9}, - {2, 0, -2396.6, 0.0, -12.1, 0.0}, - {2, 1, 3026.1, -2707.7, -4.4, -22.5}, - {2, 2, 1668.6, -576.1, 1.9, -11.8}, - {3, 0, 1340.1, 0.0, 0.4, 0.0}, - {3, 1, -2326.2, -160.2, -4.1, 7.3}, - {3, 2, 1231.9, 251.9, -2.9, -3.9}, - {3, 3, 634.0, -536.6, -7.7, -2.6}, - {4, 0, 912.6, 0.0, -1.8, 0.0}, - {4, 1, 808.9, 286.4, 2.3, 1.1}, - {4, 2, 166.7, -211.2, -8.7, 2.7}, - {4, 3, -357.1, 164.3, 4.6, 3.9}, - {4, 4, 89.4, -309.1, -2.1, -0.8}, - {5, 0, -230.9, 0.0, -1.0, 0.0}, - {5, 1, 357.2, 44.6, 0.6, 0.4}, - {5, 2, 200.3, 188.9, -1.8, 1.8}, - {5, 3, -141.1, -118.2, -1.0, 1.2}, - {5, 4, -163.0, 0.0, 0.9, 4.0}, - {5, 5, -7.8, 100.9, 1.0, -0.6}, - {6, 0, 72.8, 0.0, -0.2, 0.0}, - {6, 1, 68.6, -20.8, -0.2, -0.2}, - {6, 2, 76.0, 44.1, -0.1, -2.1}, - {6, 3, -141.4, 61.5, 2.0, -0.4}, - {6, 4, -22.8, -66.3, -1.7, -0.6}, - {6, 5, 13.2, 3.1, -0.3, 0.5}, - {6, 6, -77.9, 55.0, 1.7, 0.9}, - {7, 0, 80.5, 0.0, 0.1, 0.0}, - {7, 1, -75.1, -57.9, -0.1, 0.7}, - {7, 2, -4.7, -21.1, -0.6, 0.3}, - {7, 3, 45.3, 6.5, 1.3, -0.1}, - {7, 4, 13.9, 24.9, 0.4, -0.1}, - {7, 5, 10.4, 7.0, 0.3, -0.8}, - {7, 6, 1.7, -27.7, -0.7, -0.3}, - {7, 7, 4.9, -3.3, 0.6, 0.3}, - {8, 0, 24.4, 0.0, -0.1, 0.0}, - {8, 1, 8.1, 11.0, 0.1, -0.1}, - {8, 2, -14.5, -20.0, -0.6, 0.2}, - {8, 3, -5.6, 11.9, 0.2, 0.4}, - {8, 4, -19.3, -17.4, -0.2, 0.4}, - {8, 5, 11.5, 16.7, 0.3, 0.1}, - {8, 6, 10.9, 7.0, 0.3, -0.1}, - {8, 7, -14.1, -10.8, -0.6, 0.4}, - {8, 8, -3.7, 1.7, 0.2, 0.3}, - {9, 0, 5.4, 0.0, 0.0, 0.0}, - {9, 1, 9.4, -20.5, -0.1, 0.0}, - {9, 2, 3.4, 11.5, 0.0, -0.2}, - {9, 3, -5.2, 12.8, 0.3, 0.0}, - {9, 4, 3.1, -7.2, -0.4, -0.1}, - {9, 5, -12.4, -7.4, -0.3, 0.1}, - {9, 6, -0.7, 8.0, 0.1, 0.0}, - {9, 7, 8.4, 2.1, -0.1, -0.2}, - {9, 8, -8.5, -6.1, -0.4, 0.3}, - {9, 9, -10.1, 7.0, -0.2, 0.2}, - {10, 0, -2.0, 0.0, 0.0, 0.0}, - {10, 1, -6.3, 2.8, 0.0, 0.1}, - {10, 2, 0.9, -0.1, -0.1, -0.1}, - {10, 3, -1.1, 4.7, 0.2, 0.0}, - {10, 4, -0.2, 4.4, 0.0, -0.1}, - {10, 5, 2.5, -7.2, -0.1, -0.1}, - {10, 6, -0.3, -1.0, -0.2, 0.0}, - {10, 7, 2.2, -3.9, 0.0, -0.1}, - {10, 8, 3.1, -2.0, -0.1, -0.2}, - {10, 9, -1.0, -2.0, -0.2, 0.0}, - {10, 10, -2.8, -8.3, -0.2, -0.1}, - {11, 0, 3.0, 0.0, 0.0, 0.0}, - {11, 1, -1.5, 0.2, 0.0, 0.0}, - {11, 2, -2.1, 1.7, 0.0, 0.1}, - {11, 3, 1.7, -0.6, 0.1, 0.0}, - {11, 4, -0.5, -1.8, 0.0, 0.1}, - {11, 5, 0.5, 0.9, 0.0, 0.0}, - {11, 6, -0.8, -0.4, 0.0, 0.1}, - {11, 7, 0.4, -2.5, 0.0, 0.0}, - {11, 8, 1.8, -1.3, 0.0, -0.1}, - {11, 9, 0.1, -2.1, 0.0, -0.1}, - {11, 10, 0.7, -1.9, -0.1, 0.0}, - {11, 11, 3.8, -1.8, 0.0, -0.1}, - {12, 0, -2.2, 0.0, 0.0, 0.0}, - {12, 1, -0.2, -0.9, 0.0, 0.0}, - {12, 2, 0.3, 0.3, 0.1, 0.0}, - {12, 3, 1.0, 2.1, 0.1, 0.0}, - {12, 4, -0.6, -2.5, -0.1, 0.0}, - {12, 5, 0.9, 0.5, 0.0, 0.0}, - {12, 6, -0.1, 0.6, 0.0, 0.1}, - {12, 7, 0.5, 0.0, 0.0, 0.0}, - {12, 8, -0.4, 0.1, 0.0, 0.0}, - {12, 9, -0.4, 0.3, 0.0, 0.0}, - {12, 10, 0.2, -0.9, 0.0, 0.0}, - {12, 11, -0.8, -0.2, -0.1, 0.0}, - {12, 12, 0.0, 0.9, 0.1, 0.0} -}; - -namespace Utils { - - WorldMagModel::WorldMagModel() - { - Initialize(); - } - - int WorldMagModel::GetMagVector(double LLA[3], int Month, int Day, int Year, double Be[3]) - { - double Lat = LLA[0]; - double Lon = LLA[1]; - double AltEllipsoid = LLA[2]; - - // *********** - // range check supplied params - - if (Lat < -90) return -1; // error - if (Lat > 90) return -2; // error - - if (Lon < -180) return -3; // error - if (Lon > 180) return -4; // error - - // *********** - - WMMtype_CoordSpherical CoordSpherical; - WMMtype_CoordGeodetic CoordGeodetic; - WMMtype_GeoMagneticElements GeoMagneticElements; - - Initialize(); - - CoordGeodetic.lambda = Lon; - CoordGeodetic.phi = Lat; - CoordGeodetic.HeightAboveEllipsoid = AltEllipsoid; - - // Convert from geodeitic to Spherical Equations: 17-18, WMM Technical report - GeodeticToSpherical(&CoordGeodetic, &CoordSpherical); - - if (DateToYear(Month, Day, Year) < 0) - return -5; // error - - // Compute the geoMagnetic field elements and their time change - if (Geomag(&CoordSpherical, &CoordGeodetic, &GeoMagneticElements) < 0) - return -6; // error - - // set the returned values - Be[0] = GeoMagneticElements.X * 1e-2; - Be[1] = GeoMagneticElements.Y * 1e-2; - Be[2] = GeoMagneticElements.Z * 1e-2; - - // *********** - - return 0; // OK - } - - void WorldMagModel::Initialize() - { // Sets default values for WMM subroutines. - // UPDATES : Ellip and MagneticModel - - // Sets WGS-84 parameters - Ellip.a = 6378.137; // semi-major axis of the ellipsoid in km - Ellip.b = 6356.7523142; // semi-minor axis of the ellipsoid in km - Ellip.fla = 1 / 298.257223563; // flattening - Ellip.eps = sqrt(1 - (Ellip.b * Ellip.b) / (Ellip.a * Ellip.a)); // first eccentricity - Ellip.epssq = (Ellip.eps * Ellip.eps); // first eccentricity squared - Ellip.re = 6371.2; // Earth's radius in km - - // Sets Magnetic Model parameters - MagneticModel.nMax = WMM_MAX_MODEL_DEGREES; - MagneticModel.nMaxSecVar = WMM_MAX_SECULAR_VARIATION_MODEL_DEGREES; - MagneticModel.SecularVariationUsed = 0; - - // Really, Really needs to be read from a file - out of date in 2015 at latest - MagneticModel.EditionDate = 5.7863328170559505e-307; - MagneticModel.epoch = 2010.0; - sprintf(MagneticModel.ModelName, "WMM-2010"); - } - - - int WorldMagModel::Geomag(WMMtype_CoordSpherical *CoordSpherical, WMMtype_CoordGeodetic *CoordGeodetic, WMMtype_GeoMagneticElements *GeoMagneticElements) - /* - The main subroutine that calls a sequence of WMM sub-functions to calculate the magnetic field elements for a single point. - The function expects the model coefficients and point coordinates as input and returns the magnetic field elements and - their rate of change. Though, this subroutine can be called successively to calculate a time series, profile or grid - of magnetic field, these are better achieved by the subroutine WMM_Grid. - - INPUT: Ellip - CoordSpherical - CoordGeodetic - TimedMagneticModel - - OUTPUT : GeoMagneticElements - */ - { - WMMtype_MagneticResults MagneticResultsSph; - WMMtype_MagneticResults MagneticResultsGeo; - WMMtype_MagneticResults MagneticResultsSphVar; - WMMtype_MagneticResults MagneticResultsGeoVar; - WMMtype_LegendreFunction LegendreFunction; - WMMtype_SphericalHarmonicVariables SphVariables; - - // Compute Spherical Harmonic variables - ComputeSphericalHarmonicVariables(CoordSpherical, MagneticModel.nMax, &SphVariables); - - // Compute ALF - if (AssociatedLegendreFunction(CoordSpherical, MagneticModel.nMax, &LegendreFunction) < 0) - return -1; // error - - // Accumulate the spherical harmonic coefficients - Summation(&LegendreFunction, &SphVariables, CoordSpherical, &MagneticResultsSph); - - // Sum the Secular Variation Coefficients - SecVarSummation(&LegendreFunction, &SphVariables, CoordSpherical, &MagneticResultsSphVar); - - // Map the computed Magnetic fields to Geodeitic coordinates - RotateMagneticVector(CoordSpherical, CoordGeodetic, &MagneticResultsSph, &MagneticResultsGeo); - - // Map the secular variation field components to Geodetic coordinates - RotateMagneticVector(CoordSpherical, CoordGeodetic, &MagneticResultsSphVar, &MagneticResultsGeoVar); - - // Calculate the Geomagnetic elements, Equation 18 , WMM Technical report - CalculateGeoMagneticElements(&MagneticResultsGeo, GeoMagneticElements); - - // Calculate the secular variation of each of the Geomagnetic elements - CalculateSecularVariation(&MagneticResultsGeoVar, GeoMagneticElements); - - return 0; // OK - } - - void WorldMagModel::ComputeSphericalHarmonicVariables(WMMtype_CoordSpherical *CoordSpherical, int nMax, WMMtype_SphericalHarmonicVariables *SphVariables) - { - /* Computes Spherical variables - Variables computed are (a/r)^(n+2), cos_m(lamda) and sin_m(lambda) for spherical harmonic - summations. (Equations 10-12 in the WMM Technical Report) - INPUT Ellip data structure with the following elements - float a; semi-major axis of the ellipsoid - float b; semi-minor axis of the ellipsoid - float fla; flattening - float epssq; first eccentricity squared - float eps; first eccentricity - float re; mean radius of ellipsoid - CoordSpherical A data structure with the following elements - float lambda; ( longitude) - float phig; ( geocentric latitude ) - float r; ( distance from the center of the ellipsoid) - nMax integer ( Maxumum degree of spherical harmonic secular model)\ - - OUTPUT SphVariables Pointer to the data structure with the following elements - float RelativeRadiusPower[WMM_MAX_MODEL_DEGREES+1]; [earth_reference_radius_km sph. radius ]^n - float cos_mlambda[WMM_MAX_MODEL_DEGREES+1]; cp(m) - cosine of (mspherical coord. longitude) - float sin_mlambda[WMM_MAX_MODEL_DEGREES+1]; sp(m) - sine of (mspherical coord. longitude) - */ - double cos_lambda = cos(DEG2RAD(CoordSpherical->lambda)); - double sin_lambda = sin(DEG2RAD(CoordSpherical->lambda)); - - /* for n = 0 ... model_order, compute (Radius of Earth / Spherica radius r)^(n+2) - for n 1..nMax-1 (this is much faster than calling pow MAX_N+1 times). */ - - SphVariables->RelativeRadiusPower[0] = (Ellip.re / CoordSpherical->r) * (Ellip.re / CoordSpherical->r); - for (int n = 1; n <= nMax; n++) - SphVariables->RelativeRadiusPower[n] = SphVariables->RelativeRadiusPower[n - 1] * (Ellip.re / CoordSpherical->r); - - /* - Compute cos(m*lambda), sin(m*lambda) for m = 0 ... nMax - cos(a + b) = cos(a)*cos(b) - sin(a)*sin(b) - sin(a + b) = cos(a)*sin(b) + sin(a)*cos(b) - */ - SphVariables->cos_mlambda[0] = 1.0; - SphVariables->sin_mlambda[0] = 0.0; - - SphVariables->cos_mlambda[1] = cos_lambda; - SphVariables->sin_mlambda[1] = sin_lambda; - for (int m = 2; m <= nMax; m++) - { - SphVariables->cos_mlambda[m] = SphVariables->cos_mlambda[m - 1] * cos_lambda - SphVariables->sin_mlambda[m - 1] * sin_lambda; - SphVariables->sin_mlambda[m] = SphVariables->cos_mlambda[m - 1] * sin_lambda + SphVariables->sin_mlambda[m - 1] * cos_lambda; - } - } - - int WorldMagModel::AssociatedLegendreFunction(WMMtype_CoordSpherical *CoordSpherical, int nMax, WMMtype_LegendreFunction *LegendreFunction) - { - /* Computes all of the Schmidt-semi normalized associated Legendre - functions up to degree nMax. If nMax <= 16, function WMM_PcupLow is used. - Otherwise WMM_PcupHigh is called. - INPUT CoordSpherical A data structure with the following elements - float lambda; ( longitude) - float phig; ( geocentric latitude ) - float r; ( distance from the center of the ellipsoid) - nMax integer ( Maxumum degree of spherical harmonic secular model) - LegendreFunction Pointer to data structure with the following elements - float *Pcup; ( pointer to store Legendre Function ) - float *dPcup; ( pointer to store Derivative of Lagendre function ) - - OUTPUT LegendreFunction Calculated Legendre variables in the data structure - */ - - double sin_phi = sin(DEG2RAD(CoordSpherical->phig)); // sin (geocentric latitude) - - if (nMax <= 16 || (1 - fabs(sin_phi)) < 1.0e-10) /* If nMax is less tha 16 or at the poles */ - PcupLow(LegendreFunction->Pcup, LegendreFunction->dPcup, sin_phi, nMax); - else - { - if (PcupHigh(LegendreFunction->Pcup, LegendreFunction->dPcup, sin_phi, nMax) < 0) - return -1; // error - } - - return 0; // OK - } - - void WorldMagModel::Summation( WMMtype_LegendreFunction *LegendreFunction, - WMMtype_SphericalHarmonicVariables *SphVariables, - WMMtype_CoordSpherical *CoordSpherical, - WMMtype_MagneticResults *MagneticResults) - { - /* Computes Geomagnetic Field Elements X, Y and Z in Spherical coordinate system using spherical harmonic summation. - - The vector Magnetic field is given by -grad V, where V is Geomagnetic scalar potential - The gradient in spherical coordinates is given by: - - dV ^ 1 dV ^ 1 dV ^ - grad V = -- r + - -- t + -------- -- p - dr r dt r sin(t) dp - - INPUT : LegendreFunction - MagneticModel - SphVariables - CoordSpherical - OUTPUT : MagneticResults - - Manoj Nair, June, 2009 Manoj.C.Nair@Noaa.Gov - */ - - MagneticResults->Bz = 0.0; - MagneticResults->By = 0.0; - MagneticResults->Bx = 0.0; - - for (int n = 1; n <= MagneticModel.nMax; n++) - { - for (int m = 0; m <= n; m++) - { - int index = (n * (n + 1) / 2 + m); - -/* nMax (n+2) n m m m - Bz = -SUM (a/r) (n+1) SUM [g cos(m p) + h sin(m p)] P (sin(phi)) - n=1 m=0 n n n */ -/* Equation 12 in the WMM Technical report. Derivative with respect to radius.*/ - MagneticResults->Bz -= - SphVariables->RelativeRadiusPower[n] * - (get_main_field_coeff_g(index) * - SphVariables->cos_mlambda[m] + get_main_field_coeff_h(index) * SphVariables->sin_mlambda[m]) - * (double)(n + 1) * LegendreFunction->Pcup[index]; - -/* 1 nMax (n+2) n m m m - By = SUM (a/r) (m) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Equation 11 in the WMM Technical report. Derivative with respect to longitude, divided by radius. */ - MagneticResults->By += - SphVariables->RelativeRadiusPower[n] * - (get_main_field_coeff_g(index) * - SphVariables->sin_mlambda[m] - get_main_field_coeff_h(index) * SphVariables->cos_mlambda[m]) - * (double)(m) * LegendreFunction->Pcup[index]; -/* nMax (n+2) n m m m - Bx = - SUM (a/r) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Equation 10 in the WMM Technical report. Derivative with respect to latitude, divided by radius. */ - - MagneticResults->Bx -= - SphVariables->RelativeRadiusPower[n] * - (get_main_field_coeff_g(index) * - SphVariables->cos_mlambda[m] + get_main_field_coeff_h(index) * SphVariables->sin_mlambda[m]) - * LegendreFunction->dPcup[index]; - - } - } - - double cos_phi = cos(DEG2RAD(CoordSpherical->phig)); - if (fabs(cos_phi) > 1.0e-10) - { - MagneticResults->By = MagneticResults->By / cos_phi; - } - else - { - /* Special calculation for component - By - at Geographic poles. - * If the user wants to avoid using this function, please make sure that - * the latitude is not exactly +/-90. An option is to make use the function - * WMM_CheckGeographicPoles. - */ - SummationSpecial(SphVariables, CoordSpherical, MagneticResults); - } - } - - void WorldMagModel::SecVarSummation( WMMtype_LegendreFunction *LegendreFunction, - WMMtype_SphericalHarmonicVariables *SphVariables, - WMMtype_CoordSpherical *CoordSpherical, - WMMtype_MagneticResults *MagneticResults) - { - /*This Function sums the secular variation coefficients to get the secular variation of the Magnetic vector. - INPUT : LegendreFunction - MagneticModel - SphVariables - CoordSpherical - OUTPUT : MagneticResults - */ - - MagneticModel.SecularVariationUsed = true; - - MagneticResults->Bz = 0.0; - MagneticResults->By = 0.0; - MagneticResults->Bx = 0.0; - - for (int n = 1; n <= MagneticModel.nMaxSecVar; n++) - { - for (int m = 0; m <= n; m++) - { - int index = (n * (n + 1) / 2 + m); - -/* nMax (n+2) n m m m - Bz = -SUM (a/r) (n+1) SUM [g cos(m p) + h sin(m p)] P (sin(phi)) - n=1 m=0 n n n */ -/* Derivative with respect to radius.*/ - MagneticResults->Bz -= - SphVariables->RelativeRadiusPower[n] * - (get_secular_var_coeff_g(index) * - SphVariables->cos_mlambda[m] + get_secular_var_coeff_h(index) * SphVariables->sin_mlambda[m]) - * (double)(n + 1) * LegendreFunction->Pcup[index]; - -/* 1 nMax (n+2) n m m m - By = SUM (a/r) (m) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Derivative with respect to longitude, divided by radius. */ - MagneticResults->By += - SphVariables->RelativeRadiusPower[n] * - (get_secular_var_coeff_g(index) * - SphVariables->sin_mlambda[m] - get_secular_var_coeff_h(index) * SphVariables->cos_mlambda[m]) - * (double)(m) * LegendreFunction->Pcup[index]; -/* nMax (n+2) n m m m - Bx = - SUM (a/r) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Derivative with respect to latitude, divided by radius. */ - - MagneticResults->Bx -= - SphVariables->RelativeRadiusPower[n] * - (get_secular_var_coeff_g(index) * - SphVariables->cos_mlambda[m] + get_secular_var_coeff_h(index) * SphVariables->sin_mlambda[m]) - * LegendreFunction->dPcup[index]; - } - } - - double cos_phi = cos(DEG2RAD(CoordSpherical->phig)); - if (fabs(cos_phi) > 1.0e-10) - { - MagneticResults->By = MagneticResults->By / cos_phi; - } - else - { /* Special calculation for component By at Geographic poles */ - SecVarSummationSpecial(SphVariables, CoordSpherical, MagneticResults); - } - } - - void WorldMagModel::RotateMagneticVector( WMMtype_CoordSpherical *CoordSpherical, - WMMtype_CoordGeodetic *CoordGeodetic, - WMMtype_MagneticResults *MagneticResultsSph, - WMMtype_MagneticResults *MagneticResultsGeo) - { - /* Rotate the Magnetic Vectors to Geodetic Coordinates - Manoj Nair, June, 2009 Manoj.C.Nair@Noaa.Gov - Equation 16, WMM Technical report - - INPUT : CoordSpherical : Data structure WMMtype_CoordSpherical with the following elements - float lambda; ( longitude) - float phig; ( geocentric latitude ) - float r; ( distance from the center of the ellipsoid) - - CoordGeodetic : Data structure WMMtype_CoordGeodetic with the following elements - float lambda; (longitude) - float phi; ( geodetic latitude) - float HeightAboveEllipsoid; (height above the ellipsoid (HaE) ) - float HeightAboveGeoid;(height above the Geoid ) - - MagneticResultsSph : Data structure WMMtype_MagneticResults with the following elements - float Bx; North - float By; East - float Bz; Down - - OUTPUT: MagneticResultsGeo Pointer to the data structure WMMtype_MagneticResults, with the following elements - float Bx; North - float By; East - float Bz; Down - */ - - /* Difference between the spherical and Geodetic latitudes */ - double Psi = DEG2RAD(CoordSpherical->phig - CoordGeodetic->phi); - - /* Rotate spherical field components to the Geodeitic system */ - MagneticResultsGeo->Bz = MagneticResultsSph->Bx * sin(Psi) + MagneticResultsSph->Bz * cos(Psi); - MagneticResultsGeo->Bx = MagneticResultsSph->Bx * cos(Psi) - MagneticResultsSph->Bz * sin(Psi); - MagneticResultsGeo->By = MagneticResultsSph->By; - } - - void WorldMagModel::CalculateGeoMagneticElements(WMMtype_MagneticResults *MagneticResultsGeo, WMMtype_GeoMagneticElements *GeoMagneticElements) - { - /* Calculate all the Geomagnetic elements from X,Y and Z components - INPUT MagneticResultsGeo Pointer to data structure with the following elements - float Bx; ( North ) - float By; ( East ) - float Bz; ( Down ) - OUTPUT GeoMagneticElements Pointer to data structure with the following elements - float Decl; (Angle between the magnetic field vector and true north, positive east) - float Incl; Angle between the magnetic field vector and the horizontal plane, positive down - float F; Magnetic Field Strength - float H; Horizontal Magnetic Field Strength - float X; Northern component of the magnetic field vector - float Y; Eastern component of the magnetic field vector - float Z; Downward component of the magnetic field vector - */ - - GeoMagneticElements->X = MagneticResultsGeo->Bx; - GeoMagneticElements->Y = MagneticResultsGeo->By; - GeoMagneticElements->Z = MagneticResultsGeo->Bz; - - GeoMagneticElements->H = sqrt(MagneticResultsGeo->Bx * MagneticResultsGeo->Bx + MagneticResultsGeo->By * MagneticResultsGeo->By); - GeoMagneticElements->F = sqrt(GeoMagneticElements->H * GeoMagneticElements->H + MagneticResultsGeo->Bz * MagneticResultsGeo->Bz); - GeoMagneticElements->Decl = RAD2DEG(atan2(GeoMagneticElements->Y, GeoMagneticElements->X)); - GeoMagneticElements->Incl = RAD2DEG(atan2(GeoMagneticElements->Z, GeoMagneticElements->H)); - } - - void WorldMagModel::CalculateSecularVariation(WMMtype_MagneticResults *MagneticVariation, WMMtype_GeoMagneticElements *MagneticElements) - { - /* This takes the Magnetic Variation in x, y, and z and uses it to calculate the secular variation of each of the Geomagnetic elements. - INPUT MagneticVariation Data structure with the following elements - float Bx; ( North ) - float By; ( East ) - float Bz; ( Down ) - OUTPUT MagneticElements Pointer to the data structure with the following elements updated - float Decldot; Yearly Rate of change in declination - float Incldot; Yearly Rate of change in inclination - float Fdot; Yearly rate of change in Magnetic field strength - float Hdot; Yearly rate of change in horizontal field strength - float Xdot; Yearly rate of change in the northern component - float Ydot; Yearly rate of change in the eastern component - float Zdot; Yearly rate of change in the downward component - float GVdot;Yearly rate of chnage in grid variation - */ - - MagneticElements->Xdot = MagneticVariation->Bx; - MagneticElements->Ydot = MagneticVariation->By; - MagneticElements->Zdot = MagneticVariation->Bz; - MagneticElements->Hdot = (MagneticElements->X * MagneticElements->Xdot + MagneticElements->Y * MagneticElements->Ydot) / MagneticElements->H; //See equation 19 in the WMM technical report - MagneticElements->Fdot = - (MagneticElements->X * MagneticElements->Xdot + - MagneticElements->Y * MagneticElements->Ydot + MagneticElements->Z * MagneticElements->Zdot) / MagneticElements->F; - MagneticElements->Decldot = - 180.0 / M_PI * (MagneticElements->X * MagneticElements->Ydot - - MagneticElements->Y * MagneticElements->Xdot) / (MagneticElements->H * MagneticElements->H); - MagneticElements->Incldot = - 180.0 / M_PI * (MagneticElements->H * MagneticElements->Zdot - - MagneticElements->Z * MagneticElements->Hdot) / (MagneticElements->F * MagneticElements->F); - MagneticElements->GVdot = MagneticElements->Decldot; - } - - int WorldMagModel::PcupHigh(double *Pcup, double *dPcup, double x, int nMax) - { - /* This function evaluates all of the Schmidt-semi normalized associated Legendre - functions up to degree nMax. The functions are initially scaled by - 10^280 sin^m in order to minimize the effects of underflow at large m - near the poles (see Holmes and Featherstone 2002, J. Geodesy, 76, 279-299). - Note that this function performs the same operation as WMM_PcupLow. - However this function also can be used for high degree (large nMax) models. - - Calling Parameters: - INPUT - nMax: Maximum spherical harmonic degree to compute. - x: cos(colatitude) or sin(latitude). - - OUTPUT - Pcup: A vector of all associated Legendgre polynomials evaluated at - x up to nMax. The lenght must by greater or equal to (nMax+1)*(nMax+2)/2. - dPcup: Derivative of Pcup(x) with respect to latitude - Notes: - - Adopted from the FORTRAN code written by Mark Wieczorek September 25, 2005. - - Manoj Nair, Nov, 2009 Manoj.C.Nair@Noaa.Gov - - Change from the previous version - The prevous version computes the derivatives as - dP(n,m)(x)/dx, where x = sin(latitude) (or cos(colatitude) ). - However, the WMM Geomagnetic routines requires dP(n,m)(x)/dlatitude. - Hence the derivatives are multiplied by sin(latitude). - Removed the options for CS phase and normalizations. - - Note: In geomagnetism, the derivatives of ALF are usually found with - respect to the colatitudes. Here the derivatives are found with respect - to the latitude. The difference is a sign reversal for the derivative of - the Associated Legendre Functions. - - The derivates can't be computed for latitude = |90| degrees. - */ - double f1[WMM_NUMPCUP]; - double f2[WMM_NUMPCUP]; - double PreSqr[WMM_NUMPCUP]; - int m; - - if (fabs(x) == 1.0) - { - // printf("Error in PcupHigh: derivative cannot be calculated at poles\n"); - return -2; - } - - double scalef = 1.0e-280; - - for (int n = 0; n <= 2 * nMax + 1; ++n) - PreSqr[n] = sqrt((double)(n)); - - int k = 2; - - for (int n = 2; n <= nMax; n++) - { - k = k + 1; - f1[k] = (double)(2 * n - 1) / n; - f2[k] = (double)(n - 1) / n; - for (int m = 1; m <= n - 2; m++) - { - k = k + 1; - f1[k] = (double)(2 * n - 1) / PreSqr[n + m] / PreSqr[n - m]; - f2[k] = PreSqr[n - m - 1] * PreSqr[n + m - 1] / PreSqr[n + m] / PreSqr[n - m]; - } - k = k + 2; - } - - /*z = sin (geocentric latitude) */ - double z = sqrt((1.0 - x) * (1.0 + x)); - double pm2 = 1.0; - Pcup[0] = 1.0; - dPcup[0] = 0.0; - if (nMax == 0) - return -3; - double pm1 = x; - Pcup[1] = pm1; - dPcup[1] = z; - k = 1; - - for (int n = 2; n <= nMax; n++) - { - k = k + n; - double plm = f1[k] * x * pm1 - f2[k] * pm2; - Pcup[k] = plm; - dPcup[k] = (double)(n) * (pm1 - x * plm) / z; - pm2 = pm1; - pm1 = plm; - } - - double pmm = PreSqr[2] * scalef; - double rescalem = 1.0 / scalef; - int kstart = 0; - - for (m = 1; m <= nMax - 1; ++m) - { - rescalem = rescalem * z; - - /* Calculate Pcup(m,m) */ - kstart = kstart + m + 1; - pmm = pmm * PreSqr[2 * m + 1] / PreSqr[2 * m]; - Pcup[kstart] = pmm * rescalem / PreSqr[2 * m + 1]; - dPcup[kstart] = -((double)(m) * x * Pcup[kstart] / z); - pm2 = pmm / PreSqr[2 * m + 1]; - /* Calculate Pcup(m+1,m) */ - k = kstart + m + 1; - pm1 = x * PreSqr[2 * m + 1] * pm2; - Pcup[k] = pm1 * rescalem; - dPcup[k] = ((pm2 * rescalem) * PreSqr[2 * m + 1] - x * (double)(m + 1) * Pcup[k]) / z; - /* Calculate Pcup(n,m) */ - for (int n = m + 2; n <= nMax; ++n) - { - k = k + n; - double plm = x * f1[k] * pm1 - f2[k] * pm2; - Pcup[k] = plm * rescalem; - dPcup[k] = (PreSqr[n + m] * PreSqr[n - m] * (pm1 * rescalem) - (double)(n) * x * Pcup[k]) / z; - pm2 = pm1; - pm1 = plm; - } - } - - /* Calculate Pcup(nMax,nMax) */ - rescalem = rescalem * z; - kstart = kstart + m + 1; - pmm = pmm / PreSqr[2 * nMax]; - Pcup[kstart] = pmm * rescalem; - dPcup[kstart] = -(double)(nMax) * x * Pcup[kstart] / z; - - // ********* - - return 0; // OK - } - - void WorldMagModel::PcupLow(double *Pcup, double *dPcup, double x, int nMax) - { - /* This function evaluates all of the Schmidt-semi normalized associated Legendre functions up to degree nMax. - - Calling Parameters: - INPUT - nMax: Maximum spherical harmonic degree to compute. - x: cos(colatitude) or sin(latitude). - - OUTPUT - Pcup: A vector of all associated Legendgre polynomials evaluated at - x up to nMax. - dPcup: Derivative of Pcup(x) with respect to latitude - - Notes: Overflow may occur if nMax > 20 , especially for high-latitudes. - Use WMM_PcupHigh for large nMax. - - Writted by Manoj Nair, June, 2009 . Manoj.C.Nair@Noaa.Gov. - - Note: In geomagnetism, the derivatives of ALF are usually found with - respect to the colatitudes. Here the derivatives are found with respect - to the latitude. The difference is a sign reversal for the derivative of - the Associated Legendre Functions. - */ - - double schmidtQuasiNorm[WMM_NUMPCUP]; - - Pcup[0] = 1.0; - dPcup[0] = 0.0; - - /*sin (geocentric latitude) - sin_phi */ - double z = sqrt((1.0 - x) * (1.0 + x)); - - /* First, Compute the Gauss-normalized associated Legendre functions */ - for (int n = 1; n <= nMax; n++) - { - for (int m = 0; m <= n; m++) - { - int index = (n * (n + 1) / 2 + m); - if (n == m) - { - int index1 = (n - 1) * n / 2 + m - 1; - Pcup[index] = z * Pcup[index1]; - dPcup[index] = z * dPcup[index1] + x * Pcup[index1]; - } - else - if (n == 1 && m == 0) - { - int index1 = (n - 1) * n / 2 + m; - Pcup[index] = x * Pcup[index1]; - dPcup[index] = x * dPcup[index1] - z * Pcup[index1]; - } - else - if (n > 1 && n != m) - { - int index1 = (n - 2) * (n - 1) / 2 + m; - int index2 = (n - 1) * n / 2 + m; - if (m > n - 2) - { - Pcup[index] = x * Pcup[index2]; - dPcup[index] = x * dPcup[index2] - z * Pcup[index2]; - } - else - { - double k = (double)(((n - 1) * (n - 1)) - (m * m)) / (double)((2 * n - 1) * (2 * n - 3)); - Pcup[index] = x * Pcup[index2] - k * Pcup[index1]; - dPcup[index] = x * dPcup[index2] - z * Pcup[index2] - k * dPcup[index1]; - } - } - } - } - - /*Compute the ration between the Gauss-normalized associated Legendre - functions and the Schmidt quasi-normalized version. This is equivalent to - sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)! */ - - schmidtQuasiNorm[0] = 1.0; - for (int n = 1; n <= nMax; n++) - { - int index = (n * (n + 1) / 2); - int index1 = (n - 1) * n / 2; - /* for m = 0 */ - schmidtQuasiNorm[index] = schmidtQuasiNorm[index1] * (double)(2 * n - 1) / (double)n; - - for (int m = 1; m <= n; m++) - { - index = (n * (n + 1) / 2 + m); - index1 = (n * (n + 1) / 2 + m - 1); - schmidtQuasiNorm[index] = schmidtQuasiNorm[index1] * sqrt((double)((n - m + 1) * (m == 1 ? 2 : 1)) / (double)(n + m)); - } - } - - /* Converts the Gauss-normalized associated Legendre - functions to the Schmidt quasi-normalized version using pre-computed - relation stored in the variable schmidtQuasiNorm */ - - for (int n = 1; n <= nMax; n++) - { - for (int m = 0; m <= n; m++) - { - int index = (n * (n + 1) / 2 + m); - Pcup[index] = Pcup[index] * schmidtQuasiNorm[index]; - dPcup[index] = -dPcup[index] * schmidtQuasiNorm[index]; - /* The sign is changed since the new WMM routines use derivative with respect to latitude insted of co-latitude */ - } - } - } - - void WorldMagModel::SummationSpecial(WMMtype_SphericalHarmonicVariables *SphVariables, WMMtype_CoordSpherical *CoordSpherical, WMMtype_MagneticResults *MagneticResults) - { - /* Special calculation for the component By at Geographic poles. - Manoj Nair, June, 2009 manoj.c.nair@noaa.gov - INPUT: MagneticModel - SphVariables - CoordSpherical - OUTPUT: MagneticResults - CALLS : none - See Section 1.4, "SINGULARITIES AT THE GEOGRAPHIC POLES", WMM Technical report - */ - - double PcupS[WMM_NUMPCUPS]; - - PcupS[0] = 1; - double schmidtQuasiNorm1 = 1.0; - - MagneticResults->By = 0.0; - double sin_phi = sin(DEG2RAD(CoordSpherical->phig)); - - for (int n = 1; n <= MagneticModel.nMax; n++) - { - /*Compute the ration between the Gauss-normalized associated Legendre - functions and the Schmidt quasi-normalized version. This is equivalent to - sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)! */ - - int index = (n * (n + 1) / 2 + 1); - double schmidtQuasiNorm2 = schmidtQuasiNorm1 * (double)(2 * n - 1) / (double)n; - double schmidtQuasiNorm3 = schmidtQuasiNorm2 * sqrt((double)(n * 2) / (double)(n + 1)); - schmidtQuasiNorm1 = schmidtQuasiNorm2; - if (n == 1) - { - PcupS[n] = PcupS[n - 1]; - } - else - { - double k = (double)(((n - 1) * (n - 1)) - 1) / (double)((2 * n - 1) * (2 * n - 3)); - PcupS[n] = sin_phi * PcupS[n - 1] - k * PcupS[n - 2]; - } - -/* 1 nMax (n+2) n m m m - By = SUM (a/r) (m) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Equation 11 in the WMM Technical report. Derivative with respect to longitude, divided by radius. */ - - MagneticResults->By += - SphVariables->RelativeRadiusPower[n] * - (get_main_field_coeff_g(index) * - SphVariables->sin_mlambda[1] - get_main_field_coeff_h(index) * SphVariables->cos_mlambda[1]) - * PcupS[n] * schmidtQuasiNorm3; - } - } - - void WorldMagModel::SecVarSummationSpecial(WMMtype_SphericalHarmonicVariables *SphVariables, WMMtype_CoordSpherical *CoordSpherical, WMMtype_MagneticResults *MagneticResults) - { - /*Special calculation for the secular variation summation at the poles. - - INPUT: MagneticModel - SphVariables - CoordSpherical - OUTPUT: MagneticResults - */ - - double PcupS[WMM_NUMPCUPS]; - - PcupS[0] = 1; - double schmidtQuasiNorm1 = 1.0; - - MagneticResults->By = 0.0; - double sin_phi = sin(DEG2RAD(CoordSpherical->phig)); - - for (int n = 1; n <= MagneticModel.nMaxSecVar; n++) - { - int index = (n * (n + 1) / 2 + 1); - double schmidtQuasiNorm2 = schmidtQuasiNorm1 * (double)(2 * n - 1) / (double)n; - double schmidtQuasiNorm3 = schmidtQuasiNorm2 * sqrt((double)(n * 2) / (double)(n + 1)); - schmidtQuasiNorm1 = schmidtQuasiNorm2; - if (n == 1) - { - PcupS[n] = PcupS[n - 1]; - } - else - { - double k = (double)(((n - 1) * (n - 1)) - 1) / (double)((2 * n - 1) * (2 * n - 3)); - PcupS[n] = sin_phi * PcupS[n - 1] - k * PcupS[n - 2]; - } - -/* 1 nMax (n+2) n m m m - By = SUM (a/r) (m) SUM [g cos(m p) + h sin(m p)] dP (sin(phi)) - n=1 m=0 n n n */ -/* Derivative with respect to longitude, divided by radius. */ - - MagneticResults->By += - SphVariables->RelativeRadiusPower[n] * - (get_secular_var_coeff_g(index) * - SphVariables->sin_mlambda[1] - get_secular_var_coeff_h(index) * SphVariables->cos_mlambda[1]) - * PcupS[n] * schmidtQuasiNorm3; - } - } - - // brief Comput the MainFieldCoeffH accounting for the date - double WorldMagModel::get_main_field_coeff_g(int index) - { - if (index >= WMM_NUMTERMS) - return 0; - - double coeff = CoeffFile[index][2]; - - int a = MagneticModel.nMaxSecVar; - int b = (a * (a + 1) / 2 + a); - for (int n = 1; n <= MagneticModel.nMax; n++) - { - for (int m = 0; m <= n; m++) - { - int sum_index = (n * (n + 1) / 2 + m); - - /* Hacky for now, will solve for which conditions need summing analytically */ - if (sum_index != index) - continue; - - if (index <= b) - coeff += (decimal_date - MagneticModel.epoch) * get_secular_var_coeff_g(sum_index); - } - } - - return coeff; - } - - double WorldMagModel::get_main_field_coeff_h(int index) - { - if (index >= WMM_NUMTERMS) - return 0; - - double coeff = CoeffFile[index][3]; - - int a = MagneticModel.nMaxSecVar; - int b = (a * (a + 1) / 2 + a); - for (int n = 1; n <= MagneticModel.nMax; n++) - { - for (int m = 0; m <= n; m++) - { - int sum_index = (n * (n + 1) / 2 + m); - - /* Hacky for now, will solve for which conditions need summing analytically */ - if (sum_index != index) - continue; - - if (index <= b) - coeff += (decimal_date - MagneticModel.epoch) * get_secular_var_coeff_h(sum_index); - } - } - - return coeff; - } - - double WorldMagModel::get_secular_var_coeff_g(int index) - { - if (index >= WMM_NUMTERMS) - return 0; - - return CoeffFile[index][4]; - } - - double WorldMagModel::get_secular_var_coeff_h(int index) - { - if (index >= WMM_NUMTERMS) - return 0; - - return CoeffFile[index][5]; - } - - int WorldMagModel::DateToYear(int month, int day, int year) - { - // Converts a given calendar date into a decimal year - - int temp = 0; // Total number of days - int MonthDays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - int ExtraDay = 0; - - if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) - ExtraDay = 1; - MonthDays[2] += ExtraDay; - - /******************Validation********************************/ - - if (month <= 0 || month > 12) - return -1; // error - - if (day <= 0 || day > MonthDays[month]) - return -2; // error - - /****************Calculation of t***************************/ - for (int i = 1; i <= month; i++) - temp += MonthDays[i - 1]; - temp += day; - - decimal_date = year + (temp - 1) / (365.0 + ExtraDay); - - return 0; // OK - } - - void WorldMagModel::GeodeticToSpherical(WMMtype_CoordGeodetic *CoordGeodetic, WMMtype_CoordSpherical *CoordSpherical) - { - // Converts Geodetic coordinates to Spherical coordinates - // Convert geodetic coordinates, (defined by the WGS-84 - // reference ellipsoid), to Earth Centered Earth Fixed Cartesian - // coordinates, and then to spherical coordinates. - - double CosLat = cos(DEG2RAD(CoordGeodetic->phi)); - double SinLat = sin(DEG2RAD(CoordGeodetic->phi)); - - // compute the local radius of curvature on the WGS-84 reference ellipsoid - double rc = Ellip.a / sqrt(1.0 - Ellip.epssq * SinLat * SinLat); - - // compute ECEF Cartesian coordinates of specified point (for longitude=0) - double xp = (rc + CoordGeodetic->HeightAboveEllipsoid) * CosLat; - double zp = (rc * (1.0 - Ellip.epssq) + CoordGeodetic->HeightAboveEllipsoid) * SinLat; - - // compute spherical radius and angle lambda and phi of specified point - CoordSpherical->r = sqrt(xp * xp + zp * zp); - CoordSpherical->phig = RAD2DEG(asin(zp / CoordSpherical->r)); // geocentric latitude - CoordSpherical->lambda = CoordGeodetic->lambda; // longitude - } - -} diff --git a/libs/utils/worldmagmodel.h b/libs/utils/worldmagmodel.h deleted file mode 100644 index 2d9ca2840fee89a168ece15df1fdd54dd8f498c4..0000000000000000000000000000000000000000 --- a/libs/utils/worldmagmodel.h +++ /dev/null @@ -1,180 +0,0 @@ -/** - ****************************************************************************** - * - * @file worldmagmodel.h - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @brief - * @see The GNU Public License (GPL) Version 3 - * @defgroup - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#ifndef WORLDMAGMODEL_H -#define WORLDMAGMODEL_H - -#include "utils_global.h" - -// ****************************** -// internal structure definitions - -#define WMM_MAX_MODEL_DEGREES 12 -#define WMM_MAX_SECULAR_VARIATION_MODEL_DEGREES 12 -#define WMM_NUMTERMS 91 // ((WMM_MAX_MODEL_DEGREES + 1) * (WMM_MAX_MODEL_DEGREES + 2) / 2); -#define WMM_NUMPCUP 92 // NUMTERMS + 1 -#define WMM_NUMPCUPS 13 // WMM_MAX_MODEL_DEGREES + 1 - -typedef struct -{ - double EditionDate; - double epoch; //Base time of Geomagnetic model epoch (yrs) - char ModelName[20]; -// double Main_Field_Coeff_G[WMM_NUMTERMS]; // C - Gauss coefficients of main geomagnetic model (nT) -// double Main_Field_Coeff_H[WMM_NUMTERMS]; // C - Gauss coefficients of main geomagnetic model (nT) -// double Secular_Var_Coeff_G[WMM_NUMTERMS]; // CD - Gauss coefficients of secular geomagnetic model (nT/yr) -// double Secular_Var_Coeff_H[WMM_NUMTERMS]; // CD - Gauss coefficients of secular geomagnetic model (nT/yr) - int nMax; // Maximum degree of spherical harmonic model - int nMaxSecVar; // Maxumum degree of spherical harmonic secular model - int SecularVariationUsed; // Whether or not the magnetic secular variation vector will be needed by program -} WMMtype_MagneticModel; - -typedef struct -{ - double a; // semi-major axis of the ellipsoid - double b; // semi-minor axis of the ellipsoid - double fla; // flattening - double epssq; // first eccentricity squared - double eps; // first eccentricity - double re; // mean radius of ellipsoid -} WMMtype_Ellipsoid; - -typedef struct -{ - double lambda; // longitude - double phi; // geodetic latitude - double HeightAboveEllipsoid; // height above the ellipsoid (HaE) -} WMMtype_CoordGeodetic; - -typedef struct -{ - double lambda; // longitude - double phig; // geocentric latitude - double r; // distance from the center of the ellipsoid -} WMMtype_CoordSpherical; - -typedef struct -{ - int Year; - int Month; - int Day; - double DecimalYear; -} WMMtype_Date; - -typedef struct -{ - double Pcup[WMM_NUMPCUP]; // Legendre Function - double dPcup[WMM_NUMPCUP]; // Derivative of Lagendre fn -} WMMtype_LegendreFunction; - -typedef struct -{ - double Bx; // North - double By; // East - double Bz; // Down -} WMMtype_MagneticResults; - -typedef struct -{ - double RelativeRadiusPower[WMM_MAX_MODEL_DEGREES + 1]; // [earth_reference_radius_km / sph. radius ]^n - double cos_mlambda[WMM_MAX_MODEL_DEGREES + 1]; // cp(m) - cosine of (m*spherical coord. longitude - double sin_mlambda[WMM_MAX_MODEL_DEGREES + 1]; // sp(m) - sine of (m*spherical coord. longitude) -} WMMtype_SphericalHarmonicVariables; - -typedef struct -{ - double Decl; /*1. Angle between the magnetic field vector and true north, positive east */ - double Incl; /*2. Angle between the magnetic field vector and the horizontal plane, positive down */ - double F; /*3. Magnetic Field Strength */ - double H; /*4. Horizontal Magnetic Field Strength */ - double X; /*5. Northern component of the magnetic field vector */ - double Y; /*6. Eastern component of the magnetic field vector */ - double Z; /*7. Downward component of the magnetic field vector */ - double GV; /*8. The Grid Variation */ - double Decldot; /*9. Yearly Rate of change in declination */ - double Incldot; /*10. Yearly Rate of change in inclination */ - double Fdot; /*11. Yearly rate of change in Magnetic field strength */ - double Hdot; /*12. Yearly rate of change in horizontal field strength */ - double Xdot; /*13. Yearly rate of change in the northern component */ - double Ydot; /*14. Yearly rate of change in the eastern component */ - double Zdot; /*15. Yearly rate of change in the downward component */ - double GVdot; /*16. Yearly rate of chnage in grid variation */ -} WMMtype_GeoMagneticElements; - -// ****************************** - -namespace Utils { - - class QTCREATOR_UTILS_EXPORT WorldMagModel - { - public: - WorldMagModel(); - - int GetMagVector(double LLA[3], int Month, int Day, int Year, double Be[3]); - - private: - WMMtype_Ellipsoid Ellip; - WMMtype_MagneticModel MagneticModel; - - double decimal_date; - - void Initialize(); - int Geomag(WMMtype_CoordSpherical *CoordSpherical, WMMtype_CoordGeodetic *CoordGeodetic, WMMtype_GeoMagneticElements *GeoMagneticElements); - void ComputeSphericalHarmonicVariables(WMMtype_CoordSpherical *CoordSpherical, int nMax, WMMtype_SphericalHarmonicVariables *SphVariables); - int AssociatedLegendreFunction(WMMtype_CoordSpherical *CoordSpherical, int nMax, WMMtype_LegendreFunction *LegendreFunction); - void Summation( WMMtype_LegendreFunction *LegendreFunction, - WMMtype_SphericalHarmonicVariables *SphVariables, - WMMtype_CoordSpherical *CoordSpherical, - WMMtype_MagneticResults *MagneticResults); - void SecVarSummation( WMMtype_LegendreFunction *LegendreFunction, - WMMtype_SphericalHarmonicVariables *SphVariables, - WMMtype_CoordSpherical *CoordSpherical, - WMMtype_MagneticResults *MagneticResults); - void RotateMagneticVector( WMMtype_CoordSpherical *CoordSpherical, - WMMtype_CoordGeodetic *CoordGeodetic, - WMMtype_MagneticResults *MagneticResultsSph, - WMMtype_MagneticResults *MagneticResultsGeo); - void CalculateGeoMagneticElements(WMMtype_MagneticResults *MagneticResultsGeo, WMMtype_GeoMagneticElements *GeoMagneticElements); - void CalculateSecularVariation(WMMtype_MagneticResults *MagneticVariation, WMMtype_GeoMagneticElements *MagneticElements); - int PcupHigh(double *Pcup, double *dPcup, double x, int nMax); - void PcupLow(double *Pcup, double *dPcup, double x, int nMax); - void SummationSpecial(WMMtype_SphericalHarmonicVariables *SphVariables, WMMtype_CoordSpherical *CoordSpherical, WMMtype_MagneticResults *MagneticResults); - void SecVarSummationSpecial(WMMtype_SphericalHarmonicVariables *SphVariables, WMMtype_CoordSpherical *CoordSpherical, WMMtype_MagneticResults *MagneticResults); - double get_main_field_coeff_g(int index); - double get_main_field_coeff_h(int index); - double get_secular_var_coeff_g(int index); - double get_secular_var_coeff_h(int index); - int DateToYear(int month, int day, int year); - void GeodeticToSpherical(WMMtype_CoordGeodetic *CoordGeodetic, WMMtype_CoordSpherical *CoordSpherical); - }; - -} - -// ****************************** - -#endif diff --git a/libs/utils/xmlconfig.cpp b/libs/utils/xmlconfig.cpp deleted file mode 100644 index 72c5c92ec2b7711f470115eddfc1ee6c9ad3039e..0000000000000000000000000000000000000000 --- a/libs/utils/xmlconfig.cpp +++ /dev/null @@ -1,333 +0,0 @@ -/** - ****************************************************************************** - * - * @file xmlconfig.cpp - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009. - * @see The GNU Public License (GPL) Version 3 - * @brief Widget for Import/Export Plugin - * @addtogroup GCSPlugins GCS Plugins - * @{ - * @addtogroup importexportplugin - * @{ - * - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -/* Nokia Corporation */ -#include "xmlconfig.h" - -#include <QtDebug> -#include <QStringList> -#include <QRegExp> - -#include <QVariant> -#include <QRect> -#include <QSize> -#include <QPoint> -#include <QtCore/QUrl> - -#define NUM_PREFIX "arr_" - -QString XmlConfig::rootName = "gcs"; - -const QSettings::Format XmlConfig::XmlSettingsFormat = - QSettings::registerFormat("xml", XmlConfig::readXmlFile, XmlConfig::writeXmlFile); - - -bool XmlConfig::readXmlFile(QIODevice &device, QSettings::SettingsMap &map) -{ - QDomDocument domDoc; - QDomElement root; - QString errorStr; - int errorLine; - int errorColumn; - - if (!domDoc.setContent(&device, true, &errorStr, &errorLine, - &errorColumn)) { - QString err = QString(tr("GCS config")) + - tr("Parse error at line %1, column %2:\n%3") - .arg(errorLine) - .arg(errorColumn) - .arg(errorStr); - qFatal("%s", err.toLatin1().data()); - return false; - } - root = domDoc.documentElement(); - handleNode(&root, map); - - return true; -} - -void XmlConfig::handleNode(QDomElement* node, QSettings::SettingsMap &map, QString path) -{ - if ( !node ){ - return; - } - // qDebug() << "XmlConfig::handleNode start"; - - QString nodeName = node->nodeName(); - // For arrays, QT will use simple numbers as keys, which is not a valid element in XML. - // Therefore we prefixed these. - if ( nodeName.startsWith(NUM_PREFIX) ){ - nodeName.replace(NUM_PREFIX, ""); - } - // Xml tags are restrictive with allowed characters, - // so we urlencode and replace % with __PCT__ on file - nodeName = nodeName.replace("__PCT__", "%"); - nodeName = QUrl::fromPercentEncoding(nodeName.toAscii()); - - if ( nodeName == XmlConfig::rootName ) - ; - else if ( path == "" ) - path = nodeName; - else - path += "/" + nodeName; - -// qDebug() << "Node: " << ": " << path << " Children: " << node->childNodes().length(); - for ( uint i = 0; i < node->childNodes().length(); ++i ){ - QDomNode child = node->childNodes().item(i); - if ( child.isElement() ){ - handleNode( static_cast<QDomElement*>(&child), map, path); - } - else if ( child.isText() ){ -// qDebug() << "Key: " << path << " Value:" << node->text(); - map.insert(path, stringToVariant(node->text())); - } - else{ - qDebug() << "Child not Element or text!" << child.nodeType(); - } - } -// qDebug() << "XmlConfig::handleNode end"; -} - -bool XmlConfig::writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map) -{ - QDomDocument outDocument; -// qDebug() << "writeXmlFile start"; - outDocument.appendChild( outDocument.createElement(XmlConfig::rootName)); - QMapIterator<QString, QVariant> iter(map); - while (iter.hasNext()) { - iter.next(); -// qDebug() << "Entry: " << iter.key() << ": " << iter.value().toString() << endl; - QDomNode node = outDocument.firstChild(); - foreach ( QString elem, iter.key().split('/')){ - if ( elem == "" ){ - continue; - } - // Xml tags are restrictive with allowed characters, - // so we urlencode and replace % with __PCT__ on file - elem = QString(QUrl::toPercentEncoding(elem)); - elem = elem.replace("%", "__PCT__"); - // For arrays, QT will use simple numbers as keys, which is not a valid element in XML. - // Therefore we prefixed these. - if ( elem.startsWith(NUM_PREFIX) ){ - qWarning() << "ERROR: Settings must not start with " << NUM_PREFIX - << " in: " + iter.key(); - } - if ( QRegExp("[0-9]").exactMatch(elem.left(1)) ){ - elem.prepend(NUM_PREFIX); - } - if ( node.firstChildElement(elem).isNull() ){ - node.appendChild(outDocument.createElement(elem)); - } - node = node.firstChildElement(elem); - } - node.appendChild(outDocument.createTextNode(variantToString(iter.value()))); - } - device.write(outDocument.toByteArray(2).constData()); -// qDebug() << "Dokument:\n" << outDocument.toByteArray(2).constData(); -// qDebug() << "writeXmlFile end"; - return true; -} - - -QSettings::SettingsMap XmlConfig::settingsToMap(QSettings& qs){ - qDebug() << "settingsToMap:---------------"; - QSettings::SettingsMap map; - QStringList keys = qs.allKeys(); - foreach (QString key, keys) { - QVariant val = qs.value(key); - qDebug() << key << val.toString(); - map.insert(key, val); - } - qDebug() << "settingsToMap End --------"; - return map; -} - -QString XmlConfig::variantToString(const QVariant &v) -{ - QString result; - - switch (v.type()) { - case QVariant::Invalid: - result = QLatin1String("@Invalid()"); - break; - - case QVariant::ByteArray: { - QByteArray a = v.toByteArray().toBase64(); - result = QLatin1String("@ByteArray("); - result += QString::fromLatin1(a.constData(), a.size()); - result += QLatin1Char(')'); - break; - } - - case QVariant::String: - case QVariant::LongLong: - case QVariant::ULongLong: - case QVariant::Int: - case QVariant::UInt: - case QVariant::Bool: - case QVariant::Double: - case QVariant::KeySequence: - case QVariant::Color: { - result = v.toString(); - if (result.startsWith(QLatin1Char('@'))) - result.prepend(QLatin1Char('@')); - break; - } -#ifndef QT_NO_GEOM_VARIANT - case QVariant::Rect: { - QRect r = qvariant_cast<QRect>(v); - result += QLatin1String("@Rect("); - result += QString::number(r.x()); - result += QLatin1Char(' '); - result += QString::number(r.y()); - result += QLatin1Char(' '); - result += QString::number(r.width()); - result += QLatin1Char(' '); - result += QString::number(r.height()); - result += QLatin1Char(')'); - break; - } - case QVariant::Size: { - QSize s = qvariant_cast<QSize>(v); - result += QLatin1String("@Size("); - result += QString::number(s.width()); - result += QLatin1Char(' '); - result += QString::number(s.height()); - result += QLatin1Char(')'); - break; - } - case QVariant::Point: { - QPoint p = qvariant_cast<QPoint>(v); - result += QLatin1String("@Point("); - result += QString::number(p.x()); - result += QLatin1Char(' '); - result += QString::number(p.y()); - result += QLatin1Char(')'); - break; - } -#endif // !QT_NO_GEOM_VARIANT - - default: { -#ifndef QT_NO_DATASTREAM - QByteArray a; - { - QDataStream s(&a, QIODevice::WriteOnly); - s.setVersion(QDataStream::Qt_4_0); - s << v; - } - - result = QLatin1String("@Variant("); - result += QString::fromLatin1(a.toBase64().constData()); - result += QLatin1Char(')'); - // These were being much too noisy!! - //qDebug() << "Variant Type: " << v.type(); - //qDebug()<< "Variant: " << result; -#else - Q_ASSERT(!"QSettings: Cannot save custom types without QDataStream support"); -#endif - break; - } -} - -return result; -} - -QVariant XmlConfig::stringToVariant(const QString &s) -{ - if (s.startsWith(QLatin1Char('@'))) { - if (s.endsWith(QLatin1Char(')'))) { - if (s.startsWith(QLatin1String("@ByteArray("))) { - return QVariant(QByteArray::fromBase64(s.toLatin1().mid(11, s.size() - 12))); - } else if (s.startsWith(QLatin1String("@Variant("))) { -#ifndef QT_NO_DATASTREAM - QByteArray a(QByteArray::fromBase64(s.toLatin1().mid(9))); - QDataStream stream(&a, QIODevice::ReadOnly); - stream.setVersion(QDataStream::Qt_4_0); - QVariant result; - stream >> result; - return result; -#else - Q_ASSERT(!"QSettings: Cannot load custom types without QDataStream support"); -#endif -#ifndef QT_NO_GEOM_VARIANT - } else if (s.startsWith(QLatin1String("@Rect("))) { - QStringList args = splitArgs(s, 5); - if (args.size() == 4) - return QVariant(QRect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt())); - } else if (s.startsWith(QLatin1String("@Size("))) { - QStringList args = splitArgs(s, 5); - if (args.size() == 2) - return QVariant(QSize(args[0].toInt(), args[1].toInt())); - } else if (s.startsWith(QLatin1String("@Point("))) { - QStringList args = splitArgs(s, 6); - if (args.size() == 2) - return QVariant(QPoint(args[0].toInt(), args[1].toInt())); -#endif - } else if (s == QLatin1String("@Invalid()")) { - return QVariant(); - } - - } - if (s.startsWith(QLatin1String("@@"))) - return QVariant(s.mid(1)); - } - - return QVariant(s); -} - -QStringList XmlConfig::splitArgs(const QString &s, int idx) -{ - int l = s.length(); - Q_ASSERT(l > 0); - Q_ASSERT(s.at(idx) == QLatin1Char('(')); - Q_ASSERT(s.at(l - 1) == QLatin1Char(')')); - - QStringList result; - QString item; - - for (++idx; idx < l; ++idx) { - QChar c = s.at(idx); - if (c == QLatin1Char(')')) { - Q_ASSERT(idx == l - 1); - result.append(item); - } else if (c == QLatin1Char(' ')) { - result.append(item); - item.clear(); - } else { - item.append(c); - } - } - - return result; -} - -/** - * @} - * @} - */ diff --git a/libs/utils/xmlconfig.h b/libs/utils/xmlconfig.h deleted file mode 100644 index 447b2b6d489843d3e5e113fc7024a36b2adf15b9..0000000000000000000000000000000000000000 --- a/libs/utils/xmlconfig.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - ****************************************************************************** - * @file - * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. - * @see The GNU Public License (GPL) Version 3 - * @addtogroup GCSPlugins GCS Plugins - * @{ - * @addtogroup importexportplugin - * @{ - *****************************************************************************/ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -#ifndef XMLCONFIG_H -#define XMLCONFIG_H - -#if defined(QTCREATOR_UTILS_LIB) -# define XMLCONFIG_EXPORT Q_DECL_EXPORT -#else -# define XMLCONFIG_EXPORT Q_DECL_IMPORT -#endif - -#include <QtCore/qglobal.h> -#include <QSettings> -#include <QDomElement> -#include <QObject> - -class XMLCONFIG_EXPORT XmlConfig : QObject -{ - -public: - static const QSettings::Format XmlSettingsFormat; - - static bool readXmlFile(QIODevice &device, QSettings::SettingsMap &map); - static bool writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map); - -private: - static QString rootName; - - static void handleNode(QDomElement* node, QSettings::SettingsMap &map, QString path = ""); - static QSettings::SettingsMap settingsToMap(QSettings& qs); - static QString variantToString(const QVariant &v); - static QVariant stringToVariant(const QString &s); - static QStringList splitArgs(const QString &s, int idx); -}; - -#endif // XMLCONFIG_H -/** - * @} - * @} - */