1
0
mirror of https://bitbucket.org/librepilot/librepilot.git synced 2025-01-18 03:52:11 +01:00

OP-232 gcs configuration: First step to configure all plugins in a standard way

git-svn-id: svn://svn.openpilot.org/OpenPilot/trunk@2632 ebee16cc-31ac-478f-84a7-5cbb03baadba
This commit is contained in:
erhard 2011-01-30 23:22:51 +00:00 committed by erhard
parent b5426e09d0
commit 311bcdd492
14 changed files with 3751 additions and 3591 deletions

View File

@ -1,198 +1,207 @@
/**
******************************************************************************
*
* @file coreimpl.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "coreimpl.h"
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
namespace Core {
namespace Internal {
// The Core Singleton
static CoreImpl *m_instance = 0;
} // namespace Internal
} // namespace Core
using namespace Core;
using namespace Core::Internal;
ICore* ICore::instance()
{
return m_instance;
}
CoreImpl::CoreImpl(MainWindow *mainwindow)
{
m_instance = this;
m_mainwindow = mainwindow;
}
bool CoreImpl::showOptionsDialog(const QString &group, const QString &page, QWidget *parent)
{
return m_mainwindow->showOptionsDialog(group, page, parent);
}
bool CoreImpl::showWarningWithOptions(const QString &title, const QString &text,
const QString &details,
const QString &settingsCategory,
const QString &settingsId,
QWidget *parent)
{
return m_mainwindow->showWarningWithOptions(title, text,
details, settingsCategory,
settingsId, parent);
}
ActionManager *CoreImpl::actionManager() const
{
return m_mainwindow->actionManager();
}
UniqueIDManager *CoreImpl::uniqueIDManager() const
{
return m_mainwindow->uniqueIDManager();
}
MessageManager *CoreImpl::messageManager() const
{
return m_mainwindow->messageManager();
}
ConnectionManager *CoreImpl::connectionManager() const
{
return m_mainwindow->connectionManager();
}
UAVGadgetInstanceManager *CoreImpl::uavGadgetInstanceManager() const
{
return m_mainwindow->uavGadgetInstanceManager();
}
VariableManager *CoreImpl::variableManager() const
{
return m_mainwindow->variableManager();
}
ThreadManager *CoreImpl::threadManager() const
{
return m_mainwindow->threadManager();
}
ModeManager *CoreImpl::modeManager() const
{
return m_mainwindow->modeManager();
}
MimeDatabase *CoreImpl::mimeDatabase() const
{
return m_mainwindow->mimeDatabase();
}
QSettings *CoreImpl::settings(QSettings::Scope scope) const
{
return m_mainwindow->settings(scope);
}
SettingsDatabase *CoreImpl::settingsDatabase() const
{
return m_mainwindow->settingsDatabase();
}
#ifdef Q_OS_MAC
# define SHARE_PATH "/../Resources"
#else
# define SHARE_PATH "/../share/openpilotgcs"
#endif
QString CoreImpl::resourcePath() const
{
return QDir::cleanPath(QCoreApplication::applicationDirPath() + QLatin1String(SHARE_PATH));
}
IContext *CoreImpl::currentContextObject() const
{
return m_mainwindow->currentContextObject();
}
QMainWindow *CoreImpl::mainWindow() const
{
return m_mainwindow;
}
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
void CoreImpl::addAdditionalContext(int context)
{
m_mainwindow->addAdditionalContext(context);
}
void CoreImpl::removeAdditionalContext(int context)
{
m_mainwindow->removeAdditionalContext(context);
}
bool CoreImpl::hasContext(int context) const
{
return m_mainwindow->hasContext(context);
}
void CoreImpl::addContextObject(IContext *context)
{
m_mainwindow->addContextObject(context);
}
void CoreImpl::removeContextObject(IContext *context)
{
m_mainwindow->removeContextObject(context);
}
void CoreImpl::updateContext()
{
return m_mainwindow->updateContext();
}
void CoreImpl::openFiles(const QStringList &arguments)
{
//m_mainwindow->openFiles(arguments);
}
void CoreImpl::readMainSettings(QSettings* qs)
{
m_mainwindow->readSettings(qs);
}
void CoreImpl::saveMainSettings(QSettings* qs)
{
m_mainwindow->saveSettings(qs);
}
/**
******************************************************************************
*
* @file coreimpl.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "coreimpl.h"
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
namespace Core {
namespace Internal {
// The Core Singleton
static CoreImpl *m_instance = 0;
} // namespace Internal
} // namespace Core
using namespace Core;
using namespace Core::Internal;
ICore* ICore::instance()
{
return m_instance;
}
CoreImpl::CoreImpl(MainWindow *mainwindow)
{
m_instance = this;
m_mainwindow = mainwindow;
}
bool CoreImpl::showOptionsDialog(const QString &group, const QString &page, QWidget *parent)
{
return m_mainwindow->showOptionsDialog(group, page, parent);
}
bool CoreImpl::showWarningWithOptions(const QString &title, const QString &text,
const QString &details,
const QString &settingsCategory,
const QString &settingsId,
QWidget *parent)
{
return m_mainwindow->showWarningWithOptions(title, text,
details, settingsCategory,
settingsId, parent);
}
ActionManager *CoreImpl::actionManager() const
{
return m_mainwindow->actionManager();
}
UniqueIDManager *CoreImpl::uniqueIDManager() const
{
return m_mainwindow->uniqueIDManager();
}
MessageManager *CoreImpl::messageManager() const
{
return m_mainwindow->messageManager();
}
ConnectionManager *CoreImpl::connectionManager() const
{
return m_mainwindow->connectionManager();
}
UAVGadgetInstanceManager *CoreImpl::uavGadgetInstanceManager() const
{
return m_mainwindow->uavGadgetInstanceManager();
}
VariableManager *CoreImpl::variableManager() const
{
return m_mainwindow->variableManager();
}
ThreadManager *CoreImpl::threadManager() const
{
return m_mainwindow->threadManager();
}
ModeManager *CoreImpl::modeManager() const
{
return m_mainwindow->modeManager();
}
MimeDatabase *CoreImpl::mimeDatabase() const
{
return m_mainwindow->mimeDatabase();
}
QSettings *CoreImpl::settings(QSettings::Scope scope) const
{
return m_mainwindow->settings(scope);
}
SettingsDatabase *CoreImpl::settingsDatabase() const
{
return m_mainwindow->settingsDatabase();
}
#ifdef Q_OS_MAC
# define SHARE_PATH "/../Resources"
#else
# define SHARE_PATH "/../share/openpilotgcs"
#endif
QString CoreImpl::resourcePath() const
{
return QDir::cleanPath(QCoreApplication::applicationDirPath() + QLatin1String(SHARE_PATH));
}
IContext *CoreImpl::currentContextObject() const
{
return m_mainwindow->currentContextObject();
}
QMainWindow *CoreImpl::mainWindow() const
{
return m_mainwindow;
}
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
void CoreImpl::addAdditionalContext(int context)
{
m_mainwindow->addAdditionalContext(context);
}
void CoreImpl::removeAdditionalContext(int context)
{
m_mainwindow->removeAdditionalContext(context);
}
bool CoreImpl::hasContext(int context) const
{
return m_mainwindow->hasContext(context);
}
void CoreImpl::addContextObject(IContext *context)
{
m_mainwindow->addContextObject(context);
}
void CoreImpl::removeContextObject(IContext *context)
{
m_mainwindow->removeContextObject(context);
}
void CoreImpl::updateContext()
{
return m_mainwindow->updateContext();
}
void CoreImpl::openFiles(const QStringList &arguments)
{
//m_mainwindow->openFiles(arguments);
}
void CoreImpl::readMainSettings(QSettings* qs)
{
m_mainwindow->readSettings(qs);
}
void CoreImpl::saveMainSettings(QSettings* qs)
{
m_mainwindow->saveSettings(qs);
}
void CoreImpl::readSettings(IConfigurablePlugin* plugin, QSettings* qs)
{
m_mainwindow->readSettings(plugin, qs);
}
void CoreImpl::saveSettings(IConfigurablePlugin* plugin, QSettings* qs)
{
m_mainwindow->saveSettings(plugin, qs);
}

View File

@ -1,96 +1,98 @@
/**
******************************************************************************
*
* @file coreimpl.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 COREIMPL_H
#define COREIMPL_H
#include "icore.h"
#include "mainwindow.h"
namespace Core {
namespace Internal {
class CoreImpl : public ICore
{
Q_OBJECT
public:
CoreImpl(MainWindow *mainwindow);
~CoreImpl() {}
bool showOptionsDialog(const QString &group = QString(),
const QString &page = QString(),
QWidget *parent = 0);
bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0);
ActionManager *actionManager() const;
UniqueIDManager *uniqueIDManager() const;
MessageManager *messageManager() const;
ConnectionManager *connectionManager() const;
UAVGadgetInstanceManager *uavGadgetInstanceManager() const;
VariableManager *variableManager() const;
ThreadManager *threadManager() const;
ModeManager *modeManager() const;
MimeDatabase *mimeDatabase() const;
QSettings *settings(QSettings::Scope scope = QSettings::UserScope) const;
SettingsDatabase *settingsDatabase() const;
void readMainSettings(QSettings* qs);
void saveMainSettings(QSettings* qs);
QString resourcePath() const;
IContext *currentContextObject() const;
QMainWindow *mainWindow() const;
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
void addAdditionalContext(int context);
void removeAdditionalContext(int context);
bool hasContext(int context) const;
void addContextObject(IContext *contex);
void removeContextObject(IContext *contex);
void updateContext();
void openFiles(const QStringList &fileNames);
private:
MainWindow *m_mainwindow;
friend class MainWindow;
};
} // namespace Internal
} // namespace Core
#endif // COREIMPL_H
/**
******************************************************************************
*
* @file coreimpl.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 COREIMPL_H
#define COREIMPL_H
#include "icore.h"
#include "mainwindow.h"
namespace Core {
namespace Internal {
class CoreImpl : public ICore
{
Q_OBJECT
public:
CoreImpl(MainWindow *mainwindow);
~CoreImpl() {}
bool showOptionsDialog(const QString &group = QString(),
const QString &page = QString(),
QWidget *parent = 0);
bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0);
ActionManager *actionManager() const;
UniqueIDManager *uniqueIDManager() const;
MessageManager *messageManager() const;
ConnectionManager *connectionManager() const;
UAVGadgetInstanceManager *uavGadgetInstanceManager() const;
VariableManager *variableManager() const;
ThreadManager *threadManager() const;
ModeManager *modeManager() const;
MimeDatabase *mimeDatabase() const;
QSettings *settings(QSettings::Scope scope = QSettings::UserScope) const;
SettingsDatabase *settingsDatabase() const;
void readMainSettings(QSettings* qs);
void saveMainSettings(QSettings* qs);
void readSettings(IConfigurablePlugin* plugin, QSettings* qs = 0 );
void saveSettings(IConfigurablePlugin* plugin, QSettings* qs = 0 );
QString resourcePath() const;
IContext *currentContextObject() const;
QMainWindow *mainWindow() const;
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
void addAdditionalContext(int context);
void removeAdditionalContext(int context);
bool hasContext(int context) const;
void addContextObject(IContext *contex);
void removeContextObject(IContext *contex);
void updateContext();
void openFiles(const QStringList &fileNames);
private:
MainWindow *m_mainwindow;
friend class MainWindow;
};
} // namespace Internal
} // namespace Core
#endif // COREIMPL_H

View File

@ -125,7 +125,8 @@ HEADERS += mainwindow.h \
uavgadgetdecorator.h \
workspacesettings.h \
uavconfiginfo.h \
authorsdialog.h
authorsdialog.h \
iconfigurableplugin.h
FORMS += dialogs/settingsdialog.ui \
dialogs/shortcutsettings.ui \
generalsettings.ui \

View File

@ -1,218 +1,219 @@
/**
******************************************************************************
*
* @file generalsettings.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "generalsettings.h"
#include <utils/stylehelper.h>
#include <utils/qtcolorbutton.h>
#include <utils/consoleprocess.h>
#include <coreplugin/icore.h>
#include <QtGui/QMessageBox>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QSettings>
#include "ui_generalsettings.h"
using namespace Utils;
using namespace Core::Internal;
GeneralSettings::GeneralSettings():
m_dialog(0)
{
}
QString GeneralSettings::id() const
{
return QLatin1String("General");
}
QString GeneralSettings::trName() const
{
return tr("General");
}
QString GeneralSettings::category() const
{
return QLatin1String("Environment");
}
QString GeneralSettings::trCategory() const
{
return tr("Environment");
}
static bool hasQmFilesForLocale(const QString &locale, const QString &creatorTrPath)
{
static const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString trFile = QLatin1String("qt_") + locale + QLatin1String(".qm");
return QFile::exists(qtTrPath+'/'+trFile) || QFile::exists(creatorTrPath+'/'+trFile);
}
void GeneralSettings::fillLanguageBox() const
{
const QString currentLocale = language();
m_page->languageBox->addItem(tr("<System Language>"), QString());
// need to add this explicitly, since there is no qm file for English
m_page->languageBox->addItem(QLatin1String("English"), QLatin1String("C"));
if (currentLocale == QLatin1String("C"))
m_page->languageBox->setCurrentIndex(m_page->languageBox->count() - 1);
const QString creatorTrPath =
Core::ICore::instance()->resourcePath() + QLatin1String("/translations");
const QStringList languageFiles = QDir(creatorTrPath).entryList(QStringList(QLatin1String("openpilotgcs*.qm")));
Q_FOREACH(const QString &languageFile, languageFiles)
{
int start = languageFile.indexOf(QLatin1Char('_'))+1;
int end = languageFile.lastIndexOf(QLatin1Char('.'));
const QString locale = languageFile.mid(start, end-start);
// no need to show a language that creator will not load anyway
if (hasQmFilesForLocale(locale, creatorTrPath)) {
m_page->languageBox->addItem(QLocale::languageToString(QLocale(locale).language()), locale);
if (locale == currentLocale)
m_page->languageBox->setCurrentIndex(m_page->languageBox->count() - 1);
}
}
}
QWidget *GeneralSettings::createPage(QWidget *parent)
{
m_page = new Ui::GeneralSettings();
QWidget *w = new QWidget(parent);
m_page->setupUi(w);
QSettings* settings = Core::ICore::instance()->settings();
fillLanguageBox();
m_page->colorButton->setColor(StyleHelper::baseColor());
#ifdef Q_OS_UNIX
m_page->terminalEdit->setText(ConsoleProcess::terminalEmulator(Core::ICore::instance()->settings()));
#else
m_page->terminalLabel->hide();
m_page->terminalEdit->hide();
m_page->resetTerminalButton->hide();
#endif
connect(m_page->resetButton, SIGNAL(clicked()),
this, SLOT(resetInterfaceColor()));
connect(m_page->resetEditorButton, SIGNAL(clicked()),
this, SLOT(resetExternalEditor()));
connect(m_page->helpExternalEditorButton, SIGNAL(clicked()),
this, SLOT(showHelpForExternalEditor()));
#ifdef Q_OS_UNIX
connect(m_page->resetTerminalButton, SIGNAL(clicked()),
this, SLOT(resetTerminal()));
#endif
return w;
}
void GeneralSettings::apply()
{
int currentIndex = m_page->languageBox->currentIndex();
setLanguage(m_page->languageBox->itemData(currentIndex, Qt::UserRole).toString());
// Apply the new base color if accepted
StyleHelper::setBaseColor(m_page->colorButton->color());
#ifdef Q_OS_UNIX
ConsoleProcess::setTerminalEmulator(Core::ICore::instance()->settings(),
m_page->terminalEdit->text());
#endif
}
void GeneralSettings::finish()
{
delete m_page;
}
void GeneralSettings::resetInterfaceColor()
{
m_page->colorButton->setColor(0x666666);
}
void GeneralSettings::resetExternalEditor()
{
}
#ifdef Q_OS_UNIX
void GeneralSettings::resetTerminal()
{
m_page->terminalEdit->setText(ConsoleProcess::defaultTerminalEmulator() + QLatin1String(" -e"));
}
#endif
void GeneralSettings::showHelpForExternalEditor()
{
if (m_dialog) {
m_dialog->show();
m_dialog->raise();
m_dialog->activateWindow();
return;
}
#if 0
QMessageBox *mb = new QMessageBox(QMessageBox::Information,
tr("Variables"),
EditorManager::instance()->externalEditorHelpText(),
QMessageBox::Cancel,
m_page->helpExternalEditorButton);
mb->setWindowModality(Qt::NonModal);
m_dialog = mb;
mb->show();
#endif
}
void GeneralSettings::resetLanguage()
{
// system language is default
m_page->languageBox->setCurrentIndex(0);
}
QString GeneralSettings::language() const
{
QSettings* settings = Core::ICore::instance()->settings();
return settings->value(QLatin1String("General/OverrideLanguage")).toString();
}
void GeneralSettings::setLanguage(const QString &locale)
{
QSettings* settings = Core::ICore::instance()->settings();
if (settings->value(QLatin1String("General/OverrideLanguage")).toString() != locale)
{
QMessageBox::information((QWidget*)Core::ICore::instance()->mainWindow(), tr("Restart required"),
tr("The language change will take effect after a restart of the OpenPilot GCS."));
}
if (locale.isEmpty())
settings->remove(QLatin1String("General/OverrideLanguage"));
else
settings->setValue(QLatin1String("General/OverrideLanguage"), locale);
}
/**
******************************************************************************
*
* @file generalsettings.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "generalsettings.h"
#include <utils/stylehelper.h>
#include <utils/qtcolorbutton.h>
#include <utils/consoleprocess.h>
#include <coreplugin/icore.h>
#include <QtGui/QMessageBox>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QSettings>
#include "ui_generalsettings.h"
using namespace Utils;
using namespace Core::Internal;
GeneralSettings::GeneralSettings():
m_dialog(0)
{
}
QString GeneralSettings::id() const
{
return QLatin1String("General");
}
QString GeneralSettings::trName() const
{
return tr("General");
}
QString GeneralSettings::category() const
{
return QLatin1String("Environment");
}
QString GeneralSettings::trCategory() const
{
return tr("Environment");
}
static bool hasQmFilesForLocale(const QString &locale, const QString &creatorTrPath)
{
static const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString trFile = QLatin1String("qt_") + locale + QLatin1String(".qm");
return QFile::exists(qtTrPath+'/'+trFile) || QFile::exists(creatorTrPath+'/'+trFile);
}
void GeneralSettings::fillLanguageBox() const
{
const QString currentLocale = language();
m_page->languageBox->addItem(tr("<System Language>"), QString());
// need to add this explicitly, since there is no qm file for English
m_page->languageBox->addItem(QLatin1String("English"), QLatin1String("C"));
if (currentLocale == QLatin1String("C"))
m_page->languageBox->setCurrentIndex(m_page->languageBox->count() - 1);
const QString creatorTrPath =
Core::ICore::instance()->resourcePath() + QLatin1String("/translations");
const QStringList languageFiles = QDir(creatorTrPath).entryList(QStringList(QLatin1String("openpilotgcs*.qm")));
Q_FOREACH(const QString &languageFile, languageFiles)
{
int start = languageFile.indexOf(QLatin1Char('_'))+1;
int end = languageFile.lastIndexOf(QLatin1Char('.'));
const QString locale = languageFile.mid(start, end-start);
// no need to show a language that creator will not load anyway
if (hasQmFilesForLocale(locale, creatorTrPath)) {
m_page->languageBox->addItem(QLocale::languageToString(QLocale(locale).language()), locale);
if (locale == currentLocale)
m_page->languageBox->setCurrentIndex(m_page->languageBox->count() - 1);
}
}
}
QWidget *GeneralSettings::createPage(QWidget *parent)
{
m_page = new Ui::GeneralSettings();
QWidget *w = new QWidget(parent);
m_page->setupUi(w);
/* TODO: Clean this: settings not used, Core::ICore::instance()->settings() shouldn't be used, since not externally configurable */
QSettings* settings = Core::ICore::instance()->settings();
fillLanguageBox();
m_page->colorButton->setColor(StyleHelper::baseColor());
#ifdef Q_OS_UNIX
m_page->terminalEdit->setText(ConsoleProcess::terminalEmulator(Core::ICore::instance()->settings()));
#else
m_page->terminalLabel->hide();
m_page->terminalEdit->hide();
m_page->resetTerminalButton->hide();
#endif
connect(m_page->resetButton, SIGNAL(clicked()),
this, SLOT(resetInterfaceColor()));
connect(m_page->resetEditorButton, SIGNAL(clicked()),
this, SLOT(resetExternalEditor()));
connect(m_page->helpExternalEditorButton, SIGNAL(clicked()),
this, SLOT(showHelpForExternalEditor()));
#ifdef Q_OS_UNIX
connect(m_page->resetTerminalButton, SIGNAL(clicked()),
this, SLOT(resetTerminal()));
#endif
return w;
}
void GeneralSettings::apply()
{
int currentIndex = m_page->languageBox->currentIndex();
setLanguage(m_page->languageBox->itemData(currentIndex, Qt::UserRole).toString());
// Apply the new base color if accepted
StyleHelper::setBaseColor(m_page->colorButton->color());
#ifdef Q_OS_UNIX
ConsoleProcess::setTerminalEmulator(Core::ICore::instance()->settings(),
m_page->terminalEdit->text());
#endif
}
void GeneralSettings::finish()
{
delete m_page;
}
void GeneralSettings::resetInterfaceColor()
{
m_page->colorButton->setColor(0x666666);
}
void GeneralSettings::resetExternalEditor()
{
}
#ifdef Q_OS_UNIX
void GeneralSettings::resetTerminal()
{
m_page->terminalEdit->setText(ConsoleProcess::defaultTerminalEmulator() + QLatin1String(" -e"));
}
#endif
void GeneralSettings::showHelpForExternalEditor()
{
if (m_dialog) {
m_dialog->show();
m_dialog->raise();
m_dialog->activateWindow();
return;
}
#if 0
QMessageBox *mb = new QMessageBox(QMessageBox::Information,
tr("Variables"),
EditorManager::instance()->externalEditorHelpText(),
QMessageBox::Cancel,
m_page->helpExternalEditorButton);
mb->setWindowModality(Qt::NonModal);
m_dialog = mb;
mb->show();
#endif
}
void GeneralSettings::resetLanguage()
{
// system language is default
m_page->languageBox->setCurrentIndex(0);
}
QString GeneralSettings::language() const
{
QSettings* settings = Core::ICore::instance()->settings();
return settings->value(QLatin1String("General/OverrideLanguage")).toString();
}
void GeneralSettings::setLanguage(const QString &locale)
{
QSettings* settings = Core::ICore::instance()->settings();
if (settings->value(QLatin1String("General/OverrideLanguage")).toString() != locale)
{
QMessageBox::information((QWidget*)Core::ICore::instance()->mainWindow(), tr("Restart required"),
tr("The language change will take effect after a restart of the OpenPilot GCS."));
}
if (locale.isEmpty())
settings->remove(QLatin1String("General/OverrideLanguage"));
else
settings->setValue(QLatin1String("General/OverrideLanguage"), locale);
}

View File

@ -0,0 +1,24 @@
#ifndef ICONFIGURABLEPLUGIN_H
#define ICONFIGURABLEPLUGIN_H
#include <QObject>
#include <QSettings>
#include <extensionsystem/iplugin.h>
#include <coreplugin/uavconfiginfo.h>
#include <coreplugin/core_global.h>
namespace Core {
class CORE_EXPORT IConfigurablePlugin : public ExtensionSystem::IPlugin
{
public:
// IConfigurablePlugin(QObject *parent = 0){}
virtual ~IConfigurablePlugin() {}
virtual void readConfig( QSettings* qSettings, UAVConfigInfo *configInfo) = 0;
virtual void saveConfig(QSettings* qSettings, Core::UAVConfigInfo *configInfo) = 0;
};
} // namespace Core
#endif // ICONFIGURABLEPLUGIN_H

View File

@ -1,122 +1,125 @@
/**
******************************************************************************
*
* @file icore.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 ICORE_H
#define ICORE_H
#include "core_global.h"
#include <QtCore/QObject>
#include <QSettings>
QT_BEGIN_NAMESPACE
class QMainWindow;
class QSettings;
template <class T> class QList;
QT_END_NAMESPACE
namespace Core {
class ActionManager;
class IContext;
class IWizard;
class ConnectionManager;
class MessageManager;
class MimeDatabase;
class ModeManager;
class SettingsDatabase;
class UniqueIDManager;
class VariableManager;
class ThreadManager;
class UAVGadgetManager;
class UAVGadgetInstanceManager;
class CORE_EXPORT ICore : public QObject
{
Q_OBJECT
public:
ICore() {}
virtual ~ICore() {}
static ICore *instance();
virtual bool showOptionsDialog(const QString &group = QString(),
const QString &page = QString(),
QWidget *parent = 0) = 0;
virtual bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0) = 0;
virtual ActionManager *actionManager() const = 0;
virtual UniqueIDManager *uniqueIDManager() const = 0;
virtual MessageManager *messageManager() const = 0;
virtual VariableManager *variableManager() const = 0;
virtual ThreadManager *threadManager() const = 0;
virtual ModeManager *modeManager() const = 0;
virtual ConnectionManager *connectionManager() const = 0;
virtual UAVGadgetInstanceManager *uavGadgetInstanceManager() const = 0;
virtual MimeDatabase *mimeDatabase() const = 0;
virtual QSettings *settings(QSettings::Scope scope = QSettings::UserScope) const = 0;
virtual SettingsDatabase *settingsDatabase() const = 0;
virtual void readMainSettings(QSettings* qs) = 0;
virtual void saveMainSettings(QSettings* qs) = 0;
virtual QString resourcePath() const = 0;
virtual QMainWindow *mainWindow() const = 0;
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
virtual IContext *currentContextObject() const = 0;
virtual void addAdditionalContext(int context) = 0;
virtual void removeAdditionalContext(int context) = 0;
virtual bool hasContext(int context) const = 0;
virtual void addContextObject(IContext *context) = 0;
virtual void removeContextObject(IContext *context) = 0;
virtual void updateContext() = 0;
virtual void openFiles(const QStringList &fileNames) = 0;
signals:
void coreAboutToOpen();
void coreOpened();
void saveSettingsRequested();
void optionsDialogRequested();
void coreAboutToClose();
void contextAboutToChange(Core::IContext *context);
void contextChanged(Core::IContext *context);
};
} // namespace Core
#endif // ICORE_H
/**
******************************************************************************
*
* @file icore.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 ICORE_H
#define ICORE_H
#include "core_global.h"
#include <QtCore/QObject>
#include <QSettings>
QT_BEGIN_NAMESPACE
class QMainWindow;
class QSettings;
template <class T> class QList;
QT_END_NAMESPACE
namespace Core {
class ActionManager;
class IContext;
class IWizard;
class ConnectionManager;
class MessageManager;
class MimeDatabase;
class ModeManager;
class SettingsDatabase;
class UniqueIDManager;
class VariableManager;
class ThreadManager;
class UAVGadgetManager;
class UAVGadgetInstanceManager;
class IConfigurablePlugin;
class CORE_EXPORT ICore : public QObject
{
Q_OBJECT
public:
ICore() {}
virtual ~ICore() {}
static ICore *instance();
virtual bool showOptionsDialog(const QString &group = QString(),
const QString &page = QString(),
QWidget *parent = 0) = 0;
virtual bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0) = 0;
virtual ActionManager *actionManager() const = 0;
virtual UniqueIDManager *uniqueIDManager() const = 0;
virtual MessageManager *messageManager() const = 0;
virtual VariableManager *variableManager() const = 0;
virtual ThreadManager *threadManager() const = 0;
virtual ModeManager *modeManager() const = 0;
virtual ConnectionManager *connectionManager() const = 0;
virtual UAVGadgetInstanceManager *uavGadgetInstanceManager() const = 0;
virtual MimeDatabase *mimeDatabase() const = 0;
virtual QSettings *settings(QSettings::Scope scope = QSettings::UserScope) const = 0;
virtual SettingsDatabase *settingsDatabase() const = 0;
virtual void readMainSettings(QSettings* qs) = 0;
virtual void saveMainSettings(QSettings* qs) = 0;
virtual void readSettings(IConfigurablePlugin* plugin, QSettings* qs = 0) = 0;
virtual void saveSettings(IConfigurablePlugin* plugin, QSettings* qs = 0) = 0;
virtual QString resourcePath() const = 0;
virtual QMainWindow *mainWindow() const = 0;
// adds and removes additional active contexts, this context is appended to the
// currently active contexts. call updateContext after changing
virtual IContext *currentContextObject() const = 0;
virtual void addAdditionalContext(int context) = 0;
virtual void removeAdditionalContext(int context) = 0;
virtual bool hasContext(int context) const = 0;
virtual void addContextObject(IContext *context) = 0;
virtual void removeContextObject(IContext *context) = 0;
virtual void updateContext() = 0;
virtual void openFiles(const QStringList &fileNames) = 0;
signals:
void coreAboutToOpen();
void coreOpened();
void saveSettingsRequested();
void optionsDialogRequested();
void coreAboutToClose();
void contextAboutToChange(Core::IContext *context);
void contextChanged(Core::IContext *context);
};
} // namespace Core
#endif // ICORE_H

View File

@ -1,1221 +1,1263 @@
/**
******************************************************************************
*
* @file mainwindow.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "mainwindow.h"
#include "actioncontainer.h"
#include "actionmanager_p.h"
#include "basemode.h"
#include "coreimpl.h"
#include "coreconstants.h"
#include "fancytabwidget.h"
#include "generalsettings.h"
#include "messagemanager.h"
#include "modemanager.h"
#include "mimedatabase.h"
#include "outputpane.h"
#include "plugindialog.h"
#include "shortcutsettings.h"
#include "workspacesettings.h"
#include "modemanager.h"
#include "uavgadgetmode.h"
#include "uavgadgetmanager.h"
#include "uavgadgetinstancemanager.h"
#include "connectionmanager.h"
#include "qxtlogger.h"
#include "qxtbasicstdloggerengine.h"
#include "settingsdialog.h"
#include "variablemanager.h"
#include "threadmanager.h"
#include "versiondialog.h"
#include "authorsdialog.h"
#include "viewmanager.h"
#include "uniqueidmanager.h"
#include "manhattanstyle.h"
#include "dialogs/iwizard.h"
#include "rightpane.h"
#include "baseview.h"
#include "ioutputpane.h"
#include "icorelistener.h"
#include <coreplugin/settingsdatabase.h>
#include <utils/pathchooser.h>
#include <utils/stylehelper.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtCore/QtPlugin>
#include <QtCore/QUrl>
#include <QtGui/QApplication>
#include <QtGui/QCloseEvent>
#include <QtGui/QMenu>
#include <QtGui/QPixmap>
#include <QtGui/QShortcut>
#include <QtGui/QStatusBar>
#include <QtGui/QWizard>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
/*
#ifdef Q_OS_UNIX
#include <signal.h>
extern "C" void handleSigInt(int sig)
{
Q_UNUSED(sig)
Core::ICore::instance()->exit();
qDebug() << "SIGINT caught. Shutting down.";
}
#endif
*/
using namespace Core;
using namespace Core::Internal;
static const char *uriListMimeFormatC = "text/uri-list";
enum { debugMainWindow = 0 };
MainWindow::MainWindow() :
EventFilteringMainWindow(),
m_coreImpl(new CoreImpl(this)),
m_uniqueIDManager(new UniqueIDManager()),
m_globalContext(QList<int>() << Constants::C_GLOBAL_ID),
m_additionalContexts(m_globalContext),
// keep this in sync with main() in app/main.cpp
m_settings(new QSettings(QSettings::IniFormat, QSettings::UserScope,
QLatin1String("OpenPilot"), QLatin1String("OpenPilotGCS"), this)),
m_globalSettings(new QSettings(QSettings::IniFormat, QSettings::SystemScope,
QLatin1String("OpenPilot"), QLatin1String("OpenPilotGCS"), this)),
m_settingsDatabase(new SettingsDatabase(QFileInfo(m_settings->fileName()).path(),
QLatin1String("OpenPilotGCS"),
this)),
m_actionManager(new ActionManagerPrivate(this)),
m_variableManager(new VariableManager(this)),
m_threadManager(new ThreadManager(this)),
m_viewManager(0),
m_modeManager(0),
m_connectionManager(0),
m_mimeDatabase(new MimeDatabase),
// m_rightPaneWidget(0),
m_versionDialog(0),
m_authorsDialog(0),
m_activeContext(0),
m_generalSettings(new GeneralSettings),
m_shortcutSettings(new ShortcutSettings),
m_workspaceSettings(new WorkspaceSettings),
m_focusToEditor(0),
m_newAction(0),
m_openAction(0),
m_openWithAction(0),
m_saveAllAction(0),
m_exitAction(0),
m_optionsAction(0),
#ifdef Q_WS_MAC
m_minimizeAction(0),
m_zoomAction(0),
#endif
m_toggleFullScreenAction(0)
{
setWindowTitle(tr("OpenPilot GCS"));
#ifndef Q_WS_MAC
qApp->setWindowIcon(QIcon(":/core/images/openpilot_logo_128.png"));
#endif
QCoreApplication::setApplicationName(QLatin1String("OpenPilotGCS"));
QCoreApplication::setApplicationVersion(QLatin1String(Core::Constants::GCS_VERSION_LONG));
QCoreApplication::setOrganizationName(QLatin1String("OpenPilot"));
QCoreApplication::setOrganizationDomain(QLatin1String("openpilot.org"));
QSettings::setDefaultFormat(QSettings::IniFormat);
QString baseName = qApp->style()->objectName();
#ifdef Q_WS_X11
if (baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
baseName = QLatin1String("plastique");
else
baseName = QLatin1String("cleanlooks");
}
#endif
qApp->setStyle(new ManhattanStyle(baseName));
setDockNestingEnabled(true);
setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
registerDefaultContainers();
registerDefaultActions();
m_modeStack = new FancyTabWidget(this);
m_modeManager = new ModeManager(this, m_modeStack);
m_connectionManager = new ConnectionManager(this, m_modeStack);
m_viewManager = new ViewManager(this);
m_messageManager = new MessageManager;
setCentralWidget(m_modeStack);
connect(QApplication::instance(), SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateFocusWidget(QWidget*,QWidget*)));
// setUnifiedTitleAndToolBarOnMac(true);
#ifdef Q_OS_UNIX
//signal(SIGINT, handleSigInt);
#endif
statusBar()->setProperty("p_styled", true);
setAcceptDrops(true);
foreach (QString engine, qxtLog->allLoggerEngines())
qxtLog->removeLoggerEngine(engine);
qxtLog->addLoggerEngine("std", new QxtBasicSTDLoggerEngine());
qxtLog->installAsMessageHandler();
qxtLog->enableAllLogLevels();
}
MainWindow::~MainWindow()
{
hide();
qxtLog->removeAsMessageHandler();
foreach (QString engine, qxtLog->allLoggerEngines())
qxtLog->removeLoggerEngine(engine);
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
if (m_uavGadgetModes.count() > 0) {
foreach (UAVGadgetMode *mode, m_uavGadgetModes)
{
pm->removeObject(mode);
delete mode;
}
}
pm->removeObject(m_shortcutSettings);
pm->removeObject(m_generalSettings);
pm->removeObject(m_workspaceSettings);
delete m_messageManager;
m_messageManager = 0;
delete m_shortcutSettings;
m_shortcutSettings = 0;
delete m_generalSettings;
m_generalSettings = 0;
delete m_workspaceSettings;
m_workspaceSettings = 0;
delete m_settings;
m_settings = 0;
delete m_uniqueIDManager;
m_uniqueIDManager = 0;
delete m_viewManager;
m_viewManager = 0;
pm->removeObject(m_coreImpl);
delete m_coreImpl;
m_coreImpl = 0;
// delete m_rightPaneWidget;
// m_rightPaneWidget = 0;
delete m_modeManager;
m_modeManager = 0;
delete m_mimeDatabase;
m_mimeDatabase = 0;
}
bool MainWindow::init(QString *errorMessage)
{
Q_UNUSED(errorMessage)
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
pm->addObject(m_coreImpl);
m_viewManager->init();
m_modeManager->init();
m_connectionManager->init();
pm->addObject(m_generalSettings);
pm->addObject(m_shortcutSettings);
pm->addObject(m_workspaceSettings);
return true;
}
void MainWindow::modeChanged(Core::IMode */*mode*/)
{
}
void MainWindow::extensionsInitialized()
{
QSettings* qs = m_settings;
QSettings defaultSettings(":/core/OpenPilotGCS.ini", QSettings::IniFormat);
if ( ! qs->allKeys().count() ){
qDebug() << "There is no config, load default config from resource /core/OpenPilotGCS.ini";
qs = &defaultSettings;
}
// qDebug() << "Number of keys in config: " << qs->allKeys().count();
m_uavGadgetInstanceManager = new UAVGadgetInstanceManager(this);
m_uavGadgetInstanceManager->readConfigurations(qs);
m_messageManager->init();
readSettings(qs);
updateContext();
emit m_coreImpl->coreAboutToOpen();
show();
emit m_coreImpl->coreOpened();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
emit m_coreImpl->saveSettingsRequested();
const QList<ICoreListener *> listeners =
ExtensionSystem::PluginManager::instance()->getObjects<ICoreListener>();
foreach (ICoreListener *listener, listeners) {
if (!listener->coreAboutToClose()) {
event->ignore();
return;
}
}
emit m_coreImpl->coreAboutToClose();
saveSettings(m_settings);
m_uavGadgetInstanceManager->writeConfigurations(m_settings);
event->accept();
}
// Check for desktop file manager file drop events
static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
{
if (files)
files->clear();
// Extract dropped files from Mime data.
if (!d->hasFormat(QLatin1String(uriListMimeFormatC)))
return false;
const QList<QUrl> urls = d->urls();
if (urls.empty())
return false;
// Try to find local files
bool hasFiles = false;
const QList<QUrl>::const_iterator cend = urls.constEnd();
for (QList<QUrl>::const_iterator it = urls.constBegin(); it != cend; ++it) {
const QString fileName = it->toLocalFile();
if (!fileName.isEmpty()) {
hasFiles = true;
if (files) {
files->push_back(fileName);
} else {
break; // No result list, sufficient for checking
}
}
}
return hasFiles;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (isDesktopFileManagerDrop(event->mimeData())) {
event->accept();
} else {
event->ignore();
}
}
void MainWindow::dropEvent(QDropEvent *event)
{
QStringList files;
if (isDesktopFileManagerDrop(event->mimeData(), &files)) {
event->accept();
//openFiles(files);
} else {
event->ignore();
}
}
IContext *MainWindow::currentContextObject() const
{
return m_activeContext;
}
QStatusBar *MainWindow::statusBar() const
{
return m_modeStack->statusBar();
}
void MainWindow::registerDefaultContainers()
{
ActionManagerPrivate *am = m_actionManager;
ActionContainer *menubar = am->createMenuBar(Constants::MENU_BAR);
#ifndef Q_WS_MAC // System menu bar on Mac
setMenuBar(menubar->menuBar());
#endif
menubar->appendGroup(Constants::G_FILE);
menubar->appendGroup(Constants::G_EDIT);
menubar->appendGroup(Constants::G_VIEW);
menubar->appendGroup(Constants::G_TOOLS);
menubar->appendGroup(Constants::G_WINDOW);
menubar->appendGroup(Constants::G_HELP);
// File Menu
ActionContainer *filemenu = am->createMenu(Constants::M_FILE);
menubar->addMenu(filemenu, Constants::G_FILE);
filemenu->menu()->setTitle(tr("&File"));
filemenu->appendGroup(Constants::G_FILE_NEW);
filemenu->appendGroup(Constants::G_FILE_OPEN);
filemenu->appendGroup(Constants::G_FILE_PROJECT);
filemenu->appendGroup(Constants::G_FILE_SAVE);
filemenu->appendGroup(Constants::G_FILE_CLOSE);
filemenu->appendGroup(Constants::G_FILE_OTHER);
connect(filemenu->menu(), SIGNAL(aboutToShow()), this, SLOT(aboutToShowRecentFiles()));
// Edit Menu
ActionContainer *medit = am->createMenu(Constants::M_EDIT);
menubar->addMenu(medit, Constants::G_EDIT);
medit->menu()->setTitle(tr("&Edit"));
medit->appendGroup(Constants::G_EDIT_UNDOREDO);
medit->appendGroup(Constants::G_EDIT_COPYPASTE);
medit->appendGroup(Constants::G_EDIT_SELECTALL);
medit->appendGroup(Constants::G_EDIT_ADVANCED);
medit->appendGroup(Constants::G_EDIT_FIND);
medit->appendGroup(Constants::G_EDIT_OTHER);
// Tools Menu
ActionContainer *ac = am->createMenu(Constants::M_TOOLS);
menubar->addMenu(ac, Constants::G_TOOLS);
ac->menu()->setTitle(tr("&Tools"));
// Window Menu
ActionContainer *mwindow = am->createMenu(Constants::M_WINDOW);
menubar->addMenu(mwindow, Constants::G_WINDOW);
mwindow->menu()->setTitle(tr("&Window"));
mwindow->appendGroup(Constants::G_WINDOW_SIZE);
mwindow->appendGroup(Constants::G_WINDOW_HIDE_TOOLBAR);
mwindow->appendGroup(Constants::G_WINDOW_PANES);
mwindow->appendGroup(Constants::G_WINDOW_SPLIT);
mwindow->appendGroup(Constants::G_WINDOW_NAVIGATE);
mwindow->appendGroup(Constants::G_WINDOW_OTHER);
// Help Menu
ac = am->createMenu(Constants::M_HELP);
menubar->addMenu(ac, Constants::G_HELP);
ac->menu()->setTitle(tr("&Help"));
ac->appendGroup(Constants::G_HELP_HELP);
ac->appendGroup(Constants::G_HELP_ABOUT);
}
static Command *createSeparator(ActionManager *am, QObject *parent,
const QString &name,
const QList<int> &context)
{
QAction *tmpaction = new QAction(parent);
tmpaction->setSeparator(true);
Command *cmd = am->registerAction(tmpaction, name, context);
return cmd;
}
void MainWindow::registerDefaultActions()
{
ActionManagerPrivate *am = m_actionManager;
ActionContainer *mfile = am->actionContainer(Constants::M_FILE);
ActionContainer *medit = am->actionContainer(Constants::M_EDIT);
ActionContainer *mtools = am->actionContainer(Constants::M_TOOLS);
ActionContainer *mwindow = am->actionContainer(Constants::M_WINDOW);
ActionContainer *mhelp = am->actionContainer(Constants::M_HELP);
// File menu separators
Command *cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Save"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_SAVE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Close"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_CLOSE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Other"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_OTHER);
// Edit menu separators
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.CopyPaste"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.SelectAll"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_SELECTALL);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Find"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_FIND);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Advanced"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_ADVANCED);
// Tools menu separators
cmd = createSeparator(am, this, QLatin1String("QtCreator.Tools.Sep.Options"), m_globalContext);
mtools->addAction(cmd, Constants::G_DEFAULT_THREE);
// Help menu separators
// Return to editor shortcut: Note this requires Qt to fix up
// handling of shortcut overrides in menus, item views, combos....
m_focusToEditor = new QShortcut(this);
cmd = am->registerShortcut(m_focusToEditor, Constants::S_RETURNTOEDITOR, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence(Qt::Key_Escape));
connect(m_focusToEditor, SIGNAL(activated()), this, SLOT(setFocusToEditor()));
// New File Action
/*
m_newAction = new QAction(QIcon(Constants::ICON_NEWFILE), tr("&New File or Project..."), this);
cmd = am->registerAction(m_newAction, Constants::NEW, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::New);
mfile->addAction(cmd, Constants::G_FILE_NEW);
connect(m_newAction, SIGNAL(triggered()), this, SLOT(newFile()));
*/
// Open Action
/*
m_openAction = new QAction(QIcon(Constants::ICON_OPENFILE), tr("&Open File or Project..."), this);
cmd = am->registerAction(m_openAction, Constants::OPEN, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Open);
mfile->addAction(cmd, Constants::G_FILE_OPEN);
connect(m_openAction, SIGNAL(triggered()), this, SLOT(openFile()));
*/
// Open With Action
/*
m_openWithAction = new QAction(tr("&Open File With..."), this);
cmd = am->registerAction(m_openWithAction, Constants::OPEN_WITH, m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_OPEN);
connect(m_openWithAction, SIGNAL(triggered()), this, SLOT(openFileWith()));
*/
// File->Recent Files Menu
/*
ActionContainer *ac = am->createMenu(Constants::M_FILE_RECENTFILES);
mfile->addMenu(ac, Constants::G_FILE_OPEN);
ac->menu()->setTitle(tr("Recent Files"));
*/
/*
// Save Action
QAction *tmpaction = new QAction(QIcon(Constants::ICON_SAVEFILE), tr("&Save"), this);
cmd = am->registerAction(tmpaction, Constants::SAVE, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Save);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Save"));
mfile->addAction(cmd, Constants::G_FILE_SAVE);
// Save As Action
tmpaction = new QAction(tr("Save &As..."), this);
cmd = am->registerAction(tmpaction, Constants::SAVEAS, m_globalContext);
#ifdef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+S")));
#endif
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("Save &As..."));
mfile->addAction(cmd, Constants::G_FILE_SAVE);
*/
// SaveAll Action
m_saveAllAction = new QAction(tr("Save A&ll"), this);
cmd = am->registerAction(m_saveAllAction, Constants::SAVEALL, m_globalContext);
#ifndef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+S")));
#endif
mfile->addAction(cmd, Constants::G_FILE_SAVE);
connect(m_saveAllAction, SIGNAL(triggered()), this, SLOT(saveAll()));
// Exit Action
m_exitAction = new QAction(QIcon(Constants::ICON_EXIT), tr("E&xit"), this);
cmd = am->registerAction(m_exitAction, Constants::EXIT, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Q")));
mfile->addAction(cmd, Constants::G_FILE_OTHER);
connect(m_exitAction, SIGNAL(triggered()), this, SLOT(exit()));
// Undo Action
QAction *tmpaction = new QAction(QIcon(Constants::ICON_UNDO), tr("&Undo"), this);
cmd = am->registerAction(tmpaction, Constants::UNDO, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Undo);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Undo"));
medit->addAction(cmd, Constants::G_EDIT_UNDOREDO);
tmpaction->setEnabled(false);
// Redo Action
tmpaction = new QAction(QIcon(Constants::ICON_REDO), tr("&Redo"), this);
cmd = am->registerAction(tmpaction, Constants::REDO, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Redo);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Redo"));
medit->addAction(cmd, Constants::G_EDIT_UNDOREDO);
tmpaction->setEnabled(false);
// Cut Action
tmpaction = new QAction(QIcon(Constants::ICON_CUT), tr("Cu&t"), this);
cmd = am->registerAction(tmpaction, Constants::CUT, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Cut);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Copy Action
tmpaction = new QAction(QIcon(Constants::ICON_COPY), tr("&Copy"), this);
cmd = am->registerAction(tmpaction, Constants::COPY, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Copy);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Paste Action
tmpaction = new QAction(QIcon(Constants::ICON_PASTE), tr("&Paste"), this);
cmd = am->registerAction(tmpaction, Constants::PASTE, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Paste);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Select All
tmpaction = new QAction(tr("&Select All"), this);
cmd = am->registerAction(tmpaction, Constants::SELECTALL, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::SelectAll);
medit->addAction(cmd, Constants::G_EDIT_SELECTALL);
tmpaction->setEnabled(false);
// Options Action
m_optionsAction = new QAction(QIcon(Constants::ICON_OPTIONS), tr("&Options..."), this);
cmd = am->registerAction(m_optionsAction, Constants::OPTIONS, m_globalContext);
#ifdef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence("Ctrl+,"));
cmd->action()->setMenuRole(QAction::PreferencesRole);
#endif
mtools->addAction(cmd, Constants::G_DEFAULT_THREE);
connect(m_optionsAction, SIGNAL(triggered()), this, SLOT(showOptionsDialog()));
#ifdef Q_WS_MAC
// Minimize Action
m_minimizeAction = new QAction(tr("Minimize"), this);
cmd = am->registerAction(m_minimizeAction, Constants::MINIMIZE_WINDOW, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence("Ctrl+M"));
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(showMinimized()));
// Zoom Action
m_zoomAction = new QAction(tr("Zoom"), this);
cmd = am->registerAction(m_zoomAction, Constants::ZOOM_WINDOW, m_globalContext);
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_zoomAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
// Window separator
cmd = createSeparator(am, this, QLatin1String("QtCreator.Window.Sep.Size"), m_globalContext);
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
#endif
#ifndef Q_WS_MAC
// Full Screen Action
m_toggleFullScreenAction = new QAction(tr("Full Screen"), this);
m_toggleFullScreenAction->setCheckable(true);
cmd = am->registerAction(m_toggleFullScreenAction, Constants::TOGGLE_FULLSCREEN, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence("Ctrl+Shift+F11"));
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_toggleFullScreenAction, SIGNAL(triggered(bool)), this, SLOT(setFullScreen(bool)));
#endif
//Help Action
tmpaction = new QAction(QIcon(Constants::ICON_HELP), tr("&Help..."), this);
cmd = am->registerAction(tmpaction, Constants::G_HELP_HELP, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_HELP);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutPlugins()));
// About sep
#ifndef Q_WS_MAC // doesn't have the "About" actions in the Help menu
tmpaction = new QAction(this);
tmpaction->setSeparator(true);
cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Help.Sep.About"), m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
#endif
//About Plugins Action
tmpaction = new QAction(QIcon(Constants::ICON_PLUGIN), tr("About &Plugins..."), this);
cmd = am->registerAction(tmpaction, Constants::ABOUT_PLUGINS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutPlugins()));
// About GCS Action
#ifdef Q_WS_MAC
tmpaction = new QAction(QIcon(Constants::ICON_OPENPILOT), tr("About &OpenPilot GCS"), this); // it's convention not to add dots to the about menu
#else
tmpaction = new QAction(QIcon(Constants::ICON_OPENPILOT), tr("About &OpenPilot GCS..."), this);
#endif
cmd = am->registerAction(tmpaction, Constants::ABOUT_OPENPILOTGCS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutOpenPilotGCS()));
//Credits Action
tmpaction = new QAction(QIcon(Constants::ICON_PLUGIN), tr("About &Authors..."), this);
cmd = am->registerAction(tmpaction, Constants::ABOUT_AUTHORS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutOpenPilotAuthors()));
}
void MainWindow::newFile()
{
}
void MainWindow::openFile()
{
}
/*static QList<IFileFactory*> getNonEditorFileFactories()
{
QList<IFileFactory*> tmp;
return tmp;
}
static IFileFactory *findFileFactory(const QList<IFileFactory*> &fileFactories,
const MimeDatabase *db,
const QFileInfo &fi)
{
if (const MimeType mt = db->findByFile(fi)) {
const QString type = mt.type();
foreach (IFileFactory *factory, fileFactories) {
if (factory->mimeTypes().contains(type))
return factory;
}
}
return 0;
}
// opens either an editor or loads a project
void MainWindow::openFiles(const QStringList &fileNames)
{
QList<IFileFactory*> nonEditorFileFactories = getNonEditorFileFactories();
foreach (const QString &fileName, fileNames) {
const QFileInfo fi(fileName);
const QString absoluteFilePath = fi.absoluteFilePath();
if (IFileFactory *fileFactory = findFileFactory(nonEditorFileFactories, mimeDatabase(), fi)) {
fileFactory->open(absoluteFilePath);
} else {
}
}
}*/
void MainWindow::setFocusToEditor()
{
}
bool MainWindow::showOptionsDialog(const QString &category,
const QString &page,
QWidget *parent)
{
emit m_coreImpl->optionsDialogRequested();
if (!parent)
parent = this;
SettingsDialog dlg(parent, category, page);
return dlg.execDialog();
}
void MainWindow::saveAll()
{
emit m_coreImpl->saveSettingsRequested();
saveSettings(); // OpenPilot-specific.
}
void MainWindow::exit()
{
// this function is most likely called from a user action
// that is from an event handler of an object
// since on close we are going to delete everything
// so to prevent the deleting of that object we
// just append it
QTimer::singleShot(0, this, SLOT(close()));
}
void MainWindow::openFileWith()
{
}
ActionManager *MainWindow::actionManager() const
{
return m_actionManager;
}
UniqueIDManager *MainWindow::uniqueIDManager() const
{
return m_uniqueIDManager;
}
MessageManager *MainWindow::messageManager() const
{
return m_messageManager;
}
QSettings *MainWindow::settings(QSettings::Scope scope) const
{
if (scope == QSettings::UserScope)
return m_settings;
else
return m_globalSettings;
}
VariableManager *MainWindow::variableManager() const
{
return m_variableManager;
}
ThreadManager *MainWindow::threadManager() const
{
return m_threadManager;
}
ConnectionManager *MainWindow::connectionManager() const
{
return m_connectionManager;
}
void MainWindow::addUAVGadgetManager(UAVGadgetManager *manager)
{
if (!m_uavGadgetManagers.contains(manager))
m_uavGadgetManagers.append(manager);
}
QList<UAVGadgetManager*> MainWindow::uavGadgetManagers() const
{
return m_uavGadgetManagers;
}
UAVGadgetInstanceManager *MainWindow::uavGadgetInstanceManager() const
{
return m_uavGadgetInstanceManager;
}
ModeManager *MainWindow::modeManager() const
{
return m_modeManager;
}
MimeDatabase *MainWindow::mimeDatabase() const
{
return m_mimeDatabase;
}
IContext *MainWindow::contextObject(QWidget *widget)
{
return m_contextWidgets.value(widget);
}
void MainWindow::addContextObject(IContext *context)
{
if (!context)
return;
QWidget *widget = context->widget();
if (m_contextWidgets.contains(widget))
return;
m_contextWidgets.insert(widget, context);
}
void MainWindow::removeContextObject(IContext *context)
{
if (!context)
return;
QWidget *widget = context->widget();
if (!m_contextWidgets.contains(widget))
return;
m_contextWidgets.remove(widget);
if (m_activeContext == context)
updateContextObject(0);
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
if (e->type() == QEvent::ActivationChange) {
if (isActiveWindow()) {
if (debugMainWindow)
qDebug() << "main window activated";
emit windowActivated();
}
} else if (e->type() == QEvent::WindowStateChange) {
#ifdef Q_WS_MAC
bool minimized = isMinimized();
if (debugMainWindow)
qDebug() << "main window state changed to minimized=" << minimized;
m_minimizeAction->setEnabled(!minimized);
m_zoomAction->setEnabled(!minimized);
#else
bool isFullScreen = (windowState() & Qt::WindowFullScreen) != 0;
m_toggleFullScreenAction->setChecked(isFullScreen);
#endif
}
}
void MainWindow::updateFocusWidget(QWidget *old, QWidget *now)
{
Q_UNUSED(old)
// Prevent changing the context object just because the menu is activated
if (qobject_cast<QMenuBar*>(now))
return;
IContext *newContext = 0;
if (focusWidget()) {
IContext *context = 0;
QWidget *p = focusWidget();
while (p) {
context = m_contextWidgets.value(p);
if (context) {
newContext = context;
break;
}
p = p->parentWidget();
}
}
updateContextObject(newContext);
}
void MainWindow::updateContextObject(IContext *context)
{
if (context == m_activeContext)
return;
IContext *oldContext = m_activeContext;
m_activeContext = context;
if (!context || oldContext != m_activeContext) {
emit m_coreImpl->contextAboutToChange(context);
updateContext();
if (debugMainWindow)
qDebug() << "new context object =" << context << (context ? context->widget() : 0)
<< (context ? context->widget()->metaObject()->className() : 0);
emit m_coreImpl->contextChanged(context);
}
}
void MainWindow::resetContext()
{
updateContextObject(0);
}
void MainWindow::shutdown()
{
disconnect(QApplication::instance(), SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateFocusWidget(QWidget*,QWidget*)));
m_activeContext = 0;
}
void MainWindow::createWorkspaces() {
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVGadgetMode *uavGadgetMode;
Core::UAVGadgetManager *uavGadgetManager;
while (!m_uavGadgetModes.isEmpty()){
pm->removeObject(m_uavGadgetModes.takeFirst());
}
while (!m_uavGadgetManagers.isEmpty()){
Core::UAVGadgetManager* uavGadgetManager = m_uavGadgetManagers.takeLast();
uavGadgetManager->removeAllSplits();
// TODO Fixthis: This only happens, when settings are reloaded.
// then the old GadgetManagers should be deleted, but if
// I delete them the GCS segfaults.
//delete uavGadgetManager;
}
m_uavGadgetManagers.clear();
m_uavGadgetModes.clear();
for (int i = 0; i < m_workspaceSettings->numberOfWorkspaces(); ++i) {
uavGadgetManager = new Core::UAVGadgetManager(CoreImpl::instance(), this);
uavGadgetManager->hide();
const QString name = m_workspaceSettings->name(i);
const QString iconName = m_workspaceSettings->iconName(i);
const QString modeName = m_workspaceSettings->modeName(i);
uavGadgetMode = new UAVGadgetMode(uavGadgetManager, name,
QIcon(iconName), 90-i+1, modeName);
uavGadgetManager->setUAVGadgetMode(uavGadgetMode);
m_uavGadgetModes.append(uavGadgetMode);
pm->addObject(uavGadgetMode);
addUAVGadgetManager(uavGadgetManager);
}
}
static const char *settingsGroup = "MainWindow";
static const char *geometryKey = "Geometry";
static const char *colorKey = "Color";
static const char *maxKey = "Maximized";
static const char *fullScreenKey = "FullScreen";
void MainWindow::readSettings()
{
readSettings(m_settings);
}
void MainWindow::readSettings(QSettings* qs)
{
m_actionManager->readSettings(qs);
qs->beginGroup(QLatin1String(settingsGroup));
Utils::StyleHelper::setBaseColor(qs->value(QLatin1String(colorKey)).value<QColor>());
const QVariant geom = qs->value(QLatin1String(geometryKey));
if (geom.isValid()) {
setGeometry(geom.toRect());
} else {
resize(750, 400);
}
if (qs->value(QLatin1String(maxKey), false).toBool())
setWindowState(Qt::WindowMaximized);
setFullScreen(qs->value(QLatin1String(fullScreenKey), false).toBool());
qs->endGroup();
m_workspaceSettings->readSettings(qs);
createWorkspaces();
foreach (UAVGadgetManager *manager, m_uavGadgetManagers) {
manager->readSettings(qs);
}
m_viewManager->readSettings(qs);
}
void MainWindow::saveSettings()
{
saveSettings(m_settings);
}
void MainWindow::saveSettings(QSettings* qs)
{
m_workspaceSettings->saveSettings(qs);
qs->beginGroup(QLatin1String(settingsGroup));
qs->setValue(QLatin1String(colorKey), Utils::StyleHelper::baseColor());
if (windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen)) {
qs->setValue(QLatin1String(maxKey), (bool) (windowState() & Qt::WindowMaximized));
qs->setValue(QLatin1String(fullScreenKey), (bool) (windowState() & Qt::WindowFullScreen));
} else {
qs->setValue(QLatin1String(maxKey), false);
qs->setValue(QLatin1String(fullScreenKey), false);
qs->setValue(QLatin1String(geometryKey), geometry());
}
qs->endGroup();
foreach (UAVGadgetManager *manager, m_uavGadgetManagers) {
manager->saveSettings(qs);
}
m_viewManager->saveSettings(qs);
m_actionManager->saveSettings(qs);
}
void MainWindow::addAdditionalContext(int context)
{
if (context == 0)
return;
if (!m_additionalContexts.contains(context))
m_additionalContexts.prepend(context);
}
void MainWindow::removeAdditionalContext(int context)
{
if (context == 0)
return;
int index = m_additionalContexts.indexOf(context);
if (index != -1)
m_additionalContexts.removeAt(index);
}
bool MainWindow::hasContext(int context) const
{
return m_actionManager->hasContext(context);
}
void MainWindow::updateContext()
{
QList<int> contexts;
if (m_activeContext)
contexts += m_activeContext->context();
contexts += m_additionalContexts;
QList<int> uniquecontexts;
for (int i = 0; i < contexts.size(); ++i) {
const int c = contexts.at(i);
if (!uniquecontexts.contains(c))
uniquecontexts << c;
}
m_actionManager->setContext(uniquecontexts);
}
void MainWindow::aboutToShowRecentFiles()
{
ActionContainer *aci =
m_actionManager->actionContainer(Constants::M_FILE_RECENTFILES);
if (aci) {
aci->menu()->clear();
bool hasRecentFiles = false;
aci->menu()->setEnabled(hasRecentFiles);
}
}
void MainWindow::openRecentFile()
{
QAction *action = qobject_cast<QAction*>(sender());
if (!action)
return;
QString fileName = action->data().toString();
if (!fileName.isEmpty()) {
}
}
void MainWindow::aboutOpenPilotGCS()
{
if (!m_versionDialog) {
m_versionDialog = new VersionDialog(this);
connect(m_versionDialog, SIGNAL(finished(int)),
this, SLOT(destroyVersionDialog()));
}
m_versionDialog->show();
}
void MainWindow::destroyVersionDialog()
{
if (m_versionDialog) {
m_versionDialog->deleteLater();
m_versionDialog = 0;
}
}
void MainWindow::aboutOpenPilotAuthors()
{
if (!m_authorsDialog) {
m_authorsDialog = new AuthorsDialog(this);
connect(m_authorsDialog, SIGNAL(finished(int)),
this, SLOT(destroyAuthorsDialog()));
}
m_authorsDialog->show();
}
void MainWindow::destroyAuthorsDialog()
{
if (m_authorsDialog) {
m_authorsDialog->deleteLater();
m_authorsDialog = 0;
}
}
void MainWindow::aboutPlugins()
{
PluginDialog dialog(this);
dialog.exec();
}
void MainWindow::setFullScreen(bool on)
{
if (bool(windowState() & Qt::WindowFullScreen) == on)
return;
if (on) {
setWindowState(windowState() | Qt::WindowFullScreen);
//statusBar()->hide();
//menuBar()->hide();
} else {
setWindowState(windowState() & ~Qt::WindowFullScreen);
//menuBar()->show();
//statusBar()->show();
}
}
// Display a warning with an additional button to open
// the debugger settings dialog if settingsId is nonempty.
bool MainWindow::showWarningWithOptions(const QString &title,
const QString &text,
const QString &details,
const QString &settingsCategory,
const QString &settingsId,
QWidget *parent)
{
if (parent == 0)
parent = this;
QMessageBox msgBox(QMessageBox::Warning, title, text,
QMessageBox::Ok, parent);
if (details.isEmpty())
msgBox.setDetailedText(details);
QAbstractButton *settingsButton = 0;
if (!settingsId.isEmpty() || !settingsCategory.isEmpty())
settingsButton = msgBox.addButton(tr("Settings..."), QMessageBox::AcceptRole);
msgBox.exec();
if (settingsButton && msgBox.clickedButton() == settingsButton) {
return showOptionsDialog(settingsCategory, settingsId);
}
return false;
}
/**
******************************************************************************
*
* @file mainwindow.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 "mainwindow.h"
#include "actioncontainer.h"
#include "actionmanager_p.h"
#include "basemode.h"
#include "coreimpl.h"
#include "coreconstants.h"
#include "fancytabwidget.h"
#include "generalsettings.h"
#include "messagemanager.h"
#include "modemanager.h"
#include "mimedatabase.h"
#include "outputpane.h"
#include "plugindialog.h"
#include "shortcutsettings.h"
#include "workspacesettings.h"
#include "modemanager.h"
#include "uavgadgetmode.h"
#include "uavgadgetmanager.h"
#include "uavgadgetinstancemanager.h"
#include "connectionmanager.h"
#include "qxtlogger.h"
#include "qxtbasicstdloggerengine.h"
#include "settingsdialog.h"
#include "variablemanager.h"
#include "threadmanager.h"
#include "versiondialog.h"
#include "authorsdialog.h"
#include "viewmanager.h"
#include "uniqueidmanager.h"
#include "manhattanstyle.h"
#include "dialogs/iwizard.h"
#include "rightpane.h"
#include "baseview.h"
#include "ioutputpane.h"
#include "icorelistener.h"
#include "iconfigurableplugin.h"
#include <coreplugin/settingsdatabase.h>
#include <utils/pathchooser.h>
#include <utils/stylehelper.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtCore/QtPlugin>
#include <QtCore/QUrl>
#include <QtGui/QApplication>
#include <QtGui/QCloseEvent>
#include <QtGui/QMenu>
#include <QtGui/QPixmap>
#include <QtGui/QShortcut>
#include <QtGui/QStatusBar>
#include <QtGui/QWizard>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
/*
#ifdef Q_OS_UNIX
#include <signal.h>
extern "C" void handleSigInt(int sig)
{
Q_UNUSED(sig)
Core::ICore::instance()->exit();
qDebug() << "SIGINT caught. Shutting down.";
}
#endif
*/
using namespace Core;
using namespace Core::Internal;
static const char *uriListMimeFormatC = "text/uri-list";
enum { debugMainWindow = 0 };
MainWindow::MainWindow() :
EventFilteringMainWindow(),
m_coreImpl(new CoreImpl(this)),
m_uniqueIDManager(new UniqueIDManager()),
m_globalContext(QList<int>() << Constants::C_GLOBAL_ID),
m_additionalContexts(m_globalContext),
// keep this in sync with main() in app/main.cpp
m_settings(new QSettings(QSettings::IniFormat, QSettings::UserScope,
QLatin1String("OpenPilot"), QLatin1String("OpenPilotGCS"), this)),
m_globalSettings(new QSettings(QSettings::IniFormat, QSettings::SystemScope,
QLatin1String("OpenPilot"), QLatin1String("OpenPilotGCS"), this)),
m_settingsDatabase(new SettingsDatabase(QFileInfo(m_settings->fileName()).path(),
QLatin1String("OpenPilotGCS"),
this)),
m_actionManager(new ActionManagerPrivate(this)),
m_variableManager(new VariableManager(this)),
m_threadManager(new ThreadManager(this)),
m_viewManager(0),
m_modeManager(0),
m_connectionManager(0),
m_mimeDatabase(new MimeDatabase),
// m_rightPaneWidget(0),
m_versionDialog(0),
m_authorsDialog(0),
m_activeContext(0),
m_generalSettings(new GeneralSettings),
m_shortcutSettings(new ShortcutSettings),
m_workspaceSettings(new WorkspaceSettings),
m_focusToEditor(0),
m_newAction(0),
m_openAction(0),
m_openWithAction(0),
m_saveAllAction(0),
m_exitAction(0),
m_optionsAction(0),
#ifdef Q_WS_MAC
m_minimizeAction(0),
m_zoomAction(0),
#endif
m_toggleFullScreenAction(0)
{
setWindowTitle(tr("OpenPilot GCS"));
#ifndef Q_WS_MAC
qApp->setWindowIcon(QIcon(":/core/images/openpilot_logo_128.png"));
#endif
QCoreApplication::setApplicationName(QLatin1String("OpenPilotGCS"));
QCoreApplication::setApplicationVersion(QLatin1String(Core::Constants::GCS_VERSION_LONG));
QCoreApplication::setOrganizationName(QLatin1String("OpenPilot"));
QCoreApplication::setOrganizationDomain(QLatin1String("openpilot.org"));
QSettings::setDefaultFormat(QSettings::IniFormat);
QString baseName = qApp->style()->objectName();
#ifdef Q_WS_X11
if (baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
baseName = QLatin1String("plastique");
else
baseName = QLatin1String("cleanlooks");
}
#endif
qApp->setStyle(new ManhattanStyle(baseName));
setDockNestingEnabled(true);
setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
registerDefaultContainers();
registerDefaultActions();
m_modeStack = new FancyTabWidget(this);
m_modeManager = new ModeManager(this, m_modeStack);
m_connectionManager = new ConnectionManager(this, m_modeStack);
m_viewManager = new ViewManager(this);
m_messageManager = new MessageManager;
setCentralWidget(m_modeStack);
connect(QApplication::instance(), SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateFocusWidget(QWidget*,QWidget*)));
// setUnifiedTitleAndToolBarOnMac(true);
#ifdef Q_OS_UNIX
//signal(SIGINT, handleSigInt);
#endif
statusBar()->setProperty("p_styled", true);
setAcceptDrops(true);
foreach (QString engine, qxtLog->allLoggerEngines())
qxtLog->removeLoggerEngine(engine);
qxtLog->addLoggerEngine("std", new QxtBasicSTDLoggerEngine());
qxtLog->installAsMessageHandler();
qxtLog->enableAllLogLevels();
}
MainWindow::~MainWindow()
{
hide();
qxtLog->removeAsMessageHandler();
foreach (QString engine, qxtLog->allLoggerEngines())
qxtLog->removeLoggerEngine(engine);
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
if (m_uavGadgetModes.count() > 0) {
foreach (UAVGadgetMode *mode, m_uavGadgetModes)
{
pm->removeObject(mode);
delete mode;
}
}
pm->removeObject(m_shortcutSettings);
pm->removeObject(m_generalSettings);
pm->removeObject(m_workspaceSettings);
delete m_messageManager;
m_messageManager = 0;
delete m_shortcutSettings;
m_shortcutSettings = 0;
delete m_generalSettings;
m_generalSettings = 0;
delete m_workspaceSettings;
m_workspaceSettings = 0;
delete m_settings;
m_settings = 0;
delete m_uniqueIDManager;
m_uniqueIDManager = 0;
delete m_viewManager;
m_viewManager = 0;
pm->removeObject(m_coreImpl);
delete m_coreImpl;
m_coreImpl = 0;
// delete m_rightPaneWidget;
// m_rightPaneWidget = 0;
delete m_modeManager;
m_modeManager = 0;
delete m_mimeDatabase;
m_mimeDatabase = 0;
}
bool MainWindow::init(QString *errorMessage)
{
Q_UNUSED(errorMessage)
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
pm->addObject(m_coreImpl);
m_viewManager->init();
m_modeManager->init();
m_connectionManager->init();
pm->addObject(m_generalSettings);
pm->addObject(m_shortcutSettings);
pm->addObject(m_workspaceSettings);
return true;
}
void MainWindow::modeChanged(Core::IMode */*mode*/)
{
}
void MainWindow::extensionsInitialized()
{
QSettings* qs = m_settings;
QSettings defaultSettings(":/core/OpenPilotGCS.ini", QSettings::IniFormat);
if ( ! qs->allKeys().count() ){
qDebug() << "There is no config, load default config from resource /core/OpenPilotGCS.ini";
qs = &defaultSettings;
}
// qDebug() << "Number of keys in config: " << qs->allKeys().count();
m_uavGadgetInstanceManager = new UAVGadgetInstanceManager(this);
m_uavGadgetInstanceManager->readConfigurations(qs);
m_messageManager->init();
readSettings(qs);
updateContext();
emit m_coreImpl->coreAboutToOpen();
show();
emit m_coreImpl->coreOpened();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
emit m_coreImpl->saveSettingsRequested();
const QList<ICoreListener *> listeners =
ExtensionSystem::PluginManager::instance()->getObjects<ICoreListener>();
foreach (ICoreListener *listener, listeners) {
if (!listener->coreAboutToClose()) {
event->ignore();
return;
}
}
emit m_coreImpl->coreAboutToClose();
saveSettings(m_settings);
m_uavGadgetInstanceManager->writeConfigurations(m_settings);
event->accept();
}
// Check for desktop file manager file drop events
static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
{
if (files)
files->clear();
// Extract dropped files from Mime data.
if (!d->hasFormat(QLatin1String(uriListMimeFormatC)))
return false;
const QList<QUrl> urls = d->urls();
if (urls.empty())
return false;
// Try to find local files
bool hasFiles = false;
const QList<QUrl>::const_iterator cend = urls.constEnd();
for (QList<QUrl>::const_iterator it = urls.constBegin(); it != cend; ++it) {
const QString fileName = it->toLocalFile();
if (!fileName.isEmpty()) {
hasFiles = true;
if (files) {
files->push_back(fileName);
} else {
break; // No result list, sufficient for checking
}
}
}
return hasFiles;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (isDesktopFileManagerDrop(event->mimeData())) {
event->accept();
} else {
event->ignore();
}
}
void MainWindow::dropEvent(QDropEvent *event)
{
QStringList files;
if (isDesktopFileManagerDrop(event->mimeData(), &files)) {
event->accept();
//openFiles(files);
} else {
event->ignore();
}
}
IContext *MainWindow::currentContextObject() const
{
return m_activeContext;
}
QStatusBar *MainWindow::statusBar() const
{
return m_modeStack->statusBar();
}
void MainWindow::registerDefaultContainers()
{
ActionManagerPrivate *am = m_actionManager;
ActionContainer *menubar = am->createMenuBar(Constants::MENU_BAR);
#ifndef Q_WS_MAC // System menu bar on Mac
setMenuBar(menubar->menuBar());
#endif
menubar->appendGroup(Constants::G_FILE);
menubar->appendGroup(Constants::G_EDIT);
menubar->appendGroup(Constants::G_VIEW);
menubar->appendGroup(Constants::G_TOOLS);
menubar->appendGroup(Constants::G_WINDOW);
menubar->appendGroup(Constants::G_HELP);
// File Menu
ActionContainer *filemenu = am->createMenu(Constants::M_FILE);
menubar->addMenu(filemenu, Constants::G_FILE);
filemenu->menu()->setTitle(tr("&File"));
filemenu->appendGroup(Constants::G_FILE_NEW);
filemenu->appendGroup(Constants::G_FILE_OPEN);
filemenu->appendGroup(Constants::G_FILE_PROJECT);
filemenu->appendGroup(Constants::G_FILE_SAVE);
filemenu->appendGroup(Constants::G_FILE_CLOSE);
filemenu->appendGroup(Constants::G_FILE_OTHER);
connect(filemenu->menu(), SIGNAL(aboutToShow()), this, SLOT(aboutToShowRecentFiles()));
// Edit Menu
ActionContainer *medit = am->createMenu(Constants::M_EDIT);
menubar->addMenu(medit, Constants::G_EDIT);
medit->menu()->setTitle(tr("&Edit"));
medit->appendGroup(Constants::G_EDIT_UNDOREDO);
medit->appendGroup(Constants::G_EDIT_COPYPASTE);
medit->appendGroup(Constants::G_EDIT_SELECTALL);
medit->appendGroup(Constants::G_EDIT_ADVANCED);
medit->appendGroup(Constants::G_EDIT_FIND);
medit->appendGroup(Constants::G_EDIT_OTHER);
// Tools Menu
ActionContainer *ac = am->createMenu(Constants::M_TOOLS);
menubar->addMenu(ac, Constants::G_TOOLS);
ac->menu()->setTitle(tr("&Tools"));
// Window Menu
ActionContainer *mwindow = am->createMenu(Constants::M_WINDOW);
menubar->addMenu(mwindow, Constants::G_WINDOW);
mwindow->menu()->setTitle(tr("&Window"));
mwindow->appendGroup(Constants::G_WINDOW_SIZE);
mwindow->appendGroup(Constants::G_WINDOW_HIDE_TOOLBAR);
mwindow->appendGroup(Constants::G_WINDOW_PANES);
mwindow->appendGroup(Constants::G_WINDOW_SPLIT);
mwindow->appendGroup(Constants::G_WINDOW_NAVIGATE);
mwindow->appendGroup(Constants::G_WINDOW_OTHER);
// Help Menu
ac = am->createMenu(Constants::M_HELP);
menubar->addMenu(ac, Constants::G_HELP);
ac->menu()->setTitle(tr("&Help"));
ac->appendGroup(Constants::G_HELP_HELP);
ac->appendGroup(Constants::G_HELP_ABOUT);
}
static Command *createSeparator(ActionManager *am, QObject *parent,
const QString &name,
const QList<int> &context)
{
QAction *tmpaction = new QAction(parent);
tmpaction->setSeparator(true);
Command *cmd = am->registerAction(tmpaction, name, context);
return cmd;
}
void MainWindow::registerDefaultActions()
{
ActionManagerPrivate *am = m_actionManager;
ActionContainer *mfile = am->actionContainer(Constants::M_FILE);
ActionContainer *medit = am->actionContainer(Constants::M_EDIT);
ActionContainer *mtools = am->actionContainer(Constants::M_TOOLS);
ActionContainer *mwindow = am->actionContainer(Constants::M_WINDOW);
ActionContainer *mhelp = am->actionContainer(Constants::M_HELP);
// File menu separators
Command *cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Save"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_SAVE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Close"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_CLOSE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.File.Sep.Other"), m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_OTHER);
// Edit menu separators
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.CopyPaste"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.SelectAll"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_SELECTALL);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Find"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_FIND);
cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Advanced"), m_globalContext);
medit->addAction(cmd, Constants::G_EDIT_ADVANCED);
// Tools menu separators
cmd = createSeparator(am, this, QLatin1String("QtCreator.Tools.Sep.Options"), m_globalContext);
mtools->addAction(cmd, Constants::G_DEFAULT_THREE);
// Help menu separators
// Return to editor shortcut: Note this requires Qt to fix up
// handling of shortcut overrides in menus, item views, combos....
m_focusToEditor = new QShortcut(this);
cmd = am->registerShortcut(m_focusToEditor, Constants::S_RETURNTOEDITOR, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence(Qt::Key_Escape));
connect(m_focusToEditor, SIGNAL(activated()), this, SLOT(setFocusToEditor()));
// New File Action
/*
m_newAction = new QAction(QIcon(Constants::ICON_NEWFILE), tr("&New File or Project..."), this);
cmd = am->registerAction(m_newAction, Constants::NEW, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::New);
mfile->addAction(cmd, Constants::G_FILE_NEW);
connect(m_newAction, SIGNAL(triggered()), this, SLOT(newFile()));
*/
// Open Action
/*
m_openAction = new QAction(QIcon(Constants::ICON_OPENFILE), tr("&Open File or Project..."), this);
cmd = am->registerAction(m_openAction, Constants::OPEN, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Open);
mfile->addAction(cmd, Constants::G_FILE_OPEN);
connect(m_openAction, SIGNAL(triggered()), this, SLOT(openFile()));
*/
// Open With Action
/*
m_openWithAction = new QAction(tr("&Open File With..."), this);
cmd = am->registerAction(m_openWithAction, Constants::OPEN_WITH, m_globalContext);
mfile->addAction(cmd, Constants::G_FILE_OPEN);
connect(m_openWithAction, SIGNAL(triggered()), this, SLOT(openFileWith()));
*/
// File->Recent Files Menu
/*
ActionContainer *ac = am->createMenu(Constants::M_FILE_RECENTFILES);
mfile->addMenu(ac, Constants::G_FILE_OPEN);
ac->menu()->setTitle(tr("Recent Files"));
*/
/*
// Save Action
QAction *tmpaction = new QAction(QIcon(Constants::ICON_SAVEFILE), tr("&Save"), this);
cmd = am->registerAction(tmpaction, Constants::SAVE, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Save);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Save"));
mfile->addAction(cmd, Constants::G_FILE_SAVE);
// Save As Action
tmpaction = new QAction(tr("Save &As..."), this);
cmd = am->registerAction(tmpaction, Constants::SAVEAS, m_globalContext);
#ifdef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+S")));
#endif
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("Save &As..."));
mfile->addAction(cmd, Constants::G_FILE_SAVE);
*/
// SaveAll Action
m_saveAllAction = new QAction(tr("Save A&ll"), this);
cmd = am->registerAction(m_saveAllAction, Constants::SAVEALL, m_globalContext);
#ifndef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+S")));
#endif
mfile->addAction(cmd, Constants::G_FILE_SAVE);
connect(m_saveAllAction, SIGNAL(triggered()), this, SLOT(saveAll()));
// Exit Action
m_exitAction = new QAction(QIcon(Constants::ICON_EXIT), tr("E&xit"), this);
cmd = am->registerAction(m_exitAction, Constants::EXIT, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Q")));
mfile->addAction(cmd, Constants::G_FILE_OTHER);
connect(m_exitAction, SIGNAL(triggered()), this, SLOT(exit()));
// Undo Action
QAction *tmpaction = new QAction(QIcon(Constants::ICON_UNDO), tr("&Undo"), this);
cmd = am->registerAction(tmpaction, Constants::UNDO, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Undo);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Undo"));
medit->addAction(cmd, Constants::G_EDIT_UNDOREDO);
tmpaction->setEnabled(false);
// Redo Action
tmpaction = new QAction(QIcon(Constants::ICON_REDO), tr("&Redo"), this);
cmd = am->registerAction(tmpaction, Constants::REDO, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Redo);
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultText(tr("&Redo"));
medit->addAction(cmd, Constants::G_EDIT_UNDOREDO);
tmpaction->setEnabled(false);
// Cut Action
tmpaction = new QAction(QIcon(Constants::ICON_CUT), tr("Cu&t"), this);
cmd = am->registerAction(tmpaction, Constants::CUT, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Cut);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Copy Action
tmpaction = new QAction(QIcon(Constants::ICON_COPY), tr("&Copy"), this);
cmd = am->registerAction(tmpaction, Constants::COPY, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Copy);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Paste Action
tmpaction = new QAction(QIcon(Constants::ICON_PASTE), tr("&Paste"), this);
cmd = am->registerAction(tmpaction, Constants::PASTE, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::Paste);
medit->addAction(cmd, Constants::G_EDIT_COPYPASTE);
tmpaction->setEnabled(false);
// Select All
tmpaction = new QAction(tr("&Select All"), this);
cmd = am->registerAction(tmpaction, Constants::SELECTALL, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence::SelectAll);
medit->addAction(cmd, Constants::G_EDIT_SELECTALL);
tmpaction->setEnabled(false);
// Options Action
m_optionsAction = new QAction(QIcon(Constants::ICON_OPTIONS), tr("&Options..."), this);
cmd = am->registerAction(m_optionsAction, Constants::OPTIONS, m_globalContext);
#ifdef Q_WS_MAC
cmd->setDefaultKeySequence(QKeySequence("Ctrl+,"));
cmd->action()->setMenuRole(QAction::PreferencesRole);
#endif
mtools->addAction(cmd, Constants::G_DEFAULT_THREE);
connect(m_optionsAction, SIGNAL(triggered()), this, SLOT(showOptionsDialog()));
#ifdef Q_WS_MAC
// Minimize Action
m_minimizeAction = new QAction(tr("Minimize"), this);
cmd = am->registerAction(m_minimizeAction, Constants::MINIMIZE_WINDOW, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence("Ctrl+M"));
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(showMinimized()));
// Zoom Action
m_zoomAction = new QAction(tr("Zoom"), this);
cmd = am->registerAction(m_zoomAction, Constants::ZOOM_WINDOW, m_globalContext);
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_zoomAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
// Window separator
cmd = createSeparator(am, this, QLatin1String("QtCreator.Window.Sep.Size"), m_globalContext);
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
#endif
#ifndef Q_WS_MAC
// Full Screen Action
m_toggleFullScreenAction = new QAction(tr("Full Screen"), this);
m_toggleFullScreenAction->setCheckable(true);
cmd = am->registerAction(m_toggleFullScreenAction, Constants::TOGGLE_FULLSCREEN, m_globalContext);
cmd->setDefaultKeySequence(QKeySequence("Ctrl+Shift+F11"));
mwindow->addAction(cmd, Constants::G_WINDOW_SIZE);
connect(m_toggleFullScreenAction, SIGNAL(triggered(bool)), this, SLOT(setFullScreen(bool)));
#endif
//Help Action
tmpaction = new QAction(QIcon(Constants::ICON_HELP), tr("&Help..."), this);
cmd = am->registerAction(tmpaction, Constants::G_HELP_HELP, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_HELP);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutPlugins()));
// About sep
#ifndef Q_WS_MAC // doesn't have the "About" actions in the Help menu
tmpaction = new QAction(this);
tmpaction->setSeparator(true);
cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Help.Sep.About"), m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
#endif
//About Plugins Action
tmpaction = new QAction(QIcon(Constants::ICON_PLUGIN), tr("About &Plugins..."), this);
cmd = am->registerAction(tmpaction, Constants::ABOUT_PLUGINS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutPlugins()));
// About GCS Action
#ifdef Q_WS_MAC
tmpaction = new QAction(QIcon(Constants::ICON_OPENPILOT), tr("About &OpenPilot GCS"), this); // it's convention not to add dots to the about menu
#else
tmpaction = new QAction(QIcon(Constants::ICON_OPENPILOT), tr("About &OpenPilot GCS..."), this);
#endif
cmd = am->registerAction(tmpaction, Constants::ABOUT_OPENPILOTGCS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutOpenPilotGCS()));
//Credits Action
tmpaction = new QAction(QIcon(Constants::ICON_PLUGIN), tr("About &Authors..."), this);
cmd = am->registerAction(tmpaction, Constants::ABOUT_AUTHORS, m_globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
#ifdef Q_WS_MAC
cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
#endif
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutOpenPilotAuthors()));
}
void MainWindow::newFile()
{
}
void MainWindow::openFile()
{
}
/*static QList<IFileFactory*> getNonEditorFileFactories()
{
QList<IFileFactory*> tmp;
return tmp;
}
static IFileFactory *findFileFactory(const QList<IFileFactory*> &fileFactories,
const MimeDatabase *db,
const QFileInfo &fi)
{
if (const MimeType mt = db->findByFile(fi)) {
const QString type = mt.type();
foreach (IFileFactory *factory, fileFactories) {
if (factory->mimeTypes().contains(type))
return factory;
}
}
return 0;
}
// opens either an editor or loads a project
void MainWindow::openFiles(const QStringList &fileNames)
{
QList<IFileFactory*> nonEditorFileFactories = getNonEditorFileFactories();
foreach (const QString &fileName, fileNames) {
const QFileInfo fi(fileName);
const QString absoluteFilePath = fi.absoluteFilePath();
if (IFileFactory *fileFactory = findFileFactory(nonEditorFileFactories, mimeDatabase(), fi)) {
fileFactory->open(absoluteFilePath);
} else {
}
}
}*/
void MainWindow::setFocusToEditor()
{
}
bool MainWindow::showOptionsDialog(const QString &category,
const QString &page,
QWidget *parent)
{
emit m_coreImpl->optionsDialogRequested();
if (!parent)
parent = this;
SettingsDialog dlg(parent, category, page);
return dlg.execDialog();
}
void MainWindow::saveAll()
{
emit m_coreImpl->saveSettingsRequested();
saveSettings(); // OpenPilot-specific.
}
void MainWindow::exit()
{
// this function is most likely called from a user action
// that is from an event handler of an object
// since on close we are going to delete everything
// so to prevent the deleting of that object we
// just append it
QTimer::singleShot(0, this, SLOT(close()));
}
void MainWindow::openFileWith()
{
}
ActionManager *MainWindow::actionManager() const
{
return m_actionManager;
}
UniqueIDManager *MainWindow::uniqueIDManager() const
{
return m_uniqueIDManager;
}
MessageManager *MainWindow::messageManager() const
{
return m_messageManager;
}
QSettings *MainWindow::settings(QSettings::Scope scope) const
{
if (scope == QSettings::UserScope)
return m_settings;
else
return m_globalSettings;
}
VariableManager *MainWindow::variableManager() const
{
return m_variableManager;
}
ThreadManager *MainWindow::threadManager() const
{
return m_threadManager;
}
ConnectionManager *MainWindow::connectionManager() const
{
return m_connectionManager;
}
void MainWindow::addUAVGadgetManager(UAVGadgetManager *manager)
{
if (!m_uavGadgetManagers.contains(manager))
m_uavGadgetManagers.append(manager);
}
QList<UAVGadgetManager*> MainWindow::uavGadgetManagers() const
{
return m_uavGadgetManagers;
}
UAVGadgetInstanceManager *MainWindow::uavGadgetInstanceManager() const
{
return m_uavGadgetInstanceManager;
}
ModeManager *MainWindow::modeManager() const
{
return m_modeManager;
}
MimeDatabase *MainWindow::mimeDatabase() const
{
return m_mimeDatabase;
}
IContext *MainWindow::contextObject(QWidget *widget)
{
return m_contextWidgets.value(widget);
}
void MainWindow::addContextObject(IContext *context)
{
if (!context)
return;
QWidget *widget = context->widget();
if (m_contextWidgets.contains(widget))
return;
m_contextWidgets.insert(widget, context);
}
void MainWindow::removeContextObject(IContext *context)
{
if (!context)
return;
QWidget *widget = context->widget();
if (!m_contextWidgets.contains(widget))
return;
m_contextWidgets.remove(widget);
if (m_activeContext == context)
updateContextObject(0);
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
if (e->type() == QEvent::ActivationChange) {
if (isActiveWindow()) {
if (debugMainWindow)
qDebug() << "main window activated";
emit windowActivated();
}
} else if (e->type() == QEvent::WindowStateChange) {
#ifdef Q_WS_MAC
bool minimized = isMinimized();
if (debugMainWindow)
qDebug() << "main window state changed to minimized=" << minimized;
m_minimizeAction->setEnabled(!minimized);
m_zoomAction->setEnabled(!minimized);
#else
bool isFullScreen = (windowState() & Qt::WindowFullScreen) != 0;
m_toggleFullScreenAction->setChecked(isFullScreen);
#endif
}
}
void MainWindow::updateFocusWidget(QWidget *old, QWidget *now)
{
Q_UNUSED(old)
// Prevent changing the context object just because the menu is activated
if (qobject_cast<QMenuBar*>(now))
return;
IContext *newContext = 0;
if (focusWidget()) {
IContext *context = 0;
QWidget *p = focusWidget();
while (p) {
context = m_contextWidgets.value(p);
if (context) {
newContext = context;
break;
}
p = p->parentWidget();
}
}
updateContextObject(newContext);
}
void MainWindow::updateContextObject(IContext *context)
{
if (context == m_activeContext)
return;
IContext *oldContext = m_activeContext;
m_activeContext = context;
if (!context || oldContext != m_activeContext) {
emit m_coreImpl->contextAboutToChange(context);
updateContext();
if (debugMainWindow)
qDebug() << "new context object =" << context << (context ? context->widget() : 0)
<< (context ? context->widget()->metaObject()->className() : 0);
emit m_coreImpl->contextChanged(context);
}
}
void MainWindow::resetContext()
{
updateContextObject(0);
}
void MainWindow::shutdown()
{
disconnect(QApplication::instance(), SIGNAL(focusChanged(QWidget*,QWidget*)),
this, SLOT(updateFocusWidget(QWidget*,QWidget*)));
m_activeContext = 0;
}
void MainWindow::createWorkspaces() {
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVGadgetMode *uavGadgetMode;
Core::UAVGadgetManager *uavGadgetManager;
while (!m_uavGadgetModes.isEmpty()){
pm->removeObject(m_uavGadgetModes.takeFirst());
}
while (!m_uavGadgetManagers.isEmpty()){
Core::UAVGadgetManager* uavGadgetManager = m_uavGadgetManagers.takeLast();
uavGadgetManager->removeAllSplits();
// TODO Fixthis: This only happens, when settings are reloaded.
// then the old GadgetManagers should be deleted, but if
// I delete them the GCS segfaults.
//delete uavGadgetManager;
}
m_uavGadgetManagers.clear();
m_uavGadgetModes.clear();
for (int i = 0; i < m_workspaceSettings->numberOfWorkspaces(); ++i) {
uavGadgetManager = new Core::UAVGadgetManager(CoreImpl::instance(), this);
uavGadgetManager->hide();
const QString name = m_workspaceSettings->name(i);
const QString iconName = m_workspaceSettings->iconName(i);
const QString modeName = m_workspaceSettings->modeName(i);
uavGadgetMode = new UAVGadgetMode(uavGadgetManager, name,
QIcon(iconName), 90-i+1, modeName);
uavGadgetManager->setUAVGadgetMode(uavGadgetMode);
m_uavGadgetModes.append(uavGadgetMode);
pm->addObject(uavGadgetMode);
addUAVGadgetManager(uavGadgetManager);
}
}
static const char *settingsGroup = "MainWindow";
static const char *geometryKey = "Geometry";
static const char *colorKey = "Color";
static const char *maxKey = "Maximized";
static const char *fullScreenKey = "FullScreen";
void MainWindow::readSettings(QSettings* qs)
{
if ( !qs ){
qs = m_settings;
}
m_actionManager->readSettings(qs);
qs->beginGroup(QLatin1String(settingsGroup));
Utils::StyleHelper::setBaseColor(qs->value(QLatin1String(colorKey)).value<QColor>());
const QVariant geom = qs->value(QLatin1String(geometryKey));
if (geom.isValid()) {
setGeometry(geom.toRect());
} else {
resize(750, 400);
}
if (qs->value(QLatin1String(maxKey), false).toBool())
setWindowState(Qt::WindowMaximized);
setFullScreen(qs->value(QLatin1String(fullScreenKey), false).toBool());
qs->endGroup();
m_workspaceSettings->readSettings(qs);
createWorkspaces();
foreach (UAVGadgetManager *manager, m_uavGadgetManagers) {
manager->readSettings(qs);
}
m_viewManager->readSettings(qs);
}
void MainWindow::saveSettings(QSettings* qs)
{
if ( !qs ){
qs = m_settings;
}
m_workspaceSettings->saveSettings(qs);
qs->beginGroup(QLatin1String(settingsGroup));
qs->setValue(QLatin1String(colorKey), Utils::StyleHelper::baseColor());
if (windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen)) {
qs->setValue(QLatin1String(maxKey), (bool) (windowState() & Qt::WindowMaximized));
qs->setValue(QLatin1String(fullScreenKey), (bool) (windowState() & Qt::WindowFullScreen));
} else {
qs->setValue(QLatin1String(maxKey), false);
qs->setValue(QLatin1String(fullScreenKey), false);
qs->setValue(QLatin1String(geometryKey), geometry());
}
qs->endGroup();
foreach (UAVGadgetManager *manager, m_uavGadgetManagers) {
manager->saveSettings(qs);
}
m_viewManager->saveSettings(qs);
m_actionManager->saveSettings(qs);
}
void MainWindow::readSettings(IConfigurablePlugin* plugin, QSettings* qs)
{
if ( !qs ){
qs = m_settings;
}
UAVConfigInfo configInfo;
QObject* qo = reinterpret_cast<QObject *>(plugin);
QString configName = qo->metaObject()->className();
qs->beginGroup("Plugins");
qs->beginGroup(configName);
configInfo.read(qs);
configInfo.setNameOfConfigurable("Plugin-"+configName);
qs->beginGroup("data");
plugin->readConfig(qs, &configInfo);
qs->endGroup();
qs->endGroup();
qs->endGroup();
}
void MainWindow::saveSettings(IConfigurablePlugin* plugin, QSettings* qs)
{
if ( !qs ){
qs = m_settings;
}
UAVConfigInfo configInfo;
QString configName = plugin->metaObject()->className();
qs->beginGroup("Plugins");
qs->beginGroup(configName);
qs->beginGroup("data");
plugin->saveConfig(qs, &configInfo);
qs->endGroup();
configInfo.save(qs);
qs->endGroup();
qs->endGroup();
}
void MainWindow::addAdditionalContext(int context)
{
if (context == 0)
return;
if (!m_additionalContexts.contains(context))
m_additionalContexts.prepend(context);
}
void MainWindow::removeAdditionalContext(int context)
{
if (context == 0)
return;
int index = m_additionalContexts.indexOf(context);
if (index != -1)
m_additionalContexts.removeAt(index);
}
bool MainWindow::hasContext(int context) const
{
return m_actionManager->hasContext(context);
}
void MainWindow::updateContext()
{
QList<int> contexts;
if (m_activeContext)
contexts += m_activeContext->context();
contexts += m_additionalContexts;
QList<int> uniquecontexts;
for (int i = 0; i < contexts.size(); ++i) {
const int c = contexts.at(i);
if (!uniquecontexts.contains(c))
uniquecontexts << c;
}
m_actionManager->setContext(uniquecontexts);
}
void MainWindow::aboutToShowRecentFiles()
{
ActionContainer *aci =
m_actionManager->actionContainer(Constants::M_FILE_RECENTFILES);
if (aci) {
aci->menu()->clear();
bool hasRecentFiles = false;
aci->menu()->setEnabled(hasRecentFiles);
}
}
void MainWindow::openRecentFile()
{
QAction *action = qobject_cast<QAction*>(sender());
if (!action)
return;
QString fileName = action->data().toString();
if (!fileName.isEmpty()) {
}
}
void MainWindow::aboutOpenPilotGCS()
{
if (!m_versionDialog) {
m_versionDialog = new VersionDialog(this);
connect(m_versionDialog, SIGNAL(finished(int)),
this, SLOT(destroyVersionDialog()));
}
m_versionDialog->show();
}
void MainWindow::destroyVersionDialog()
{
if (m_versionDialog) {
m_versionDialog->deleteLater();
m_versionDialog = 0;
}
}
void MainWindow::aboutOpenPilotAuthors()
{
if (!m_authorsDialog) {
m_authorsDialog = new AuthorsDialog(this);
connect(m_authorsDialog, SIGNAL(finished(int)),
this, SLOT(destroyAuthorsDialog()));
}
m_authorsDialog->show();
}
void MainWindow::destroyAuthorsDialog()
{
if (m_authorsDialog) {
m_authorsDialog->deleteLater();
m_authorsDialog = 0;
}
}
void MainWindow::aboutPlugins()
{
PluginDialog dialog(this);
dialog.exec();
}
void MainWindow::setFullScreen(bool on)
{
if (bool(windowState() & Qt::WindowFullScreen) == on)
return;
if (on) {
setWindowState(windowState() | Qt::WindowFullScreen);
//statusBar()->hide();
//menuBar()->hide();
} else {
setWindowState(windowState() & ~Qt::WindowFullScreen);
//menuBar()->show();
//statusBar()->show();
}
}
// Display a warning with an additional button to open
// the debugger settings dialog if settingsId is nonempty.
bool MainWindow::showWarningWithOptions(const QString &title,
const QString &text,
const QString &details,
const QString &settingsCategory,
const QString &settingsId,
QWidget *parent)
{
if (parent == 0)
parent = this;
QMessageBox msgBox(QMessageBox::Warning, title, text,
QMessageBox::Ok, parent);
if (details.isEmpty())
msgBox.setDetailedText(details);
QAbstractButton *settingsButton = 0;
if (!settingsId.isEmpty() || !settingsCategory.isEmpty())
settingsButton = msgBox.addButton(tr("Settings..."), QMessageBox::AcceptRole);
msgBox.exec();
if (settingsButton && msgBox.clickedButton() == settingsButton) {
return showOptionsDialog(settingsCategory, settingsId);
}
return false;
}

View File

@ -1,223 +1,224 @@
/**
******************************************************************************
*
* @file mainwindow.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 MAINWINDOW_H
#define MAINWINDOW_H
#include "core_global.h"
#include "eventfilteringmainwindow.h"
#include <QtCore/QMap>
#include <QSettings>
QT_BEGIN_NAMESPACE
class QSettings;
class QShortcut;
class QToolButton;
QT_END_NAMESPACE
namespace Core {
class ActionManager;
class BaseMode;
class BaseView;
class IContext;
class IMode;
class IWizard;
class ConnectionManager;
class MessageManager;
class MimeDatabase;
class ModeManager;
class RightPaneWidget;
class SettingsDatabase;
class UniqueIDManager;
class VariableManager;
class ThreadManager;
class ViewManagerInterface;
class UAVGadgetManager;
class UAVGadgetInstanceManager;
namespace Internal {
class ActionManagerPrivate;
class CoreImpl;
class FancyTabWidget;
class GeneralSettings;
class ShortcutSettings;
class WorkspaceSettings;
class ViewManager;
class VersionDialog;
class AuthorsDialog;
class UAVGadgetMode;
class CORE_EXPORT MainWindow : public EventFilteringMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
bool init(QString *errorMessage);
void extensionsInitialized();
void shutdown();
IContext *contextObject(QWidget *widget);
void addContextObject(IContext *contex);
void removeContextObject(IContext *contex);
void resetContext();
void readSettings(QSettings* qs);
void saveSettings(QSettings* qs);
void openFiles(const QStringList &fileNames);
Core::ActionManager *actionManager() const;
Core::UniqueIDManager *uniqueIDManager() const;
Core::MessageManager *messageManager() const;
QList<UAVGadgetManager*> uavGadgetManagers() const;
UAVGadgetInstanceManager *uavGadgetInstanceManager() const;
Core::ConnectionManager *connectionManager() const;
Core::VariableManager *variableManager() const;
Core::ThreadManager *threadManager() const;
Core::ModeManager *modeManager() const;
Core::MimeDatabase *mimeDatabase() const;
QSettings *settings(QSettings::Scope scope) const;
inline SettingsDatabase *settingsDatabase() const { return m_settingsDatabase; }
IContext * currentContextObject() const;
QStatusBar *statusBar() const;
void addAdditionalContext(int context);
void removeAdditionalContext(int context);
bool hasContext(int context) const;
void updateContext();
void setSuppressNavigationWidget(bool suppress);
signals:
void windowActivated();
public slots:
void newFile();
void openFileWith();
void exit();
void setFullScreen(bool on);
bool showOptionsDialog(const QString &category = QString(),
const QString &page = QString(),
QWidget *parent = 0);
bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0);
protected:
virtual void changeEvent(QEvent *e);
virtual void closeEvent(QCloseEvent *event);
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dropEvent(QDropEvent *event);
private slots:
void openFile();
void aboutToShowRecentFiles();
void openRecentFile();
void setFocusToEditor();
void saveAll();
void aboutOpenPilotGCS();
void aboutPlugins();
void aboutOpenPilotAuthors();
void updateFocusWidget(QWidget *old, QWidget *now);
void destroyVersionDialog();
void destroyAuthorsDialog();
void modeChanged(Core::IMode *mode);
private:
void addUAVGadgetManager(Core::UAVGadgetManager *manager);
void updateContextObject(IContext *context);
void registerDefaultContainers();
void registerDefaultActions();
void createWorkspaces();
void readSettings();
void saveSettings();
CoreImpl *m_coreImpl;
UniqueIDManager *m_uniqueIDManager;
QList<int> m_globalContext;
QList<int> m_additionalContexts;
QSettings *m_settings;
QSettings *m_globalSettings;
SettingsDatabase *m_settingsDatabase;
ActionManagerPrivate *m_actionManager;
MessageManager *m_messageManager;
VariableManager *m_variableManager;
ThreadManager *m_threadManager;
ViewManager *m_viewManager;
ModeManager *m_modeManager;
QList<UAVGadgetManager*> m_uavGadgetManagers;
QList<UAVGadgetMode*> m_uavGadgetModes;
UAVGadgetInstanceManager *m_uavGadgetInstanceManager;
ConnectionManager *m_connectionManager;
MimeDatabase *m_mimeDatabase;
FancyTabWidget *m_modeStack;
// RightPaneWidget *m_rightPaneWidget;
Core::BaseView *m_outputView;
VersionDialog *m_versionDialog;
AuthorsDialog *m_authorsDialog;
IContext * m_activeContext;
QMap<QWidget *, IContext *> m_contextWidgets;
GeneralSettings *m_generalSettings;
ShortcutSettings *m_shortcutSettings;
WorkspaceSettings *m_workspaceSettings;
// actions
QShortcut *m_focusToEditor;
QAction *m_newAction;
QAction *m_openAction;
QAction *m_openWithAction;
QAction *m_saveAllAction;
QAction *m_exitAction;
QAction *m_optionsAction;
QAction *m_toggleFullScreenAction;
#ifdef Q_WS_MAC
QAction *m_minimizeAction;
QAction *m_zoomAction;
#endif
};
} // namespace Internal
} // namespace Core
#endif // MAINWINDOW_H
/**
******************************************************************************
*
* @file mainwindow.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* 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 MAINWINDOW_H
#define MAINWINDOW_H
#include "core_global.h"
#include "eventfilteringmainwindow.h"
#include <QtCore/QMap>
#include <QSettings>
QT_BEGIN_NAMESPACE
class QSettings;
class QShortcut;
class QToolButton;
QT_END_NAMESPACE
namespace Core {
class ActionManager;
class BaseMode;
class BaseView;
class IConfigurablePlugin;
class IContext;
class IMode;
class IWizard;
class ConnectionManager;
class MessageManager;
class MimeDatabase;
class ModeManager;
class RightPaneWidget;
class SettingsDatabase;
class UniqueIDManager;
class VariableManager;
class ThreadManager;
class ViewManagerInterface;
class UAVGadgetManager;
class UAVGadgetInstanceManager;
namespace Internal {
class ActionManagerPrivate;
class CoreImpl;
class FancyTabWidget;
class GeneralSettings;
class ShortcutSettings;
class WorkspaceSettings;
class ViewManager;
class VersionDialog;
class AuthorsDialog;
class UAVGadgetMode;
class CORE_EXPORT MainWindow : public EventFilteringMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
bool init(QString *errorMessage);
void extensionsInitialized();
void shutdown();
IContext *contextObject(QWidget *widget);
void addContextObject(IContext *contex);
void removeContextObject(IContext *contex);
void resetContext();
void readSettings(QSettings* qs = 0);
void saveSettings(QSettings* qs = 0);
void readSettings(IConfigurablePlugin* plugin, QSettings* qs = 0);
void saveSettings(IConfigurablePlugin* plugin, QSettings* qs = 0);
void openFiles(const QStringList &fileNames);
Core::ActionManager *actionManager() const;
Core::UniqueIDManager *uniqueIDManager() const;
Core::MessageManager *messageManager() const;
QList<UAVGadgetManager*> uavGadgetManagers() const;
UAVGadgetInstanceManager *uavGadgetInstanceManager() const;
Core::ConnectionManager *connectionManager() const;
Core::VariableManager *variableManager() const;
Core::ThreadManager *threadManager() const;
Core::ModeManager *modeManager() const;
Core::MimeDatabase *mimeDatabase() const;
QSettings *settings(QSettings::Scope scope) const;
inline SettingsDatabase *settingsDatabase() const { return m_settingsDatabase; }
IContext * currentContextObject() const;
QStatusBar *statusBar() const;
void addAdditionalContext(int context);
void removeAdditionalContext(int context);
bool hasContext(int context) const;
void updateContext();
void setSuppressNavigationWidget(bool suppress);
signals:
void windowActivated();
public slots:
void newFile();
void openFileWith();
void exit();
void setFullScreen(bool on);
bool showOptionsDialog(const QString &category = QString(),
const QString &page = QString(),
QWidget *parent = 0);
bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0);
protected:
virtual void changeEvent(QEvent *e);
virtual void closeEvent(QCloseEvent *event);
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dropEvent(QDropEvent *event);
private slots:
void openFile();
void aboutToShowRecentFiles();
void openRecentFile();
void setFocusToEditor();
void saveAll();
void aboutOpenPilotGCS();
void aboutPlugins();
void aboutOpenPilotAuthors();
void updateFocusWidget(QWidget *old, QWidget *now);
void destroyVersionDialog();
void destroyAuthorsDialog();
void modeChanged(Core::IMode *mode);
private:
void addUAVGadgetManager(Core::UAVGadgetManager *manager);
void updateContextObject(IContext *context);
void registerDefaultContainers();
void registerDefaultActions();
void createWorkspaces();
CoreImpl *m_coreImpl;
UniqueIDManager *m_uniqueIDManager;
QList<int> m_globalContext;
QList<int> m_additionalContexts;
QSettings *m_settings;
QSettings *m_globalSettings;
SettingsDatabase *m_settingsDatabase;
ActionManagerPrivate *m_actionManager;
MessageManager *m_messageManager;
VariableManager *m_variableManager;
ThreadManager *m_threadManager;
ViewManager *m_viewManager;
ModeManager *m_modeManager;
QList<UAVGadgetManager*> m_uavGadgetManagers;
QList<UAVGadgetMode*> m_uavGadgetModes;
UAVGadgetInstanceManager *m_uavGadgetInstanceManager;
ConnectionManager *m_connectionManager;
MimeDatabase *m_mimeDatabase;
FancyTabWidget *m_modeStack;
// RightPaneWidget *m_rightPaneWidget;
Core::BaseView *m_outputView;
VersionDialog *m_versionDialog;
AuthorsDialog *m_authorsDialog;
IContext * m_activeContext;
QMap<QWidget *, IContext *> m_contextWidgets;
GeneralSettings *m_generalSettings;
ShortcutSettings *m_shortcutSettings;
WorkspaceSettings *m_workspaceSettings;
// actions
QShortcut *m_focusToEditor;
QAction *m_newAction;
QAction *m_openAction;
QAction *m_openWithAction;
QAction *m_saveAllAction;
QAction *m_exitAction;
QAction *m_optionsAction;
QAction *m_toggleFullScreenAction;
#ifdef Q_WS_MAC
QAction *m_minimizeAction;
QAction *m_zoomAction;
#endif
};
} // namespace Internal
} // namespace Core
#endif // MAINWINDOW_H

View File

@ -1,438 +1,514 @@
/**
******************************************************************************
*
* @file notifyplugin.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifyplugin.h"
#include "notifypluginconfiguration.h"
#include "notifypluginoptionspage.h"
#include <coreplugin/icore.h>
#include <QDebug>
#include <QtPlugin>
#include <QStringList>
#include <extensionsystem/pluginmanager.h>
#include <iostream>
#include "qxttimer.h"
//#define DEBUG_NOTIFIES
SoundNotifyPlugin::SoundNotifyPlugin()
{
phonon.mo = NULL;
// Do nothing
}
SoundNotifyPlugin::~SoundNotifyPlugin()
{
if (phonon.mo != NULL)
delete phonon.mo;
// Do nothing
}
bool SoundNotifyPlugin::initialize(const QStringList& args, QString *errMsg)
{
Q_UNUSED(args);
Q_UNUSED(errMsg);
mop = new NotifyPluginOptionsPage(this);
addAutoReleasedObject(mop);
return true;
}
void SoundNotifyPlugin::extensionsInitialized()
{
settings = Core::ICore::instance()->settings();
settings->beginGroup(QLatin1String("NotifyPlugin"));
// read list of notifications from settings
int size = settings->beginReadArray("listNotifies");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
notification->restoreState(settings);
lstNotifications.append(notification);
}
settings->endArray();
setEnableSound(settings->value(QLatin1String("EnableSound"),0).toBool());
settings->endGroup();
ExtensionSystem::PluginManager* pm = ExtensionSystem::PluginManager::instance();
connect(pm, SIGNAL(objectAdded(QObject*)), this, SLOT(onTelemetryManagerAdded(QObject*)));
removedNotifies.clear();
connectNotifications();
}
void SoundNotifyPlugin::onTelemetryManagerAdded(QObject* obj)
{
telMngr = qobject_cast<TelemetryManager *>(obj);
if(telMngr)
connect(telMngr, SIGNAL(disconnected()), this, SLOT(onAutopilotDisconnect()));
}
void SoundNotifyPlugin::shutdown()
{
// Do nothing
}
void SoundNotifyPlugin::onAutopilotDisconnect()
{
connectNotifications();
}
/*!
clear any notify timers from previous flight;
reset will be perform on start of option page
*/
void SoundNotifyPlugin::resetNotification(void)
{
//first, reject empty args and unknown fields.
foreach(NotifyPluginConfiguration* notify,lstNotifications) {
if(notify->timer)
{
disconnect(notify->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
notify->timer->stop();
delete notify->timer;
notify->timer = NULL;
}
if(notify->expireTimer)
{
disconnect(notify->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
notify->expireTimer->stop();
delete notify->expireTimer;
notify->expireTimer = NULL;
}
}
}
/*!
update list of notifies;
will be perform on OK or APPLY press of option page
*/
void SoundNotifyPlugin::updateNotificationList(QList<NotifyPluginConfiguration*> list)
{
removedNotifies.clear();
resetNotification();
lstNotifications.clear();
lstNotifications=list;
connectNotifications();
}
void SoundNotifyPlugin::connectNotifications()
{
foreach(UAVDataObject* obj,lstNotifiedUAVObjects) {
if (obj != NULL)
disconnect(obj,SIGNAL(objectUpdated(UAVObject*)),this,SLOT(appendNotification(UAVObject*)));
}
if(phonon.mo != NULL) {
delete phonon.mo;
phonon.mo = NULL;
}
if(!enableSound) return;
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
lstNotifiedUAVObjects.clear();
pendingNotifications.clear();
lstNotifications.append(removedNotifies);
removedNotifies.clear();
//first, reject empty args and unknown fields.
foreach(NotifyPluginConfiguration* notify,lstNotifications) {
notify->firstStart=true;
notify->isNowPlaying=false;
// if(notify->timer)
// {
// disconnect(notify->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
// notify->timer->stop();
// delete notify->timer;
// notify->timer = NULL;
// }
// if(notify->expireTimer)
// {
// disconnect(notify->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
// notify->expireTimer->stop();
// delete notify->expireTimer;
// notify->expireTimer = NULL;
// }
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(notify->getDataObject()) );
if (obj != NULL ) {
if(!lstNotifiedUAVObjects.contains(obj)) {
lstNotifiedUAVObjects.append(obj);
connect(obj, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
}
} else
std::cout << "Error: Object is unknown (" << notify->getDataObject().toStdString() << ")." << std::endl;
}
if(lstNotifications.isEmpty()) return;
// set notification message to current event
phonon.mo = Phonon::createPlayer(Phonon::NotificationCategory);
phonon.mo->clearQueue();
phonon.firstPlay = true;
#ifdef DEBUG_NOTIFIES
QList<Phonon::AudioOutputDevice> audioOutputDevices =
Phonon::BackendCapabilities::availableAudioOutputDevices();
foreach(Phonon::AudioOutputDevice dev, audioOutputDevices) {
qDebug() << "Notify: Audio Output device: " << dev.name() << " - " << dev.description();
}
#endif
connect(phonon.mo,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(stateChanged(Phonon::State,Phonon::State)));
}
void SoundNotifyPlugin::appendNotification(UAVObject *object)
{
disconnect(object, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
foreach(NotifyPluginConfiguration* notification, lstNotifications) {
if(object->getName()!=notification->getDataObject())
continue;
if(nowPlayingConfiguration == notification)
continue;
if(notification->getRepeatFlag()!= "Repeat Instantly" &&
notification->getRepeatFlag()!= "Repeat Once" && !notification->firstStart)
continue;
checkNotificationRule(notification,object);
}
connect(object, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
}
void SoundNotifyPlugin::checkNotificationRule(NotifyPluginConfiguration* notification, UAVObject* object)
{
bool condition=false;
double threshold;
QString direction;
QString fieldName;
threshold = notification->getSpinBoxValue();
direction = notification->getValue();
fieldName = notification->getObjectField();
UAVObjectField* field = object->getField(fieldName);
if (field->getName()!="") {
double value = field->getDouble();
switch(direction[0].toAscii())
{
case 'E':
if(value==threshold)
condition = true;
break;
case 'G':
if(value>threshold)
condition = true;
break;
case 'L':
if(value<threshold)
condition = true;
break;
}
}
if(condition)
{
if(!playNotification(notification))
{
if(!pendingNotifications.contains(notification))
{
if(notification->timer)
if(notification->timer->isActive())
notification->timer->stop();
#ifdef DEBUG_NOTIFIES
qDebug() << "add to pending list - " << notification->parseNotifyMessage();
#endif
// if audio is busy, start expiration timer
//ms = (notification->getExpiredTimeout()[in sec])*1000
//QxtTimer::singleShot(notification->getExpireTimeout()*1000, this, SLOT(expirationTimerHandler(NotifyPluginConfiguration*)), qVariantFromValue(notification));
pendingNotifications.append(notification);
if(!notification->expireTimer)
{
notification->expireTimer = new QTimer(notification);
connect(notification->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
}
notification->expireTimer->start(notification->getExpireTimeout()*1000);
}
}
}
}
bool SoundNotifyPlugin::playNotification(NotifyPluginConfiguration* notification)
{
// Check: race condition, if phonon.mo got deleted don't go further
if (phonon.mo == NULL)
return false;
#ifdef DEBUG_NOTIFIES
qDebug() << "Phonon State: " << phonon.mo->state();
#endif
if((phonon.mo->state()==Phonon::PausedState) ||
(phonon.mo->state()==Phonon::StoppedState) ||
phonon.firstPlay)
{
// don't fire expire timer
//notification->expire = false;
nowPlayingConfiguration = notification;
if(notification->expireTimer)
notification->expireTimer->stop();
if(notification->getRepeatFlag()=="Repeat Once")
{
removedNotifies.append(lstNotifications.takeAt(lstNotifications.indexOf(notification)));
//if(!notification->firstStart) return true;
}
else {
if(notification->getRepeatFlag()!="Repeat Instantly")
{
QRegExp rxlen("(\\d+)");
QString value;
int timer_value;
int pos = rxlen.indexIn(notification->getRepeatFlag());
if (pos > -1) {
value = rxlen.cap(1); // "189"
timer_value = (value.toInt()+8)*1000; //ms*1000 + average duration of meassage
}
if(!notification->timer)
{
notification->timer = new QTimer(notification);
notification->timer->setInterval(timer_value);
connect(notification->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
}
if(!notification->timer->isActive())
notification->timer->start();
//QxtTimer::singleShot(timer_value, this, SLOT(repeatTimerHandler(NotifyPluginConfiguration*)), qVariantFromValue(notification));
}
}
notification->firstStart=false;
phonon.mo->clear();
QString str = notification->parseNotifyMessage();
#ifdef DEBUG_NOTIFIES
qDebug() << "play notification - " << str;
#endif
foreach(QString item, notification->getNotifyMessageList()) {
Phonon::MediaSource *ms = new Phonon::MediaSource(item);
ms->setAutoDelete(true);
phonon.mo->enqueue(*ms);
}
phonon.mo->play();
phonon.firstPlay = false; // On Linux, you sometimes have to nudge Phonon to play 1 time before
// the state is not "Loading" anymore.
}
else
return false; // if audio is busy
return true;
}
//void SoundNotifyPlugin::repeatTimerHandler(NotifyPluginConfiguration* notification)
//{
// qDebug() << "repeatTimerHandler - " << notification->parseNotifyMessage();
// ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
// UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
// UAVObject* object = objManager->getObject(notification->getDataObject());
// if(object)
// checkNotificationRule(notification,object);
//}
void SoundNotifyPlugin::repeatTimerHandler()
{
NotifyPluginConfiguration* notification = static_cast<NotifyPluginConfiguration*>(sender()->parent());
#ifdef DEBUG_NOTIFIES
qDebug() << "repeatTimerHandler - " << notification->parseNotifyMessage();
#endif
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
UAVObject* object = objManager->getObject(notification->getDataObject());
if(object)
checkNotificationRule(notification,object);
}
void SoundNotifyPlugin::expireTimerHandler()
{
// fire expire timer
NotifyPluginConfiguration* notification = static_cast<NotifyPluginConfiguration*>(sender()->parent());
notification->expireTimer->stop();
if(!pendingNotifications.isEmpty())
{
#ifdef DEBUG_NOTIFIES
qDebug() << "expireTimerHandler - " << notification->parseNotifyMessage();
#endif
pendingNotifications.removeOne(notification);
}
}
void SoundNotifyPlugin::stateChanged(Phonon::State newstate, Phonon::State oldstate)
{
Q_UNUSED(oldstate)
#ifdef DEBUG_NOTIFIES
qDebug() << "File length (ms): " << phonon.mo->totalTime();
qDebug() << "New State: " << newstate;
#endif
#ifndef Q_OS_WIN
// This is a hack to force Linux to wait until the end of the
// wav file before moving to the next in the queue.
// I wish I did not have to go through a #define, but I did not
// manage to make this work on both platforms any other way!
if (phonon.mo->totalTime()>0)
phonon.mo->setTransitionTime(phonon.mo->totalTime());
#endif
if((newstate == Phonon::PausedState) ||
(newstate == Phonon::StoppedState))
{
nowPlayingConfiguration=NULL;
if(!pendingNotifications.isEmpty())
{
NotifyPluginConfiguration* notification = pendingNotifications.takeFirst();
#ifdef DEBUG_NOTIFIES
qDebug() << "play audioFree - " << notification->parseNotifyMessage();
#endif
playNotification(notification);
}
} else if (newstate == Phonon::ErrorState)
{
if(phonon.mo->errorType()==0) {
qDebug() << "Phonon::ErrorState: ErrorType = " << phonon.mo->errorType();
phonon.mo->clearQueue();
}
}
// if(newstate == Phonon::BufferingState)
// qDebug() << "Phonon::BufferingState!!!";
}
Q_EXPORT_PLUGIN(SoundNotifyPlugin)
/**
******************************************************************************
*
* @file notifyplugin.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifyplugin.h"
#include "notifypluginconfiguration.h"
#include "notifypluginoptionspage.h"
#include <coreplugin/icore.h>
#include <QDebug>
#include <QtPlugin>
#include <QStringList>
#include <extensionsystem/pluginmanager.h>
#include <iostream>
#include "qxttimer.h"
static const QString VERSION = "1.0.0";
//#define DEBUG_NOTIFIES
SoundNotifyPlugin::SoundNotifyPlugin()
{
phonon.mo = NULL;
configured = false;
// Do nothing
}
SoundNotifyPlugin::~SoundNotifyPlugin()
{
Core::ICore::instance()->saveSettings(this);
if (phonon.mo != NULL)
delete phonon.mo;
// Do nothing
}
bool SoundNotifyPlugin::initialize(const QStringList& args, QString *errMsg)
{
Q_UNUSED(args);
Q_UNUSED(errMsg);
mop = new NotifyPluginOptionsPage(this);
addAutoReleasedObject(mop);
return true;
}
void SoundNotifyPlugin::extensionsInitialized()
{
Core::ICore::instance()->readSettings(this);
if ( !configured ){
readConfig_0_0_0();
}
ExtensionSystem::PluginManager* pm = ExtensionSystem::PluginManager::instance();
connect(pm, SIGNAL(objectAdded(QObject*)), this, SLOT(onTelemetryManagerAdded(QObject*)));
removedNotifies.clear();
connectNotifications();
}
void SoundNotifyPlugin::saveConfig( QSettings* settings, UAVConfigInfo *configInfo){
configInfo->setVersion(VERSION);
settings->beginWriteArray("Current");
settings->setArrayIndex(0);
currentNotification.saveState(settings);
settings->endArray();
settings->beginGroup("listNotifies");
settings->remove("");
settings->endGroup();
settings->beginWriteArray("listNotifies");
for (int i = 0; i < lstNotifications.size(); i++) {
settings->setArrayIndex(i);
lstNotifications.at(i)->saveState(settings);
}
settings->endArray();
settings->setValue(QLatin1String("EnableSound"), enableSound);
}
void SoundNotifyPlugin::readConfig( QSettings* settings, UAVConfigInfo *configInfo){
if ( configInfo->version() == UAVConfigVersion() ){
// Just for migration to the new format.
configured = false;
return;
}
settings->beginReadArray("Current");
settings->setArrayIndex(0);
currentNotification.restoreState(settings);
settings->endArray();
// read list of notifications from settings
int size = settings->beginReadArray("listNotifies");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
notification->restoreState(settings);
lstNotifications.append(notification);
}
settings->endArray();
setEnableSound(settings->value(QLatin1String("EnableSound"),0).toBool());
configured = true;
}
void SoundNotifyPlugin::readConfig_0_0_0(){
settings = Core::ICore::instance()->settings();
settings->beginGroup(QLatin1String("NotifyPlugin"));
settings->beginReadArray("Current");
settings->setArrayIndex(0);
currentNotification.restoreState(settings);
settings->endArray();
// read list of notifications from settings
int size = settings->beginReadArray("listNotifies");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
notification->restoreState(settings);
lstNotifications.append(notification);
}
settings->endArray();
setEnableSound(settings->value(QLatin1String("EnableSound"),0).toBool());
settings->endGroup();
ExtensionSystem::PluginManager* pm = ExtensionSystem::PluginManager::instance();
connect(pm, SIGNAL(objectAdded(QObject*)), this, SLOT(onTelemetryManagerAdded(QObject*)));
removedNotifies.clear();
connectNotifications();
configured = true;
}
void SoundNotifyPlugin::onTelemetryManagerAdded(QObject* obj)
{
telMngr = qobject_cast<TelemetryManager *>(obj);
if(telMngr)
connect(telMngr, SIGNAL(disconnected()), this, SLOT(onAutopilotDisconnect()));
}
void SoundNotifyPlugin::shutdown()
{
// Do nothing
}
void SoundNotifyPlugin::onAutopilotDisconnect()
{
connectNotifications();
}
/*!
clear any notify timers from previous flight;
reset will be perform on start of option page
*/
void SoundNotifyPlugin::resetNotification(void)
{
//first, reject empty args and unknown fields.
foreach(NotifyPluginConfiguration* notify,lstNotifications) {
if(notify->timer)
{
disconnect(notify->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
notify->timer->stop();
delete notify->timer;
notify->timer = NULL;
}
if(notify->expireTimer)
{
disconnect(notify->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
notify->expireTimer->stop();
delete notify->expireTimer;
notify->expireTimer = NULL;
}
}
}
/*!
update list of notifies;
will be perform on OK or APPLY press of option page
*/
void SoundNotifyPlugin::updateNotificationList(QList<NotifyPluginConfiguration*> list)
{
removedNotifies.clear();
resetNotification();
lstNotifications.clear();
lstNotifications=list;
connectNotifications();
Core::ICore::instance()->saveSettings(this);
}
void SoundNotifyPlugin::connectNotifications()
{
foreach(UAVDataObject* obj,lstNotifiedUAVObjects) {
if (obj != NULL)
disconnect(obj,SIGNAL(objectUpdated(UAVObject*)),this,SLOT(appendNotification(UAVObject*)));
}
if(phonon.mo != NULL) {
delete phonon.mo;
phonon.mo = NULL;
}
if(!enableSound) return;
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
lstNotifiedUAVObjects.clear();
pendingNotifications.clear();
lstNotifications.append(removedNotifies);
removedNotifies.clear();
//first, reject empty args and unknown fields.
foreach(NotifyPluginConfiguration* notify,lstNotifications) {
notify->firstStart=true;
notify->isNowPlaying=false;
// if(notify->timer)
// {
// disconnect(notify->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
// notify->timer->stop();
// delete notify->timer;
// notify->timer = NULL;
// }
// if(notify->expireTimer)
// {
// disconnect(notify->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
// notify->expireTimer->stop();
// delete notify->expireTimer;
// notify->expireTimer = NULL;
// }
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(notify->getDataObject()) );
if (obj != NULL ) {
if(!lstNotifiedUAVObjects.contains(obj)) {
lstNotifiedUAVObjects.append(obj);
connect(obj, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
}
} else
std::cout << "Error: Object is unknown (" << notify->getDataObject().toStdString() << ")." << std::endl;
}
if(lstNotifications.isEmpty()) return;
// set notification message to current event
phonon.mo = Phonon::createPlayer(Phonon::NotificationCategory);
phonon.mo->clearQueue();
phonon.firstPlay = true;
#ifdef DEBUG_NOTIFIES
QList<Phonon::AudioOutputDevice> audioOutputDevices =
Phonon::BackendCapabilities::availableAudioOutputDevices();
foreach(Phonon::AudioOutputDevice dev, audioOutputDevices) {
qDebug() << "Notify: Audio Output device: " << dev.name() << " - " << dev.description();
}
#endif
connect(phonon.mo,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(stateChanged(Phonon::State,Phonon::State)));
}
void SoundNotifyPlugin::appendNotification(UAVObject *object)
{
disconnect(object, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
foreach(NotifyPluginConfiguration* notification, lstNotifications) {
if(object->getName()!=notification->getDataObject())
continue;
if(nowPlayingConfiguration == notification)
continue;
if(notification->getRepeatFlag()!= "Repeat Instantly" &&
notification->getRepeatFlag()!= "Repeat Once" && !notification->firstStart)
continue;
checkNotificationRule(notification,object);
}
connect(object, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(appendNotification(UAVObject*)));
}
void SoundNotifyPlugin::checkNotificationRule(NotifyPluginConfiguration* notification, UAVObject* object)
{
bool condition=false;
double threshold;
QString direction;
QString fieldName;
threshold = notification->getSpinBoxValue();
direction = notification->getValue();
fieldName = notification->getObjectField();
UAVObjectField* field = object->getField(fieldName);
if (field->getName()!="") {
double value = field->getDouble();
switch(direction[0].toAscii())
{
case 'E':
if(value==threshold)
condition = true;
break;
case 'G':
if(value>threshold)
condition = true;
break;
case 'L':
if(value<threshold)
condition = true;
break;
}
}
if(condition)
{
if(!playNotification(notification))
{
if(!pendingNotifications.contains(notification))
{
if(notification->timer)
if(notification->timer->isActive())
notification->timer->stop();
#ifdef DEBUG_NOTIFIES
qDebug() << "add to pending list - " << notification->parseNotifyMessage();
#endif
// if audio is busy, start expiration timer
//ms = (notification->getExpiredTimeout()[in sec])*1000
//QxtTimer::singleShot(notification->getExpireTimeout()*1000, this, SLOT(expirationTimerHandler(NotifyPluginConfiguration*)), qVariantFromValue(notification));
pendingNotifications.append(notification);
if(!notification->expireTimer)
{
notification->expireTimer = new QTimer(notification);
connect(notification->expireTimer, SIGNAL(timeout()), this, SLOT(expireTimerHandler()));
}
notification->expireTimer->start(notification->getExpireTimeout()*1000);
}
}
}
}
bool SoundNotifyPlugin::playNotification(NotifyPluginConfiguration* notification)
{
// Check: race condition, if phonon.mo got deleted don't go further
if (phonon.mo == NULL)
return false;
#ifdef DEBUG_NOTIFIES
qDebug() << "Phonon State: " << phonon.mo->state();
#endif
if((phonon.mo->state()==Phonon::PausedState) ||
(phonon.mo->state()==Phonon::StoppedState) ||
phonon.firstPlay)
{
// don't fire expire timer
//notification->expire = false;
nowPlayingConfiguration = notification;
if(notification->expireTimer)
notification->expireTimer->stop();
if(notification->getRepeatFlag()=="Repeat Once")
{
removedNotifies.append(lstNotifications.takeAt(lstNotifications.indexOf(notification)));
//if(!notification->firstStart) return true;
}
else {
if(notification->getRepeatFlag()!="Repeat Instantly")
{
QRegExp rxlen("(\\d+)");
QString value;
int timer_value;
int pos = rxlen.indexIn(notification->getRepeatFlag());
if (pos > -1) {
value = rxlen.cap(1); // "189"
timer_value = (value.toInt()+8)*1000; //ms*1000 + average duration of meassage
}
if(!notification->timer)
{
notification->timer = new QTimer(notification);
notification->timer->setInterval(timer_value);
connect(notification->timer, SIGNAL(timeout()), this, SLOT(repeatTimerHandler()));
}
if(!notification->timer->isActive())
notification->timer->start();
//QxtTimer::singleShot(timer_value, this, SLOT(repeatTimerHandler(NotifyPluginConfiguration*)), qVariantFromValue(notification));
}
}
notification->firstStart=false;
phonon.mo->clear();
QString str = notification->parseNotifyMessage();
#ifdef DEBUG_NOTIFIES
qDebug() << "play notification - " << str;
#endif
foreach(QString item, notification->getNotifyMessageList()) {
Phonon::MediaSource *ms = new Phonon::MediaSource(item);
ms->setAutoDelete(true);
phonon.mo->enqueue(*ms);
}
phonon.mo->play();
phonon.firstPlay = false; // On Linux, you sometimes have to nudge Phonon to play 1 time before
// the state is not "Loading" anymore.
}
else
return false; // if audio is busy
return true;
}
//void SoundNotifyPlugin::repeatTimerHandler(NotifyPluginConfiguration* notification)
//{
// qDebug() << "repeatTimerHandler - " << notification->parseNotifyMessage();
// ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
// UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
// UAVObject* object = objManager->getObject(notification->getDataObject());
// if(object)
// checkNotificationRule(notification,object);
//}
void SoundNotifyPlugin::repeatTimerHandler()
{
NotifyPluginConfiguration* notification = static_cast<NotifyPluginConfiguration*>(sender()->parent());
#ifdef DEBUG_NOTIFIES
qDebug() << "repeatTimerHandler - " << notification->parseNotifyMessage();
#endif
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
UAVObject* object = objManager->getObject(notification->getDataObject());
if(object)
checkNotificationRule(notification,object);
}
void SoundNotifyPlugin::expireTimerHandler()
{
// fire expire timer
NotifyPluginConfiguration* notification = static_cast<NotifyPluginConfiguration*>(sender()->parent());
notification->expireTimer->stop();
if(!pendingNotifications.isEmpty())
{
#ifdef DEBUG_NOTIFIES
qDebug() << "expireTimerHandler - " << notification->parseNotifyMessage();
#endif
pendingNotifications.removeOne(notification);
}
}
void SoundNotifyPlugin::stateChanged(Phonon::State newstate, Phonon::State oldstate)
{
Q_UNUSED(oldstate)
#ifdef DEBUG_NOTIFIES
qDebug() << "File length (ms): " << phonon.mo->totalTime();
qDebug() << "New State: " << newstate;
#endif
#ifndef Q_OS_WIN
// This is a hack to force Linux to wait until the end of the
// wav file before moving to the next in the queue.
// I wish I did not have to go through a #define, but I did not
// manage to make this work on both platforms any other way!
if (phonon.mo->totalTime()>0)
phonon.mo->setTransitionTime(phonon.mo->totalTime());
#endif
if((newstate == Phonon::PausedState) ||
(newstate == Phonon::StoppedState))
{
nowPlayingConfiguration=NULL;
if(!pendingNotifications.isEmpty())
{
NotifyPluginConfiguration* notification = pendingNotifications.takeFirst();
#ifdef DEBUG_NOTIFIES
qDebug() << "play audioFree - " << notification->parseNotifyMessage();
#endif
playNotification(notification);
}
} else if (newstate == Phonon::ErrorState)
{
if(phonon.mo->errorType()==0) {
qDebug() << "Phonon::ErrorState: ErrorType = " << phonon.mo->errorType();
phonon.mo->clearQueue();
}
}
// if(newstate == Phonon::BufferingState)
// qDebug() << "Phonon::BufferingState!!!";
}
Q_EXPORT_PLUGIN(SoundNotifyPlugin)

View File

@ -1,104 +1,111 @@
/**
******************************************************************************
*
* @file notifyplugin.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 SOUNDNOTIFYPLUGIN_H
#define SOUNDNOTIFYPLUGIN_H
#include <extensionsystem/iplugin.h>
#include "uavtalk/telemetrymanager.h"
#include "uavobjectmanager.h"
#include "uavobject.h"
#include <QSettings>
#include <phonon>
class NotifyPluginOptionsPage;
class NotifyPluginConfiguration;
typedef struct {
Phonon::MediaObject* mo;
NotifyPluginConfiguration* notify;
bool firstPlay;
} PhononObject, *pPhononObject;
class SoundNotifyPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
public:
SoundNotifyPlugin();
~SoundNotifyPlugin();
void extensionsInitialized();
bool initialize(const QStringList & arguments, QString * errorString);
void shutdown();
QList<NotifyPluginConfiguration*> getListNotifications() { return lstNotifications; }
//void setListNotifications(QList<NotifyPluginConfiguration*>& list_notify) { }
bool getEnableSound() const { return enableSound; }
void setEnableSound(bool value) {enableSound = value; }
private:
bool enableSound;
QList< QList<Phonon::MediaSource>* > lstMediaSource;
QStringList mediaSource;
//QMap<QString, Phonon::MediaObject*> mapMediaObjects;
QMultiMap<QString, PhononObject> mapMediaObjects;
QSettings* settings;
QList<UAVDataObject*> lstNotifiedUAVObjects;
QList<NotifyPluginConfiguration*> lstNotifications;
QList<NotifyPluginConfiguration*> pendingNotifications;
QList<NotifyPluginConfiguration*> removedNotifies;
NotifyPluginConfiguration* nowPlayingConfiguration;
QString m_field;
PhononObject phonon;
NotifyPluginOptionsPage *mop;
TelemetryManager* telMngr;
bool playNotification(NotifyPluginConfiguration* notification);
void checkNotificationRule(NotifyPluginConfiguration* notification, UAVObject* object);
private slots:
void onTelemetryManagerAdded(QObject* obj);
void onAutopilotDisconnect();
void connectNotifications();
void updateNotificationList(QList<NotifyPluginConfiguration*> list);
void resetNotification(void);
void appendNotification(UAVObject *object);
void repeatTimerHandler(void);
void expireTimerHandler(void);
void stateChanged(Phonon::State newstate, Phonon::State oldstate);
};
#endif // SOUNDNOTIFYPLUGIN_H
/**
******************************************************************************
*
* @file notifyplugin.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 SOUNDNOTIFYPLUGIN_H
#define SOUNDNOTIFYPLUGIN_H
#include <extensionsystem/iplugin.h>
#include <coreplugin/iconfigurableplugin.h>
#include "uavtalk/telemetrymanager.h"
#include "uavobjectmanager.h"
#include "uavobject.h"
#include "notifypluginconfiguration.h"
#include <QSettings>
#include <phonon>
class NotifyPluginOptionsPage;
typedef struct {
Phonon::MediaObject* mo;
NotifyPluginConfiguration* notify;
bool firstPlay;
} PhononObject, *pPhononObject;
class SoundNotifyPlugin : public Core::IConfigurablePlugin
{
Q_OBJECT
public:
SoundNotifyPlugin();
~SoundNotifyPlugin();
void extensionsInitialized();
bool initialize(const QStringList & arguments, QString * errorString);
void readConfig( QSettings* qSettings, Core::UAVConfigInfo *configInfo);
void saveConfig( QSettings* qSettings, Core::UAVConfigInfo *configInfo);
void shutdown();
QList<NotifyPluginConfiguration*> getListNotifications() { return lstNotifications; }
//void setListNotifications(QList<NotifyPluginConfiguration*>& list_notify) { }
NotifyPluginConfiguration* getCurrentNotification(){ return &currentNotification;}
bool getEnableSound() const { return enableSound; }
void setEnableSound(bool value) {enableSound = value; }
private:
bool configured; // just for migration,delete later
bool enableSound;
QList< QList<Phonon::MediaSource>* > lstMediaSource;
QStringList mediaSource;
//QMap<QString, Phonon::MediaObject*> mapMediaObjects;
QMultiMap<QString, PhononObject> mapMediaObjects;
QSettings* settings;
QList<UAVDataObject*> lstNotifiedUAVObjects;
QList<NotifyPluginConfiguration*> lstNotifications;
QList<NotifyPluginConfiguration*> pendingNotifications;
QList<NotifyPluginConfiguration*> removedNotifies;
NotifyPluginConfiguration currentNotification;
NotifyPluginConfiguration* nowPlayingConfiguration;
QString m_field;
PhononObject phonon;
NotifyPluginOptionsPage *mop;
TelemetryManager* telMngr;
bool playNotification(NotifyPluginConfiguration* notification);
void checkNotificationRule(NotifyPluginConfiguration* notification, UAVObject* object);
void readConfig_0_0_0();
private slots:
void onTelemetryManagerAdded(QObject* obj);
void onAutopilotDisconnect();
void connectNotifications();
void updateNotificationList(QList<NotifyPluginConfiguration*> list);
void resetNotification(void);
void appendNotification(UAVObject *object);
void repeatTimerHandler(void);
void expireTimerHandler(void);
void stateChanged(Phonon::State newstate, Phonon::State oldstate);
};
#endif // SOUNDNOTIFYPLUGIN_H

View File

@ -1,223 +1,245 @@
/**
******************************************************************************
*
* @file notifyPluginConfiguration.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin configuration
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifypluginconfiguration.h"
#include <QtCore/QDataStream>
#include <QFile>
#include "utils/pathutils.h"
NotifyPluginConfiguration::NotifyPluginConfiguration(QObject *parent) :
isNowPlaying(0),
firstStart(1),
soundCollectionPath(""),
currentLanguage("default"),
dataObject(""),
objectField(""),
value("Equal to"),
sound1(""),
sound2(""),
sound3(""),
sayOrder("Never"),
spinBoxValue(0),
repeatString("Repeat Instantly"),
repeatTimeout(true),
expireTimeout(15)
{
timer = NULL;
expireTimer = NULL;
}
void NotifyPluginConfiguration::saveState(QSettings* settings) const
{
settings->setValue("SoundCollectionPath", Utils::PathUtils().RemoveDataPath(getSoundCollectionPath()));
settings->setValue(QLatin1String("CurrentLanguage"), getCurrentLanguage());
settings->setValue(QLatin1String("ObjectField"), getObjectField());
settings->setValue(QLatin1String("DataObject"), getDataObject());
settings->setValue(QLatin1String("Value"), getValue());
settings->setValue(QLatin1String("ValueSpinBox"), getSpinBoxValue());
settings->setValue(QLatin1String("Sound1"), getSound1());
settings->setValue(QLatin1String("Sound2"), getSound2());
settings->setValue(QLatin1String("Sound3"), getSound3());
settings->setValue(QLatin1String("SayOrder"), getSayOrder());
settings->setValue(QLatin1String("Repeat"), getRepeatFlag());
settings->setValue(QLatin1String("ExpireTimeout"), getExpireTimeout());
}
void NotifyPluginConfiguration::restoreState(QSettings* settings)
{
//settings = Core::ICore::instance()->settings();
setSoundCollectionPath(Utils::PathUtils().InsertDataPath(settings->value(QLatin1String("SoundCollectionPath"), tr("")).toString()));
setCurrentLanguage(settings->value(QLatin1String("CurrentLanguage"), tr("")).toString());
setDataObject(settings->value(QLatin1String("DataObject"), tr("")).toString());
setObjectField(settings->value(QLatin1String("ObjectField"), tr("")).toString());
setValue(settings->value(QLatin1String("Value"), tr("")).toString());
setSound1(settings->value(QLatin1String("Sound1"), tr("")).toString());
setSound2(settings->value(QLatin1String("Sound2"), tr("")).toString());
setSound3(settings->value(QLatin1String("Sound3"), tr("")).toString());
setSayOrder(settings->value(QLatin1String("SayOrder"), tr("")).toString());
setSpinBoxValue(settings->value(QLatin1String("ValueSpinBox"), tr("")).toDouble());
setRepeatFlag(settings->value(QLatin1String("Repeat"), tr("")).toString());
setExpireTimeout(settings->value(QLatin1String("ExpireTimeout"), tr("")).toInt());
}
QString NotifyPluginConfiguration::parseNotifyMessage()
{
// tips:
// check of *.wav files exist needed for playing phonon queues;
// if phonon player don't find next file in queue, it buzz
QString str,str1;
str1= getSayOrder();
str = QString("%L1 ").arg(getSpinBoxValue());
int position = 0xFF;
// generate queue of sound files to play
notifyMessageList.clear();
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav"));
if(getSound2()!="")
{
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound2()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound2()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav"));
}
if(getSound3()!="")
{
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav"));
}
switch(str1.at(0).toAscii())
{
case 'N'://NEVER:
str = getSound1()+" "+getSound2()+" "+getSound3();
position = 0xFF;
break;
case 'B'://BEFORE:
str = QString("%L1 ").arg(getSpinBoxValue())+getSound1()+" "+getSound2()+" "+getSound3();
position = 0;
break;
case 'A'://AFTER:
switch(str1.at(6).toAscii())
{
case 'f':
str = getSound1()+QString(" %L1 ").arg(getSpinBoxValue())+getSound2()+" "+getSound3();
position = 1;
break;
case 's':
str = getSound1()+" "+getSound2()+QString(" %L1").arg(getSpinBoxValue())+" "+getSound3();
position = 2;
break;
case 't':
str = getSound1()+" "+getSound2()+" "+getSound3()+QString(" %L1").arg(getSpinBoxValue());
position = 3;
break;
}
break;
}
if(position!=0xFF)
{
QStringList numberParts = QString("%1").arg(getSpinBoxValue()).trimmed().split(".");
QStringList numberFiles;
if((numberParts.at(0).size()==1) || (numberParts.at(0).toInt()<20))
{
//if(numberParts.at(0)!="0")
numberFiles.append(numberParts.at(0));
} else {
int i=0;
if(numberParts.at(0).right(2).toInt()<20 && numberParts.at(0).right(2).toInt()!=0) {
if(numberParts.at(0).right(2).toInt()<10)
numberFiles.append(numberParts.at(0).right(1));
else
numberFiles.append(numberParts.at(0).right(2));
i=2;
}
for(;i<numberParts.at(0).size();i++)
{
numberFiles.prepend(numberParts.at(0).at(numberParts.at(0).size()-i-1));
if(numberFiles.first()==QString("0")) {
numberFiles.removeFirst();
continue;
}
if(i==1)
numberFiles.replace(0,numberFiles.first()+'0');
if(i==2)
numberFiles.insert(1,"100");
if(i==3)
numberFiles.insert(1,"1000");
}
}
if(numberParts.size()>1) {
numberFiles.append("point");
if((numberParts.at(1).size()==1) /*|| (numberParts.at(1).toInt()<20)*/)
numberFiles.append(numberParts.at(1));
else {
if(numberParts.at(1).left(1)=="0")
numberFiles.append(numberParts.at(1).left(1));
else
numberFiles.append(numberParts.at(1).left(1)+'0');
numberFiles.append(numberParts.at(1).right(1));
}
}
foreach(QString fileName,numberFiles) {
fileName+=".wav";
QString filePath = QDir::toNativeSeparators(getSoundCollectionPath()+"/"+ getCurrentLanguage()+"/"+fileName);
if(QFile::exists(filePath))
notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+ "/"+getCurrentLanguage()+"/"+fileName));
else {
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName)))
notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName));
else {
notifyMessageList.clear();
break; // if no some of *.wav files, then don't play number!
}
}
}
}
//str.replace(QString(".wav | .mp3"), QString(""));
return str;
}
/**
******************************************************************************
*
* @file notifyPluginConfiguration.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin configuration
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifypluginconfiguration.h"
#include <QtCore/QDataStream>
#include <QFile>
#include "utils/pathutils.h"
NotifyPluginConfiguration::NotifyPluginConfiguration(QObject *parent) :
QObject(parent),
isNowPlaying(0),
firstStart(1),
soundCollectionPath(""),
currentLanguage("default"),
dataObject(""),
objectField(""),
value("Equal to"),
sound1(""),
sound2(""),
sound3(""),
sayOrder("Never"),
spinBoxValue(0),
repeatString("Repeat Instantly"),
repeatTimeout(true),
expireTimeout(15)
{
timer = NULL;
expireTimer = NULL;
}
void NotifyPluginConfiguration::copyTo(NotifyPluginConfiguration* that) const
{
that->isNowPlaying = isNowPlaying;
that->firstStart = firstStart;
that->soundCollectionPath = soundCollectionPath;
that->currentLanguage = currentLanguage;
that->soundCollectionPath = soundCollectionPath;
that->dataObject = dataObject;
that->objectField = objectField;
that->value = value;
that->sound1 = sound1;
that->sound2 = sound2;
that->sound3 = sound3;
that->sayOrder = sayOrder;
that->spinBoxValue = spinBoxValue;
that->repeatString = repeatString;
that->repeatTimeout = repeatTimeout;
that->expireTimeout = expireTimeout;
}
void NotifyPluginConfiguration::saveState(QSettings* settings) const
{
settings->setValue("SoundCollectionPath", Utils::PathUtils().RemoveDataPath(getSoundCollectionPath()));
settings->setValue(QLatin1String("CurrentLanguage"), getCurrentLanguage());
settings->setValue(QLatin1String("ObjectField"), getObjectField());
settings->setValue(QLatin1String("DataObject"), getDataObject());
settings->setValue(QLatin1String("Value"), getValue());
settings->setValue(QLatin1String("ValueSpinBox"), getSpinBoxValue());
settings->setValue(QLatin1String("Sound1"), getSound1());
settings->setValue(QLatin1String("Sound2"), getSound2());
settings->setValue(QLatin1String("Sound3"), getSound3());
settings->setValue(QLatin1String("SayOrder"), getSayOrder());
settings->setValue(QLatin1String("Repeat"), getRepeatFlag());
settings->setValue(QLatin1String("ExpireTimeout"), getExpireTimeout());
}
void NotifyPluginConfiguration::restoreState(QSettings* settings)
{
//settings = Core::ICore::instance()->settings();
setSoundCollectionPath(Utils::PathUtils().InsertDataPath(settings->value(QLatin1String("SoundCollectionPath"), tr("")).toString()));
setCurrentLanguage(settings->value(QLatin1String("CurrentLanguage"), tr("")).toString());
setDataObject(settings->value(QLatin1String("DataObject"), tr("")).toString());
setObjectField(settings->value(QLatin1String("ObjectField"), tr("")).toString());
setValue(settings->value(QLatin1String("Value"), tr("")).toString());
setSound1(settings->value(QLatin1String("Sound1"), tr("")).toString());
setSound2(settings->value(QLatin1String("Sound2"), tr("")).toString());
setSound3(settings->value(QLatin1String("Sound3"), tr("")).toString());
setSayOrder(settings->value(QLatin1String("SayOrder"), tr("")).toString());
setSpinBoxValue(settings->value(QLatin1String("ValueSpinBox"), tr("")).toDouble());
setRepeatFlag(settings->value(QLatin1String("Repeat"), tr("")).toString());
setExpireTimeout(settings->value(QLatin1String("ExpireTimeout"), tr("")).toInt());
}
QString NotifyPluginConfiguration::parseNotifyMessage()
{
// tips:
// check of *.wav files exist needed for playing phonon queues;
// if phonon player don't find next file in queue, it buzz
QString str,str1;
str1= getSayOrder();
str = QString("%L1 ").arg(getSpinBoxValue());
int position = 0xFF;
// generate queue of sound files to play
notifyMessageList.clear();
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav"));
if(getSound2()!="")
{
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound2()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound2()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav"));
}
if(getSound3()!="")
{
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav"));
else
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav")))
notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav"));
}
switch(str1.at(0).toAscii())
{
case 'N'://NEVER:
str = getSound1()+" "+getSound2()+" "+getSound3();
position = 0xFF;
break;
case 'B'://BEFORE:
str = QString("%L1 ").arg(getSpinBoxValue())+getSound1()+" "+getSound2()+" "+getSound3();
position = 0;
break;
case 'A'://AFTER:
switch(str1.at(6).toAscii())
{
case 'f':
str = getSound1()+QString(" %L1 ").arg(getSpinBoxValue())+getSound2()+" "+getSound3();
position = 1;
break;
case 's':
str = getSound1()+" "+getSound2()+QString(" %L1").arg(getSpinBoxValue())+" "+getSound3();
position = 2;
break;
case 't':
str = getSound1()+" "+getSound2()+" "+getSound3()+QString(" %L1").arg(getSpinBoxValue());
position = 3;
break;
}
break;
}
if(position!=0xFF)
{
QStringList numberParts = QString("%1").arg(getSpinBoxValue()).trimmed().split(".");
QStringList numberFiles;
if((numberParts.at(0).size()==1) || (numberParts.at(0).toInt()<20))
{
//if(numberParts.at(0)!="0")
numberFiles.append(numberParts.at(0));
} else {
int i=0;
if(numberParts.at(0).right(2).toInt()<20 && numberParts.at(0).right(2).toInt()!=0) {
if(numberParts.at(0).right(2).toInt()<10)
numberFiles.append(numberParts.at(0).right(1));
else
numberFiles.append(numberParts.at(0).right(2));
i=2;
}
for(;i<numberParts.at(0).size();i++)
{
numberFiles.prepend(numberParts.at(0).at(numberParts.at(0).size()-i-1));
if(numberFiles.first()==QString("0")) {
numberFiles.removeFirst();
continue;
}
if(i==1)
numberFiles.replace(0,numberFiles.first()+'0');
if(i==2)
numberFiles.insert(1,"100");
if(i==3)
numberFiles.insert(1,"1000");
}
}
if(numberParts.size()>1) {
numberFiles.append("point");
if((numberParts.at(1).size()==1) /*|| (numberParts.at(1).toInt()<20)*/)
numberFiles.append(numberParts.at(1));
else {
if(numberParts.at(1).left(1)=="0")
numberFiles.append(numberParts.at(1).left(1));
else
numberFiles.append(numberParts.at(1).left(1)+'0');
numberFiles.append(numberParts.at(1).right(1));
}
}
foreach(QString fileName,numberFiles) {
fileName+=".wav";
QString filePath = QDir::toNativeSeparators(getSoundCollectionPath()+"/"+ getCurrentLanguage()+"/"+fileName);
if(QFile::exists(filePath))
notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+ "/"+getCurrentLanguage()+"/"+fileName));
else {
if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName)))
notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName));
else {
notifyMessageList.clear();
break; // if no some of *.wav files, then don't play number!
}
}
}
}
//str.replace(QString(".wav | .mp3"), QString(""));
return str;
}

View File

@ -1,120 +1,122 @@
/**
******************************************************************************
*
* @file notifypluginconfiguration.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin configuration header
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 NOTIFYPLUGINCONFIGURATION_H
#define NOTIFYPLUGINCONFIGURATION_H
#include <coreplugin/iuavgadgetconfiguration.h>
#include "qsettings.h"
#include <qstringlist.h>
#include <QTimer>
using namespace Core;
class NotifyPluginConfiguration : public QObject
{
Q_OBJECT
public:
explicit NotifyPluginConfiguration(QObject *parent = 0);
QTimer* timer;
QTimer* expireTimer;
bool isNowPlaying; //
bool firstStart;
QString getSound1() const { return sound1; }
void setSound1(QString text) {sound1 = text; }
QString getSound2() const { return sound2; }
void setSound2(QString text) {sound2 = text; }
QString getSound3() const { return sound3; }
void setSound3(QString text) {sound3 = text; }
QString getValue() const { return value; }
void setValue(QString text) {value = text; }
QString getSayOrder() const { return sayOrder; }
void setSayOrder(QString text) {sayOrder = text; }
double getSpinBoxValue() const { return spinBoxValue; }
void setSpinBoxValue(double value) {spinBoxValue = value; }
QString getDataObject() const { return dataObject; }
void setDataObject(QString text) {dataObject = text; }
QString getObjectField() const { return objectField; }
void setObjectField(QString text) { objectField = text; }
QString getSoundCollectionPath() const { return soundCollectionPath; }
void setSoundCollectionPath(QString text) { soundCollectionPath = text; }
QString getCurrentLanguage() const { return currentLanguage; }
void setCurrentLanguage(QString text) { currentLanguage = text; }
QStringList getNotifyMessageList() const { return notifyMessageList; }
void setNotifyMessageList(QStringList text) { notifyMessageList = text; }
QString getRepeatFlag() const { return repeatString; }
void setRepeatFlag(QString value) { repeatString = value; }
bool getRepeatTimeout() const { return repeatTimeout; }
void setRepeatTimeout(bool value) { repeatTimeout = value; }
int getExpireTimeout() const { return expireTimeout; }
void setExpireTimeout(int value) { expireTimeout = value; }
void saveState(QSettings* settings) const;
void restoreState(QSettings* settings);
QString parseNotifyMessage();
private:
QStringList notifyMessageList;
QString soundCollectionPath;
QString currentLanguage;
QString dataObject;
QString objectField;
QString value;
QString sound1;
QString sound2;
QString sound3;
QString sayOrder;
double spinBoxValue;
QString repeatString;
bool repeatTimeout;
int repeatTimerValue;
int expireTimeout;
};
Q_DECLARE_METATYPE(NotifyPluginConfiguration*)
#endif // NOTIFYPLUGINCONFIGURATION_H
/**
******************************************************************************
*
* @file notifypluginconfiguration.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin configuration header
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 NOTIFYPLUGINCONFIGURATION_H
#define NOTIFYPLUGINCONFIGURATION_H
#include <coreplugin/iuavgadgetconfiguration.h>
#include "qsettings.h"
#include <qstringlist.h>
#include <QTimer>
using namespace Core;
class NotifyPluginConfiguration : public QObject
{
Q_OBJECT
public:
explicit NotifyPluginConfiguration(QObject *parent = 0);
QTimer* timer;
QTimer* expireTimer;
bool isNowPlaying; //
bool firstStart;
void copyTo(NotifyPluginConfiguration*) const;
QString getSound1() const { return sound1; }
void setSound1(QString text) {sound1 = text; }
QString getSound2() const { return sound2; }
void setSound2(QString text) {sound2 = text; }
QString getSound3() const { return sound3; }
void setSound3(QString text) {sound3 = text; }
QString getValue() const { return value; }
void setValue(QString text) {value = text; }
QString getSayOrder() const { return sayOrder; }
void setSayOrder(QString text) {sayOrder = text; }
double getSpinBoxValue() const { return spinBoxValue; }
void setSpinBoxValue(double value) {spinBoxValue = value; }
QString getDataObject() const { return dataObject; }
void setDataObject(QString text) {dataObject = text; }
QString getObjectField() const { return objectField; }
void setObjectField(QString text) { objectField = text; }
QString getSoundCollectionPath() const { return soundCollectionPath; }
void setSoundCollectionPath(QString text) { soundCollectionPath = text; }
QString getCurrentLanguage() const { return currentLanguage; }
void setCurrentLanguage(QString text) { currentLanguage = text; }
QStringList getNotifyMessageList() const { return notifyMessageList; }
void setNotifyMessageList(QStringList text) { notifyMessageList = text; }
QString getRepeatFlag() const { return repeatString; }
void setRepeatFlag(QString value) { repeatString = value; }
bool getRepeatTimeout() const { return repeatTimeout; }
void setRepeatTimeout(bool value) { repeatTimeout = value; }
int getExpireTimeout() const { return expireTimeout; }
void setExpireTimeout(int value) { expireTimeout = value; }
void saveState(QSettings* settings) const;
void restoreState(QSettings* settings);
QString parseNotifyMessage();
private:
QStringList notifyMessageList;
QString soundCollectionPath;
QString currentLanguage;
QString dataObject;
QString objectField;
QString value;
QString sound1;
QString sound2;
QString sound3;
QString sayOrder;
double spinBoxValue;
QString repeatString;
bool repeatTimeout;
int repeatTimerValue;
int expireTimeout;
};
Q_DECLARE_METATYPE(NotifyPluginConfiguration*)
#endif // NOTIFYPLUGINCONFIGURATION_H

View File

@ -1,505 +1,476 @@
/**
******************************************************************************
*
* @file notifypluginoptionspage.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin options page
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifypluginoptionspage.h"
#include <coreplugin/icore.h>
#include "notifypluginconfiguration.h"
#include "ui_notifypluginoptionspage.h"
#include "extensionsystem/pluginmanager.h"
#include <QFileDialog>
#include <QtAlgorithms>
#include <QStringList>
#include <QtCore/QSettings>
#include <QTableWidget>
#include <QPalette>
#include <QBuffer>
#include "notifyplugin.h"
#include "notifyitemdelegate.h"
#include "notifytablemodel.h"
NotifyPluginOptionsPage::NotifyPluginOptionsPage(/*NotifyPluginConfiguration *config,*/ QObject *parent) :
IOptionsPage(parent),
owner((SoundNotifyPlugin*)parent),
currentCollectionPath(""),
privListNotifications(((SoundNotifyPlugin*)parent)->getListNotifications())
{
}
//creates options page widget (uses the UI file)
QWidget *NotifyPluginOptionsPage::createPage(QWidget *parent)
{
options_page = new Ui::NotifyPluginOptionsPage();
//main widget
QWidget *optionsPageWidget = new QWidget;
//main layout
options_page->setupUi(optionsPageWidget);
delegateItems.clear();
privListNotifications.clear();
listSoundFiles.clear();
delegateItems << "Repeat Once"
<< "Repeat Instantly"
<< "Repeat 10 seconds"
<< "Repeat 30 seconds"
<< "Repeat 1 minute";
options_page->chkEnableSound->setChecked(owner->getEnableSound());
options_page->SoundDirectoryPathChooser->setExpectedKind(Utils::PathChooser::Directory);
options_page->SoundDirectoryPathChooser->setPromptDialogTitle(tr("Choose sound collection directory"));
settings = Core::ICore::instance()->settings();
settings->beginGroup(QLatin1String("NotifyPlugin"));
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
objManager = pm->getObject<UAVObjectManager>();
// Fills the combo boxes for the UAVObjects
QList< QList<UAVDataObject*> > objList = objManager->getDataObjects();
foreach (QList<UAVDataObject*> list, objList) {
foreach (UAVDataObject* obj, list) {
options_page->UAVObject->addItem(obj->getName());
}
}
connect(options_page->SoundDirectoryPathChooser, SIGNAL(changed(const QString&)), this, SLOT(on_buttonSoundFolder_clicked(const QString&)));
connect(options_page->SoundCollectionList, SIGNAL(currentIndexChanged (int)), this, SLOT(on_soundLanguage_indexChanged(int)));
connect(options_page->buttonAdd, SIGNAL(pressed()), this, SLOT(on_buttonAddNotification_clicked()));
connect(options_page->buttonDelete, SIGNAL(pressed()), this, SLOT(on_buttonDeleteNotification_clicked()));
connect(options_page->buttonModify, SIGNAL(pressed()), this, SLOT(on_buttonModifyNotification_clicked()));
// connect(options_page->buttonTestSound1, SIGNAL(clicked()), this, SLOT(on_buttonTestSound1_clicked()));
// connect(options_page->buttonTestSound2, SIGNAL(clicked()), this, SLOT(on_buttonTestSound2_clicked()));
connect(options_page->buttonPlayNotification, SIGNAL(clicked()), this, SLOT(on_buttonTestSoundNotification_clicked()));
connect(options_page->chkEnableSound, SIGNAL(toggled(bool)), this, SLOT(on_chkEnableSound_toggled(bool)));
connect(options_page->UAVObject, SIGNAL(currentIndexChanged(QString)), this, SLOT(on_UAVObject_indexChanged(QString)));
connect(this, SIGNAL(updateNotifications(QList<NotifyPluginConfiguration*>)),
owner, SLOT(updateNotificationList(QList<NotifyPluginConfiguration*>)));
connect(this, SIGNAL(resetNotification()),owner, SLOT(resetNotification()));
//emit resetNotification();
int size = settings->beginReadArray("listNotifies");
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
notification->restoreState(settings);
privListNotifications.append(notification);
}
settings->endArray();
settings->beginReadArray("Current");
settings->setArrayIndex(0);
NotifyPluginConfiguration notification;
notification.restoreState(settings);
updateConfigView(&notification);
settings->endArray();
options_page->chkEnableSound->setChecked(settings->value(QLatin1String("EnableSound"),0).toBool());
settings->endGroup();
QStringList headerStrings;
headerStrings << "Name" << "Repeats" << "Lifetime,sec";
notifyRulesModel = new NotifyTableModel(&privListNotifications,headerStrings);
options_page->notifyRulesView->setModel(notifyRulesModel);
options_page->notifyRulesView->resizeRowsToContents();
notifyRulesSelection = new QItemSelectionModel(notifyRulesModel);
connect(notifyRulesSelection, SIGNAL(selectionChanged ( const QItemSelection &, const QItemSelection & )),
this, SLOT(on_tableNotification_changeSelection( const QItemSelection & , const QItemSelection & )));
connect(this, SIGNAL(entryUpdated(int)),
notifyRulesModel, SLOT(entryUpdated(int)));
connect(this, SIGNAL(entryAdded(int)),
notifyRulesModel, SLOT(entryAdded(int)));
options_page->notifyRulesView->setSelectionModel(notifyRulesSelection);
options_page->notifyRulesView->setItemDelegate(new NotifyItemDelegate(delegateItems,this));
options_page->notifyRulesView->setColumnWidth(0,200);
options_page->notifyRulesView->setColumnWidth(1,150);
options_page->notifyRulesView->setColumnWidth(2,100);
options_page->buttonModify->setEnabled(false);
options_page->buttonDelete->setEnabled(false);
options_page->buttonPlayNotification->setEnabled(false);
// sound1 = Phonon::createPlayer(Phonon::NotificationCategory);
// sound2 = Phonon::createPlayer(Phonon::NotificationCategory);
notifySound = Phonon::createPlayer(Phonon::NotificationCategory);
// audioOutput = new Phonon::AudioOutput(Phonon::NotificationCategory, this);
// Phonon::createPath(sound1, audioOutput);
// Phonon::createPath(sound2, audioOutput);
// Phonon::createPath(notifySound, audioOutput);
// connect(sound1,SIGNAL(stateChanged(Phonon::State,Phonon::State)),SLOT(changeButtonText(Phonon::State,Phonon::State)));
// connect(sound2,SIGNAL(stateChanged(Phonon::State,Phonon::State)),SLOT(changeButtonText(Phonon::State,Phonon::State)));
connect(notifySound,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(changeButtonText(Phonon::State,Phonon::State)));
return optionsPageWidget;
}
void NotifyPluginOptionsPage::showPersistentComboBox( const QModelIndex & parent, int start, int end )
{
// for (int i=start; i<end+1; i++) {
// options_page->tableNotifications->openPersistentEditor(options_page->tableNotifications->item(i,1));
// }
}
void NotifyPluginOptionsPage::showPersistentComboBox2( const QModelIndex & topLeft, const QModelIndex & bottomRight )
{
//for (QModelIndex i=topLeft; i<bottomRight+1; i++)
{
// options_page->tableNotifications->openPersistentEditor(options_page->tableNotifications->item(options_page->tableNotifications->currentRow(),1));
}
}
void NotifyPluginOptionsPage::getOptionsPageValues(NotifyPluginConfiguration* notification)
{
notification->setSoundCollectionPath(options_page->SoundDirectoryPathChooser->path());
notification->setCurrentLanguage(options_page->SoundCollectionList->currentText());
notification->setDataObject(options_page->UAVObject->currentText());
notification->setObjectField(options_page->UAVObjectField->currentText());
notification->setSound1(options_page->Sound1->currentText());
notification->setSound2(options_page->Sound2->currentText());
notification->setSound3(options_page->Sound3->currentText());
notification->setSayOrder(options_page->SayOrder->currentText());
notification->setValue(options_page->Value->currentText());
notification->setSpinBoxValue(options_page->ValueSpinBox->value());
// if(notifyRulesSelection->currentIndex().row()>-1)
// {
// //qDebug() << "delegate value:" << options_page->tableNotifications->item(options_page->tableNotifications->currentRow(),1)->data(Qt::EditRole);
// notification->setRepeatFlag(notifyRulesModel->data(notifyRulesSelection->currentIndex(),Qt::DisplayRole).toString());
// }
}
////////////////////////////////////////////
// Called when the user presses apply or OK.
//
// Saves the current values
//
////////////////////////////////////////////
void NotifyPluginOptionsPage::apply()
{
NotifyPluginConfiguration notification;
settings->beginGroup(QLatin1String("NotifyPlugin"));
getOptionsPageValues(&notification);
settings->beginWriteArray("Current");
settings->setArrayIndex(0);
notification.saveState(settings);
settings->endArray();
settings->beginGroup("listNotifies");
settings->remove("");
settings->endGroup();
settings->beginWriteArray("listNotifies");
for (int i = 0; i < privListNotifications.size(); i++) {
settings->setArrayIndex(i);
privListNotifications.at(i)->saveState(settings);
}
settings->endArray();
settings->setValue(QLatin1String("EnableSound"), options_page->chkEnableSound->isChecked());
settings->endGroup();
owner->setEnableSound(options_page->chkEnableSound->isChecked());
//owner->setListNotifications(privListNotifications);
emit updateNotifications(privListNotifications);
}
void NotifyPluginOptionsPage::finish()
{
disconnect(notifySound,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(changeButtonText(Phonon::State,Phonon::State)));
if(notifySound)
{
notifySound->stop();
notifySound->clear();
}
delete options_page;
}
//////////////////////////////////////////////////////////////////////////////
// Fills in the <Field> combo box when value is changed in the
// <Object> combo box
//////////////////////////////////////////////////////////////////////////////
void NotifyPluginOptionsPage::on_UAVObject_indexChanged(QString val) {
options_page->UAVObjectField->clear();
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(val) );
QList<UAVObjectField*> fieldList = obj->getFields();
foreach (UAVObjectField* field, fieldList) {
options_page->UAVObjectField->addItem(field->getName());
}
}
// locate collection folder on disk
void NotifyPluginOptionsPage::on_buttonSoundFolder_clicked(const QString& path)
{
QDir dirPath(path);
listDirCollections = dirPath.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
options_page->SoundCollectionList->clear();
options_page->SoundCollectionList->addItems(listDirCollections);
}
void NotifyPluginOptionsPage::on_soundLanguage_indexChanged(int index)
{
options_page->SoundCollectionList->setCurrentIndex(index);
currentCollectionPath = options_page->SoundDirectoryPathChooser->path() +
QDir::toNativeSeparators("/" + options_page->SoundCollectionList->currentText());
QDir dirPath(currentCollectionPath);
QStringList filters;
filters << "*.mp3" << "*.wav";
dirPath.setNameFilters(filters);
listSoundFiles = dirPath.entryList(filters);
listSoundFiles.replaceInStrings(QRegExp(".mp3|.wav"), "");
options_page->Sound1->clear();
options_page->Sound2->clear();
options_page->Sound3->clear();
options_page->Sound1->addItems(listSoundFiles);
options_page->Sound2->addItem("");
options_page->Sound2->addItems(listSoundFiles);
options_page->Sound3->addItem("");
options_page->Sound3->addItems(listSoundFiles);
}
void NotifyPluginOptionsPage::changeButtonText(Phonon::State newstate, Phonon::State oldstate)
{
if(newstate == Phonon::PausedState || newstate == Phonon::StoppedState){
options_page->buttonPlayNotification->setText("Play");
options_page->buttonPlayNotification->setIcon(QPixmap(":/notify/images/play.png"));
}
else
if(newstate == Phonon::PlayingState) {
options_page->buttonPlayNotification->setText("Stop");
options_page->buttonPlayNotification->setIcon(QPixmap(":/notify/images/stop.png"));
}
}
void NotifyPluginOptionsPage::on_buttonTestSoundNotification_clicked()
{
// QList <Phonon::MediaSource> messageNotify;
NotifyPluginConfiguration *notification;
if(notifyRulesSelection->currentIndex().row()==-1) return;
notifySound->clearQueue();
notification = privListNotifications.at(notifyRulesSelection->currentIndex().row());
notification->parseNotifyMessage();
foreach(QString item, notification->getNotifyMessageList())
notifySound->enqueue(Phonon::MediaSource(item));
notifySound->play();
}
void NotifyPluginOptionsPage::on_chkEnableSound_toggled(bool state)
{
bool state1 = 1^state;
QList<Phonon::Path> listOutputs = notifySound->outputPaths();
Phonon::AudioOutput * audioOutput = (Phonon::AudioOutput*)listOutputs.last().sink();
audioOutput->setMuted(state1);
}
void NotifyPluginOptionsPage::updateConfigView(NotifyPluginConfiguration* notification)
{
QString path = notification->getSoundCollectionPath();
if(path=="")
{
//QDir dir = QDir::currentPath();
//path = QDir::currentPath().left(QDir::currentPath().indexOf("OpenPilot",0,Qt::CaseSensitive))+"../share/sounds";
path = "../share/sounds";
}
options_page->SoundDirectoryPathChooser->setPath(path);
if(options_page->SoundCollectionList->findText(notification->getCurrentLanguage())!=-1){
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText(notification->getCurrentLanguage()));
}
else
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
if(options_page->UAVObject->findText(notification->getDataObject())!=-1){
options_page->UAVObject->setCurrentIndex(options_page->UAVObject->findText(notification->getDataObject()));
}
// Now load the object field values:
options_page->UAVObjectField->clear();
QString uavDataObject = notification->getDataObject();
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(uavDataObject/*objList.at(0).at(0)->getName()*/) );
if (obj != NULL ) {
QList<UAVObjectField*> fieldList = obj->getFields();
foreach (UAVObjectField* field, fieldList) {
options_page->UAVObjectField->addItem(field->getName());
}
}
if(options_page->UAVObjectField->findText(notification->getObjectField())!=-1){
options_page->UAVObjectField->setCurrentIndex(options_page->UAVObjectField->findText(notification->getObjectField()));
}
if(options_page->Sound1->findText(notification->getSound1())!=-1){
options_page->Sound1->setCurrentIndex(options_page->Sound1->findText(notification->getSound1()));
}
else
{
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound1->setCurrentIndex(options_page->Sound1->findText(notification->getSound1()));
// don't show item if it wasn't find in stored location
//options_page->Sound1->setCurrentIndex(-1);
}
if(options_page->Sound2->findText(notification->getSound2())!=-1) {
options_page->Sound2->setCurrentIndex(options_page->Sound2->findText(notification->getSound2()));
}
else {
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound2->setCurrentIndex(options_page->Sound2->findText(notification->getSound2()));
// don't show item if it wasn't find in stored location
//options_page->Sound2->setCurrentIndex(-1);
}
if(options_page->Sound3->findText(notification->getSound3())!=-1) {
options_page->Sound3->setCurrentIndex(options_page->Sound3->findText(notification->getSound3()));
}
else {
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound3->setCurrentIndex(options_page->Sound3->findText(notification->getSound3()));
}
if(options_page->Value->findText(notification->getValue())!=-1) {
options_page->Value->setCurrentIndex(options_page->Value->findText(notification->getValue()));
}
if(options_page->SayOrder->findText(notification->getSayOrder())!=-1) {
options_page->SayOrder->setCurrentIndex(options_page->SayOrder->findText(notification->getSayOrder()));
}
options_page->ValueSpinBox->setValue(notification->getSpinBoxValue());
}
void NotifyPluginOptionsPage::on_tableNotification_changeSelection( const QItemSelection & selected, const QItemSelection & deselected )
{
bool select = true;
notifySound->stop();
if(selected.indexes().size())
updateConfigView(privListNotifications.at(selected.indexes().at(0).row()));
else
select = false;
options_page->buttonModify->setEnabled(select);
options_page->buttonDelete->setEnabled(select);
options_page->buttonPlayNotification->setEnabled(select);
}
void NotifyPluginOptionsPage::on_buttonAddNotification_clicked()
{
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
if(options_page->SoundDirectoryPathChooser->path()=="")
{
QPalette textPalette=options_page->SoundDirectoryPathChooser->palette();
textPalette.setColor(QPalette::Normal,QPalette::Text, Qt::red);
options_page->SoundDirectoryPathChooser->setPalette(textPalette);
options_page->SoundDirectoryPathChooser->setPath("please select sound collection folder");
return;
}
notification->setSoundCollectionPath(options_page->SoundDirectoryPathChooser->path());
notification->setCurrentLanguage(options_page->SoundCollectionList->currentText());
notification->setDataObject(options_page->UAVObject->currentText());
notification->setObjectField(options_page->UAVObjectField->currentText());
notification->setValue(options_page->Value->currentText());
notification->setSpinBoxValue(options_page->ValueSpinBox->value());
if(options_page->Sound1->currentText()!="")
notification->setSound1(options_page->Sound1->currentText());
notification->setSound2(options_page->Sound2->currentText());
notification->setSound3(options_page->Sound3->currentText());
if(((options_page->Sound2->currentText()=="")&&(options_page->SayOrder->currentText()=="After second"))
|| ((options_page->Sound3->currentText()=="")&&(options_page->SayOrder->currentText()=="After third")))
return;
else
notification->setSayOrder(options_page->SayOrder->currentText());
privListNotifications.append(notification);
emit entryAdded(privListNotifications.size()-1);
notifyRulesSelection->setCurrentIndex(notifyRulesModel->index(privListNotifications.size()-1,0,QModelIndex()),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void NotifyPluginOptionsPage::on_buttonDeleteNotification_clicked()
{
notifyRulesModel->removeRow(notifyRulesSelection->currentIndex().row());
if(!notifyRulesModel->rowCount() && (notifyRulesSelection->currentIndex().row() > 0 && notifyRulesSelection->currentIndex().row() < notifyRulesModel->rowCount()))
{
options_page->buttonDelete->setEnabled(false);
options_page->buttonModify->setEnabled(false);
options_page->buttonPlayNotification->setEnabled(false);
}
}
void NotifyPluginOptionsPage::on_buttonModifyNotification_clicked()
{
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
getOptionsPageValues(notification);
notification->setRepeatFlag(privListNotifications.at(notifyRulesSelection->currentIndex().row())->getRepeatFlag());
privListNotifications.replace(notifyRulesSelection->currentIndex().row(),notification);
entryUpdated(notifyRulesSelection->currentIndex().row());
}
/**
******************************************************************************
*
* @file notifypluginoptionspage.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin options page
* @see The GNU Public License (GPL) Version 3
* @defgroup notifyplugin
* @{
*
*****************************************************************************/
/*
* 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 "notifypluginoptionspage.h"
#include <coreplugin/icore.h>
#include "notifypluginconfiguration.h"
#include "ui_notifypluginoptionspage.h"
#include "extensionsystem/pluginmanager.h"
#include "utils/pathutils.h"
#include <QFileDialog>
#include <QtAlgorithms>
#include <QStringList>
#include <QtCore/QSettings>
#include <QTableWidget>
#include <QPalette>
#include <QBuffer>
#include "notifyplugin.h"
#include "notifyitemdelegate.h"
#include "notifytablemodel.h"
NotifyPluginOptionsPage::NotifyPluginOptionsPage(/*NotifyPluginConfiguration *config,*/ QObject *parent) :
IOptionsPage(parent),
owner((SoundNotifyPlugin*)parent),
currentCollectionPath(""),
privListNotifications(((SoundNotifyPlugin*)parent)->getListNotifications())
{
}
//creates options page widget (uses the UI file)
QWidget *NotifyPluginOptionsPage::createPage(QWidget *parent)
{
options_page = new Ui::NotifyPluginOptionsPage();
//main widget
QWidget *optionsPageWidget = new QWidget;
//main layout
options_page->setupUi(optionsPageWidget);
delegateItems.clear();
listSoundFiles.clear();
delegateItems << "Repeat Once"
<< "Repeat Instantly"
<< "Repeat 10 seconds"
<< "Repeat 30 seconds"
<< "Repeat 1 minute";
options_page->chkEnableSound->setChecked(owner->getEnableSound());
options_page->SoundDirectoryPathChooser->setExpectedKind(Utils::PathChooser::Directory);
options_page->SoundDirectoryPathChooser->setPromptDialogTitle(tr("Choose sound collection directory"));
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
objManager = pm->getObject<UAVObjectManager>();
// Fills the combo boxes for the UAVObjects
QList< QList<UAVDataObject*> > objList = objManager->getDataObjects();
foreach (QList<UAVDataObject*> list, objList) {
foreach (UAVDataObject* obj, list) {
options_page->UAVObject->addItem(obj->getName());
}
}
connect(options_page->SoundDirectoryPathChooser, SIGNAL(changed(const QString&)), this, SLOT(on_buttonSoundFolder_clicked(const QString&)));
connect(options_page->SoundCollectionList, SIGNAL(currentIndexChanged (int)), this, SLOT(on_soundLanguage_indexChanged(int)));
connect(options_page->buttonAdd, SIGNAL(pressed()), this, SLOT(on_buttonAddNotification_clicked()));
connect(options_page->buttonDelete, SIGNAL(pressed()), this, SLOT(on_buttonDeleteNotification_clicked()));
connect(options_page->buttonModify, SIGNAL(pressed()), this, SLOT(on_buttonModifyNotification_clicked()));
// connect(options_page->buttonTestSound1, SIGNAL(clicked()), this, SLOT(on_buttonTestSound1_clicked()));
// connect(options_page->buttonTestSound2, SIGNAL(clicked()), this, SLOT(on_buttonTestSound2_clicked()));
connect(options_page->buttonPlayNotification, SIGNAL(clicked()), this, SLOT(on_buttonTestSoundNotification_clicked()));
connect(options_page->chkEnableSound, SIGNAL(toggled(bool)), this, SLOT(on_chkEnableSound_toggled(bool)));
connect(options_page->UAVObject, SIGNAL(currentIndexChanged(QString)), this, SLOT(on_UAVObject_indexChanged(QString)));
connect(this, SIGNAL(updateNotifications(QList<NotifyPluginConfiguration*>)),
owner, SLOT(updateNotificationList(QList<NotifyPluginConfiguration*>)));
connect(this, SIGNAL(resetNotification()),owner, SLOT(resetNotification()));
//emit resetNotification();
privListNotifications.clear();
for (int i = 0; i < owner->getListNotifications().size(); ++i) {
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration();
owner->getListNotifications().at(i)->copyTo(notification);
privListNotifications.append(notification);
}
updateConfigView(owner->getCurrentNotification());
options_page->chkEnableSound->setChecked(owner->getEnableSound());
QStringList headerStrings;
headerStrings << "Name" << "Repeats" << "Lifetime,sec";
notifyRulesModel = new NotifyTableModel(&privListNotifications,headerStrings);
options_page->notifyRulesView->setModel(notifyRulesModel);
options_page->notifyRulesView->resizeRowsToContents();
notifyRulesSelection = new QItemSelectionModel(notifyRulesModel);
connect(notifyRulesSelection, SIGNAL(selectionChanged ( const QItemSelection &, const QItemSelection & )),
this, SLOT(on_tableNotification_changeSelection( const QItemSelection & , const QItemSelection & )));
connect(this, SIGNAL(entryUpdated(int)),
notifyRulesModel, SLOT(entryUpdated(int)));
connect(this, SIGNAL(entryAdded(int)),
notifyRulesModel, SLOT(entryAdded(int)));
options_page->notifyRulesView->setSelectionModel(notifyRulesSelection);
options_page->notifyRulesView->setItemDelegate(new NotifyItemDelegate(delegateItems,this));
options_page->notifyRulesView->setColumnWidth(0,200);
options_page->notifyRulesView->setColumnWidth(1,150);
options_page->notifyRulesView->setColumnWidth(2,100);
options_page->buttonModify->setEnabled(false);
options_page->buttonDelete->setEnabled(false);
options_page->buttonPlayNotification->setEnabled(false);
// sound1 = Phonon::createPlayer(Phonon::NotificationCategory);
// sound2 = Phonon::createPlayer(Phonon::NotificationCategory);
notifySound = Phonon::createPlayer(Phonon::NotificationCategory);
// audioOutput = new Phonon::AudioOutput(Phonon::NotificationCategory, this);
// Phonon::createPath(sound1, audioOutput);
// Phonon::createPath(sound2, audioOutput);
// Phonon::createPath(notifySound, audioOutput);
// connect(sound1,SIGNAL(stateChanged(Phonon::State,Phonon::State)),SLOT(changeButtonText(Phonon::State,Phonon::State)));
// connect(sound2,SIGNAL(stateChanged(Phonon::State,Phonon::State)),SLOT(changeButtonText(Phonon::State,Phonon::State)));
connect(notifySound,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(changeButtonText(Phonon::State,Phonon::State)));
return optionsPageWidget;
}
void NotifyPluginOptionsPage::showPersistentComboBox( const QModelIndex & parent, int start, int end )
{
// for (int i=start; i<end+1; i++) {
// options_page->tableNotifications->openPersistentEditor(options_page->tableNotifications->item(i,1));
// }
}
void NotifyPluginOptionsPage::showPersistentComboBox2( const QModelIndex & topLeft, const QModelIndex & bottomRight )
{
//for (QModelIndex i=topLeft; i<bottomRight+1; i++)
{
// options_page->tableNotifications->openPersistentEditor(options_page->tableNotifications->item(options_page->tableNotifications->currentRow(),1));
}
}
void NotifyPluginOptionsPage::getOptionsPageValues(NotifyPluginConfiguration* notification)
{
notification->setSoundCollectionPath(options_page->SoundDirectoryPathChooser->path());
notification->setCurrentLanguage(options_page->SoundCollectionList->currentText());
notification->setDataObject(options_page->UAVObject->currentText());
notification->setObjectField(options_page->UAVObjectField->currentText());
notification->setSound1(options_page->Sound1->currentText());
notification->setSound2(options_page->Sound2->currentText());
notification->setSound3(options_page->Sound3->currentText());
notification->setSayOrder(options_page->SayOrder->currentText());
notification->setValue(options_page->Value->currentText());
notification->setSpinBoxValue(options_page->ValueSpinBox->value());
// if(notifyRulesSelection->currentIndex().row()>-1)
// {
// //qDebug() << "delegate value:" << options_page->tableNotifications->item(options_page->tableNotifications->currentRow(),1)->data(Qt::EditRole);
// notification->setRepeatFlag(notifyRulesModel->data(notifyRulesSelection->currentIndex(),Qt::DisplayRole).toString());
// }
}
////////////////////////////////////////////
// Called when the user presses apply or OK.
//
// Saves the current values
//
////////////////////////////////////////////
void NotifyPluginOptionsPage::apply()
{
getOptionsPageValues(owner->getCurrentNotification());
owner->setEnableSound(options_page->chkEnableSound->isChecked());
//owner->setListNotifications(privListNotifications);
emit updateNotifications(privListNotifications);
}
void NotifyPluginOptionsPage::finish()
{
disconnect(notifySound,SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this,SLOT(changeButtonText(Phonon::State,Phonon::State)));
if(notifySound)
{
notifySound->stop();
notifySound->clear();
}
delete options_page;
}
//////////////////////////////////////////////////////////////////////////////
// Fills in the <Field> combo box when value is changed in the
// <Object> combo box
//////////////////////////////////////////////////////////////////////////////
void NotifyPluginOptionsPage::on_UAVObject_indexChanged(QString val) {
options_page->UAVObjectField->clear();
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(val) );
QList<UAVObjectField*> fieldList = obj->getFields();
foreach (UAVObjectField* field, fieldList) {
options_page->UAVObjectField->addItem(field->getName());
}
}
// locate collection folder on disk
void NotifyPluginOptionsPage::on_buttonSoundFolder_clicked(const QString& path)
{
QDir dirPath(path);
listDirCollections = dirPath.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
options_page->SoundCollectionList->clear();
options_page->SoundCollectionList->addItems(listDirCollections);
}
void NotifyPluginOptionsPage::on_soundLanguage_indexChanged(int index)
{
options_page->SoundCollectionList->setCurrentIndex(index);
currentCollectionPath = options_page->SoundDirectoryPathChooser->path() +
QDir::toNativeSeparators("/" + options_page->SoundCollectionList->currentText());
QDir dirPath(currentCollectionPath);
QStringList filters;
filters << "*.mp3" << "*.wav";
dirPath.setNameFilters(filters);
listSoundFiles = dirPath.entryList(filters);
listSoundFiles.replaceInStrings(QRegExp(".mp3|.wav"), "");
options_page->Sound1->clear();
options_page->Sound2->clear();
options_page->Sound3->clear();
options_page->Sound1->addItems(listSoundFiles);
options_page->Sound2->addItem("");
options_page->Sound2->addItems(listSoundFiles);
options_page->Sound3->addItem("");
options_page->Sound3->addItems(listSoundFiles);
}
void NotifyPluginOptionsPage::changeButtonText(Phonon::State newstate, Phonon::State oldstate)
{
if(newstate == Phonon::PausedState || newstate == Phonon::StoppedState){
options_page->buttonPlayNotification->setText("Play");
options_page->buttonPlayNotification->setIcon(QPixmap(":/notify/images/play.png"));
}
else
if(newstate == Phonon::PlayingState) {
options_page->buttonPlayNotification->setText("Stop");
options_page->buttonPlayNotification->setIcon(QPixmap(":/notify/images/stop.png"));
}
}
void NotifyPluginOptionsPage::on_buttonTestSoundNotification_clicked()
{
// QList <Phonon::MediaSource> messageNotify;
NotifyPluginConfiguration *notification;
if(notifyRulesSelection->currentIndex().row()==-1) return;
notifySound->clearQueue();
notification = privListNotifications.at(notifyRulesSelection->currentIndex().row());
notification->parseNotifyMessage();
foreach(QString item, notification->getNotifyMessageList())
notifySound->enqueue(Phonon::MediaSource(item));
notifySound->play();
}
void NotifyPluginOptionsPage::on_chkEnableSound_toggled(bool state)
{
bool state1 = 1^state;
QList<Phonon::Path> listOutputs = notifySound->outputPaths();
Phonon::AudioOutput * audioOutput = (Phonon::AudioOutput*)listOutputs.last().sink();
audioOutput->setMuted(state1);
}
void NotifyPluginOptionsPage::updateConfigView(NotifyPluginConfiguration* notification)
{
QString path = notification->getSoundCollectionPath();
if(path=="")
{
//QDir dir = QDir::currentPath();
//path = QDir::currentPath().left(QDir::currentPath().indexOf("OpenPilot",0,Qt::CaseSensitive))+"../share/sounds";
path = Utils::PathUtils().InsertDataPath("%%DATAPATH%%sounds");
}
options_page->SoundDirectoryPathChooser->setPath(path);
if(options_page->SoundCollectionList->findText(notification->getCurrentLanguage())!=-1){
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText(notification->getCurrentLanguage()));
}
else
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
if(options_page->UAVObject->findText(notification->getDataObject())!=-1){
options_page->UAVObject->setCurrentIndex(options_page->UAVObject->findText(notification->getDataObject()));
}
// Now load the object field values:
options_page->UAVObjectField->clear();
QString uavDataObject = notification->getDataObject();
UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(uavDataObject/*objList.at(0).at(0)->getName()*/) );
if (obj != NULL ) {
QList<UAVObjectField*> fieldList = obj->getFields();
foreach (UAVObjectField* field, fieldList) {
options_page->UAVObjectField->addItem(field->getName());
}
}
if(options_page->UAVObjectField->findText(notification->getObjectField())!=-1){
options_page->UAVObjectField->setCurrentIndex(options_page->UAVObjectField->findText(notification->getObjectField()));
}
if(options_page->Sound1->findText(notification->getSound1())!=-1){
options_page->Sound1->setCurrentIndex(options_page->Sound1->findText(notification->getSound1()));
}
else
{
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound1->setCurrentIndex(options_page->Sound1->findText(notification->getSound1()));
// don't show item if it wasn't find in stored location
//options_page->Sound1->setCurrentIndex(-1);
}
if(options_page->Sound2->findText(notification->getSound2())!=-1) {
options_page->Sound2->setCurrentIndex(options_page->Sound2->findText(notification->getSound2()));
}
else {
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound2->setCurrentIndex(options_page->Sound2->findText(notification->getSound2()));
// don't show item if it wasn't find in stored location
//options_page->Sound2->setCurrentIndex(-1);
}
if(options_page->Sound3->findText(notification->getSound3())!=-1) {
options_page->Sound3->setCurrentIndex(options_page->Sound3->findText(notification->getSound3()));
}
else {
// show item from default location
options_page->SoundCollectionList->setCurrentIndex(options_page->SoundCollectionList->findText("default"));
options_page->Sound3->setCurrentIndex(options_page->Sound3->findText(notification->getSound3()));
}
if(options_page->Value->findText(notification->getValue())!=-1) {
options_page->Value->setCurrentIndex(options_page->Value->findText(notification->getValue()));
}
if(options_page->SayOrder->findText(notification->getSayOrder())!=-1) {
options_page->SayOrder->setCurrentIndex(options_page->SayOrder->findText(notification->getSayOrder()));
}
options_page->ValueSpinBox->setValue(notification->getSpinBoxValue());
}
void NotifyPluginOptionsPage::on_tableNotification_changeSelection( const QItemSelection & selected, const QItemSelection & deselected )
{
bool select = true;
notifySound->stop();
if(selected.indexes().size())
updateConfigView(privListNotifications.at(selected.indexes().at(0).row()));
else
select = false;
options_page->buttonModify->setEnabled(select);
options_page->buttonDelete->setEnabled(select);
options_page->buttonPlayNotification->setEnabled(select);
}
void NotifyPluginOptionsPage::on_buttonAddNotification_clicked()
{
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
if(options_page->SoundDirectoryPathChooser->path()=="")
{
QPalette textPalette=options_page->SoundDirectoryPathChooser->palette();
textPalette.setColor(QPalette::Normal,QPalette::Text, Qt::red);
options_page->SoundDirectoryPathChooser->setPalette(textPalette);
options_page->SoundDirectoryPathChooser->setPath("please select sound collection folder");
return;
}
notification->setSoundCollectionPath(options_page->SoundDirectoryPathChooser->path());
notification->setCurrentLanguage(options_page->SoundCollectionList->currentText());
notification->setDataObject(options_page->UAVObject->currentText());
notification->setObjectField(options_page->UAVObjectField->currentText());
notification->setValue(options_page->Value->currentText());
notification->setSpinBoxValue(options_page->ValueSpinBox->value());
if(options_page->Sound1->currentText()!="")
notification->setSound1(options_page->Sound1->currentText());
notification->setSound2(options_page->Sound2->currentText());
notification->setSound3(options_page->Sound3->currentText());
if(((options_page->Sound2->currentText()=="")&&(options_page->SayOrder->currentText()=="After second"))
|| ((options_page->Sound3->currentText()=="")&&(options_page->SayOrder->currentText()=="After third")))
return;
else
notification->setSayOrder(options_page->SayOrder->currentText());
privListNotifications.append(notification);
emit entryAdded(privListNotifications.size()-1);
notifyRulesSelection->setCurrentIndex(notifyRulesModel->index(privListNotifications.size()-1,0,QModelIndex()),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void NotifyPluginOptionsPage::on_buttonDeleteNotification_clicked()
{
notifyRulesModel->removeRow(notifyRulesSelection->currentIndex().row());
if(!notifyRulesModel->rowCount() && (notifyRulesSelection->currentIndex().row() > 0 && notifyRulesSelection->currentIndex().row() < notifyRulesModel->rowCount()))
{
options_page->buttonDelete->setEnabled(false);
options_page->buttonModify->setEnabled(false);
options_page->buttonPlayNotification->setEnabled(false);
}
}
void NotifyPluginOptionsPage::on_buttonModifyNotification_clicked()
{
NotifyPluginConfiguration* notification = new NotifyPluginConfiguration;
getOptionsPageValues(notification);
notification->setRepeatFlag(privListNotifications.at(notifyRulesSelection->currentIndex().row())->getRepeatFlag());
privListNotifications.replace(notifyRulesSelection->currentIndex().row(),notification);
entryUpdated(notifyRulesSelection->currentIndex().row());
}

View File

@ -1,122 +1,121 @@
/**
******************************************************************************
*
* @file notifypluginoptionspage.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin options page header
* @see The GNU Public License (GPL) Version 3
* @defgroup notify
* @{
*
*****************************************************************************/
/*
* 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 NOTIFYPLUGINOPTIONSPAGE_H
#define NOTIFYPLUGINOPTIONSPAGE_H
#include "coreplugin/dialogs/ioptionspage.h"
#include "uavobjectmanager.h"
#include "uavobject.h"
#include "QString"
#include <QStringList>
#include <QItemSelectionModel>
#include <QDebug>
#include <QtCore/QSettings>
#include <phonon>
class NotifyTableModel;
class NotifyPluginConfiguration;
class SoundNotifyPlugin;
namespace Ui {
class NotifyPluginOptionsPage;
}
using namespace Core;
class NotifyPluginOptionsPage : public IOptionsPage
{
Q_OBJECT
public:
explicit NotifyPluginOptionsPage(/*NotifyPluginConfiguration *config, */QObject *parent = 0);
QString id() const { return QLatin1String("settings"); }
QString trName() const { return tr("settings"); }
QString category() const { return QLatin1String("Notify Plugin");}
QString trCategory() const { return tr("Notify Plugin");}
QWidget *createPage(QWidget *parent);
void apply();
void finish();
void restoreFromSettings();
void updateConfigView(NotifyPluginConfiguration* notification);
void getOptionsPageValues(NotifyPluginConfiguration* notification);
private:
UAVObjectManager *objManager;
SoundNotifyPlugin* owner;
QSettings* settings;
QStringList listDirCollections;
QStringList listSoundFiles;
QString currentCollectionPath;
int sizeNotifyList;
Phonon::MediaObject *sound1;
Phonon::MediaObject *sound2;
Phonon::MediaObject *notifySound;
Phonon::AudioOutput *audioOutput;
QStringList delegateItems;
NotifyTableModel* notifyRulesModel;
QItemSelectionModel *notifyRulesSelection;
QList<NotifyPluginConfiguration*> privListNotifications;
Ui::NotifyPluginOptionsPage *options_page;
//NotifyPluginConfiguration *notify;
signals:
void updateNotifications(QList<NotifyPluginConfiguration*> list);
void resetNotification(void);
void entryUpdated(int index);
void entryAdded(int position);
private slots:
void showPersistentComboBox( const QModelIndex & parent, int start, int end );
void showPersistentComboBox2 ( const QModelIndex & topLeft, const QModelIndex & bottomRight );
// void on_buttonTestSound1_clicked();
// void on_buttonTestSound2_clicked();
void on_buttonTestSoundNotification_clicked();
void on_buttonAddNotification_clicked();
void on_buttonDeleteNotification_clicked();
void on_buttonModifyNotification_clicked();
void on_tableNotification_changeSelection( const QItemSelection & selected, const QItemSelection & deselected );
void on_soundLanguage_indexChanged(int index);
void on_buttonSoundFolder_clicked(const QString& path);
void on_UAVObject_indexChanged(QString val);
void changeButtonText(Phonon::State newstate, Phonon::State oldstate);
void on_chkEnableSound_toggled(bool state);
};
#endif // NOTIFYPLUGINOPTIONSPAGE_H
/**
******************************************************************************
*
* @file notifypluginoptionspage.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Notify Plugin options page header
* @see The GNU Public License (GPL) Version 3
* @defgroup notify
* @{
*
*****************************************************************************/
/*
* 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 NOTIFYPLUGINOPTIONSPAGE_H
#define NOTIFYPLUGINOPTIONSPAGE_H
#include "coreplugin/dialogs/ioptionspage.h"
#include "uavobjectmanager.h"
#include "uavobject.h"
#include "QString"
#include <QStringList>
#include <QItemSelectionModel>
#include <QDebug>
#include <QtCore/QSettings>
#include <phonon>
class NotifyTableModel;
class NotifyPluginConfiguration;
class SoundNotifyPlugin;
namespace Ui {
class NotifyPluginOptionsPage;
}
using namespace Core;
class NotifyPluginOptionsPage : public IOptionsPage
{
Q_OBJECT
public:
explicit NotifyPluginOptionsPage(/*NotifyPluginConfiguration *config, */QObject *parent = 0);
QString id() const { return QLatin1String("settings"); }
QString trName() const { return tr("settings"); }
QString category() const { return QLatin1String("Notify Plugin");}
QString trCategory() const { return tr("Notify Plugin");}
QWidget *createPage(QWidget *parent);
void apply();
void finish();
void restoreFromSettings();
void updateConfigView(NotifyPluginConfiguration* notification);
void getOptionsPageValues(NotifyPluginConfiguration* notification);
private:
UAVObjectManager *objManager;
SoundNotifyPlugin* owner;
QStringList listDirCollections;
QStringList listSoundFiles;
QString currentCollectionPath;
int sizeNotifyList;
Phonon::MediaObject *sound1;
Phonon::MediaObject *sound2;
Phonon::MediaObject *notifySound;
Phonon::AudioOutput *audioOutput;
QStringList delegateItems;
NotifyTableModel* notifyRulesModel;
QItemSelectionModel *notifyRulesSelection;
QList<NotifyPluginConfiguration*> privListNotifications;
Ui::NotifyPluginOptionsPage *options_page;
//NotifyPluginConfiguration *notify;
signals:
void updateNotifications(QList<NotifyPluginConfiguration*> list);
void resetNotification(void);
void entryUpdated(int index);
void entryAdded(int position);
private slots:
void showPersistentComboBox( const QModelIndex & parent, int start, int end );
void showPersistentComboBox2 ( const QModelIndex & topLeft, const QModelIndex & bottomRight );
// void on_buttonTestSound1_clicked();
// void on_buttonTestSound2_clicked();
void on_buttonTestSoundNotification_clicked();
void on_buttonAddNotification_clicked();
void on_buttonDeleteNotification_clicked();
void on_buttonModifyNotification_clicked();
void on_tableNotification_changeSelection( const QItemSelection & selected, const QItemSelection & deselected );
void on_soundLanguage_indexChanged(int index);
void on_buttonSoundFolder_clicked(const QString& path);
void on_UAVObject_indexChanged(QString val);
void changeButtonText(Phonon::State newstate, Phonon::State oldstate);
void on_chkEnableSound_toggled(bool state);
};
#endif // NOTIFYPLUGINOPTIONSPAGE_H