1
0
mirror of https://bitbucket.org/librepilot/librepilot.git synced 2025-02-20 10:54:14 +01:00

Merged in filnet/librepilot/LP-513_gcs_remove_unused_code (pull request #417)

LP-513 gcs remove unused code

Approved-by: Philippe Renon <philippe_renon@yahoo.fr>
Approved-by: Lalanne Laurent <f5soh@free.fr>
Approved-by: Brian Webb <webbbn@gmail.com>
Approved-by: Alessio Morale <alessiomorale@gmail.com>
This commit is contained in:
Philippe Renon 2017-05-15 19:49:35 +00:00 committed by Lalanne Laurent
commit 03ec59b6a6
45 changed files with 0 additions and 6186 deletions

View File

@ -4,7 +4,6 @@ CONFIG += ordered
SUBDIRS = \
version_info \
qscispinbox\
qtconcurrent \
aggregation \
extensionsystem \
utils \

View File

@ -1,31 +0,0 @@
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qtconcurrent/multitask.h"
#include "qtconcurrent/runextensions.h"

View File

@ -1,199 +0,0 @@
/**
******************************************************************************
*
* @file multitask.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MULTITASK_H
#define MULTITASK_H
#include "qtconcurrent_global.h"
#include "runextensions.h"
#include <QtCore/QObject>
#include <QtCore/QList>
#include <QtCore/QEventLoop>
#include <QtCore/QFutureWatcher>
#include <QtConcurrent/QtConcurrentRun>
#include <QtCore/QThreadPool>
#include <QtDebug>
QT_BEGIN_NAMESPACE
namespace QtConcurrent {
class QTCONCURRENT_EXPORT MultiTaskBase : public QObject, public QRunnable {
Q_OBJECT
protected slots:
virtual void cancelSelf() = 0;
virtual void setFinished() = 0;
virtual void setProgressRange(int min, int max) = 0;
virtual void setProgressValue(int value) = 0;
virtual void setProgressText(QString value) = 0;
};
template <typename Class, typename R>
class MultiTask : public MultiTaskBase {
public:
MultiTask(void(Class::*fn)(QFutureInterface<R> &), const QList<Class *> &objects)
: fn(fn),
objects(objects)
{
maxProgress = 100 * objects.size();
}
QFuture<R> future()
{
futureInterface.reportStarted();
return futureInterface.future();
}
void run()
{
QThreadPool::globalInstance()->releaseThread();
futureInterface.setProgressRange(0, maxProgress);
foreach(Class * object, objects) {
QFutureWatcher<R> *watcher = new QFutureWatcher<R>();
watchers.insert(object, watcher);
finished.insert(watcher, false);
connect(watcher, SIGNAL(finished()), this, SLOT(setFinished()));
connect(watcher, SIGNAL(progressRangeChanged(int, int)), this, SLOT(setProgressRange(int, int)));
connect(watcher, SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int)));
connect(watcher, SIGNAL(progressTextChanged(QString)), this, SLOT(setProgressText(QString)));
watcher->setFuture(QtConcurrent::run(fn, object));
}
selfWatcher = new QFutureWatcher<R>();
connect(selfWatcher, SIGNAL(canceled()), this, SLOT(cancelSelf()));
selfWatcher->setFuture(futureInterface.future());
loop = new QEventLoop;
loop->exec();
futureInterface.reportFinished();
QThreadPool::globalInstance()->reserveThread();
qDeleteAll(watchers.values());
delete selfWatcher;
delete loop;
}
protected:
void cancelSelf()
{
foreach(QFutureWatcher<R> *watcher, watchers)
watcher->future().cancel();
}
void setFinished()
{
updateProgress();
QFutureWatcher<R> *watcher = static_cast<QFutureWatcher<R> *>(sender());
if (finished.contains(watcher)) {
finished[watcher] = true;
}
bool allFinished = true;
const QList<bool> finishedValues = finished.values();
foreach(bool isFinished, finishedValues) {
if (!isFinished) {
allFinished = false;
break;
}
}
if (allFinished) {
loop->quit();
}
}
void setProgressRange(int min, int max)
{
Q_UNUSED(min)
Q_UNUSED(max)
updateProgress();
}
void setProgressValue(int value)
{
Q_UNUSED(value)
updateProgress();
}
void setProgressText(QString value)
{
Q_UNUSED(value)
updateProgressText();
}
private:
void updateProgress()
{
int progressSum = 0;
const QList<QFutureWatcher<R> *> watchersValues = watchers.values();
foreach(QFutureWatcher<R> *watcher, watchersValues) {
if (watcher->progressMinimum() == watcher->progressMaximum()) {
if (watcher->future().isFinished() && !watcher->future().isCanceled()) {
progressSum += 100;
}
} else {
progressSum += 100 * (watcher->progressValue() - watcher->progressMinimum()) / (watcher->progressMaximum() - watcher->progressMinimum());
}
}
futureInterface.setProgressValue(progressSum);
}
void updateProgressText()
{
QString text;
const QList<QFutureWatcher<R> *> watchersValues = watchers.values();
foreach(QFutureWatcher<R> *watcher, watchersValues) {
if (!watcher->progressText().isEmpty()) {
text += watcher->progressText() + "\n";
}
}
text = text.trimmed();
futureInterface.setProgressValueAndText(futureInterface.progressValue(), text);
}
QFutureInterface<R> futureInterface;
void (Class::*fn)(QFutureInterface<R> &);
QList<Class *> objects;
QFutureWatcher<R> *selfWatcher;
QMap<Class *, QFutureWatcher<R> *> watchers;
QMap<QFutureWatcher<R> *, bool> finished;
QEventLoop *loop;
int maxProgress;
};
template <typename Class, typename T>
QFuture<T> run(void (Class::*fn)(QFutureInterface<T> &), const QList<Class *> &objects, int priority = 0)
{
MultiTask<Class, T> *task = new MultiTask<Class, T>(fn, objects);
QFuture<T> future = task->future();
QThreadPool::globalInstance()->start(task, priority);
return future;
}
} // namespace QtConcurrent
QT_END_NAMESPACE
#endif // MULTITASK_H

View File

@ -1 +0,0 @@
LIBS *= -l$$qtLibraryName(QtConcurrent)

View File

@ -1,10 +0,0 @@
TEMPLATE = lib
TARGET = QtConcurrent
DEFINES += BUILD_QTCONCURRENT
include(../../library.pri)
HEADERS += \
qtconcurrent_global.h \
multitask.h \
runextensions.h

View File

@ -1,40 +0,0 @@
/**
******************************************************************************
*
* @file qtconcurrent_global.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef QTCONCURRENT_GLOBAL_H
#define QTCONCURRENT_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(BUILD_QTCONCURRENT)
# define QTCONCURRENT_EXPORT Q_DECL_EXPORT
#else
# define QTCONCURRENT_EXPORT Q_DECL_IMPORT
#endif
#endif // QTCONCURRENT_GLOBAL_H

View File

@ -1,377 +0,0 @@
/**
******************************************************************************
*
* @file runextensions.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef QTCONCURRENT_RUNEX_H
#define QTCONCURRENT_RUNEX_H
#include <qrunnable.h>
#include <qfutureinterface.h>
#include <qthreadpool.h>
QT_BEGIN_NAMESPACE
namespace QtConcurrent {
template <typename T, typename FunctionPointer>
class StoredInterfaceFunctionCall0 : public QRunnable {
public:
StoredInterfaceFunctionCall0(void(fn)(QFutureInterface<T> &))
: fn(fn) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
};
template <typename T, typename FunctionPointer, typename Class>
class StoredInterfaceMemberFunctionCall0 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall0(void(Class::*fn)(QFutureInterface<T> &), Class *object)
: fn(fn), object(object) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
};
template <typename T, typename FunctionPointer, typename Arg1>
class StoredInterfaceFunctionCall1 : public QRunnable {
public:
StoredInterfaceFunctionCall1(void(fn)(QFutureInterface<T> &, Arg1), Arg1 arg1)
: fn(fn), arg1(arg1) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface, arg1);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Arg1 arg1;
};
template <typename T, typename FunctionPointer, typename Class, typename Arg1>
class StoredInterfaceMemberFunctionCall1 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall1(void(Class::*fn)(QFutureInterface<T> &, Arg1), Class *object, Arg1 arg1)
: fn(fn), object(object), arg1(arg1) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface, arg1);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
Arg1 arg1;
};
template <typename T, typename FunctionPointer, typename Arg1, typename Arg2>
class StoredInterfaceFunctionCall2 : public QRunnable {
public:
StoredInterfaceFunctionCall2(void(fn)(QFutureInterface<T> &, Arg1, Arg2), Arg1 arg1, Arg2 arg2)
: fn(fn), arg1(arg1), arg2(arg2) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface, arg1, arg2);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Arg1 arg1; Arg2 arg2;
};
template <typename T, typename FunctionPointer, typename Class, typename Arg1, typename Arg2>
class StoredInterfaceMemberFunctionCall2 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall2(void(Class::*fn)(QFutureInterface<T> &, Arg1, Arg2), Class *object, Arg1 arg1, Arg2 arg2)
: fn(fn), object(object), arg1(arg1), arg2(arg2) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface, arg1, arg2);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
Arg1 arg1; Arg2 arg2;
};
template <typename T, typename FunctionPointer, typename Arg1, typename Arg2, typename Arg3>
class StoredInterfaceFunctionCall3 : public QRunnable {
public:
StoredInterfaceFunctionCall3(void(fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3), Arg1 arg1, Arg2 arg2, Arg3 arg3)
: fn(fn), arg1(arg1), arg2(arg2), arg3(arg3) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface, arg1, arg2, arg3);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Arg1 arg1; Arg2 arg2; Arg3 arg3;
};
template <typename T, typename FunctionPointer, typename Class, typename Arg1, typename Arg2, typename Arg3>
class StoredInterfaceMemberFunctionCall3 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall3(void(Class::*fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3), Class *object, Arg1 arg1, Arg2 arg2, Arg3 arg3)
: fn(fn), object(object), arg1(arg1), arg2(arg2), arg3(arg3) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface, arg1, arg2, arg3);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
Arg1 arg1; Arg2 arg2; Arg3 arg3;
};
template <typename T, typename FunctionPointer, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
class StoredInterfaceFunctionCall4 : public QRunnable {
public:
StoredInterfaceFunctionCall4(void(fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4)
: fn(fn), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface, arg1, arg2, arg3, arg4);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Arg1 arg1; Arg2 arg2; Arg3 arg3; Arg4 arg4;
};
template <typename T, typename FunctionPointer, typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
class StoredInterfaceMemberFunctionCall4 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall4(void(Class::*fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4), Class *object, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4)
: fn(fn), object(object), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface, arg1, arg2, arg3, arg4);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
Arg1 arg1; Arg2 arg2; Arg3 arg3; Arg4 arg4;
};
template <typename T, typename FunctionPointer, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5>
class StoredInterfaceFunctionCall5 : public QRunnable {
public:
StoredInterfaceFunctionCall5(void(fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4, Arg5), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5)
: fn(fn), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
fn(futureInterface, arg1, arg2, arg3, arg4, arg5);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Arg1 arg1; Arg2 arg2; Arg3 arg3; Arg4 arg4; Arg5 arg5;
};
template <typename T, typename FunctionPointer, typename Class, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5>
class StoredInterfaceMemberFunctionCall5 : public QRunnable {
public:
StoredInterfaceMemberFunctionCall5(void(Class::*fn)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4, Arg5), Class *object, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5)
: fn(fn), object(object), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) {}
QFuture<T> start()
{
futureInterface.reportStarted();
QFuture<T> future = futureInterface.future();
QThreadPool::globalInstance()->start(this);
return future;
}
void run()
{
(object->*fn)(futureInterface, arg1, arg2, arg3, arg4, arg5);
futureInterface.reportFinished();
}
private:
QFutureInterface<T> futureInterface;
FunctionPointer fn;
Class *object;
Arg1 arg1; Arg2 arg2; Arg3 arg3; Arg4 arg4; Arg5 arg5;
};
template <typename T>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &))
{
return (new StoredInterfaceFunctionCall0<T, void (*)(QFutureInterface<T> &)>(functionPointer))->start();
}
template <typename T, typename Arg1>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &, Arg1), Arg1 arg1)
{
return (new StoredInterfaceFunctionCall1<T, void (*)(QFutureInterface<T> &, Arg1), Arg1>(functionPointer, arg1))->start();
}
template <typename T, typename Arg1, typename Arg2>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &, Arg1, Arg2), Arg1 arg1, Arg2 arg2)
{
return (new StoredInterfaceFunctionCall2<T, void (*)(QFutureInterface<T> &, Arg1, Arg2), Arg1, Arg2>(functionPointer, arg1, arg2))->start();
}
template <typename T, typename Arg1, typename Arg2, typename Arg3>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &, Arg1, Arg2, Arg3), Arg1 arg1, Arg2 arg2, Arg3 arg3)
{
return (new StoredInterfaceFunctionCall3<T, void (*)(QFutureInterface<T> &, Arg1, Arg2, Arg3), Arg1, Arg2, Arg3>(functionPointer, arg1, arg2, arg3))->start();
}
template <typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4)
{
return (new StoredInterfaceFunctionCall4<T, void (*)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4), Arg1, Arg2, Arg3, Arg4>(functionPointer, arg1, arg2, arg3, arg4))->start();
}
template <typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5>
QFuture<T> run(void (*functionPointer)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4, Arg5), Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5)
{
return (new StoredInterfaceFunctionCall5<T, void (*)(QFutureInterface<T> &, Arg1, Arg2, Arg3, Arg4, Arg5), Arg1, Arg2, Arg3, Arg4, Arg5>(functionPointer, arg1, arg2, arg3, arg4, arg5))->start();
}
template <typename Class, typename T>
QFuture<T> run(void (Class::*fn)(QFutureInterface<T> &), Class *object)
{
return (new StoredInterfaceMemberFunctionCall0<T, void(Class::*) (QFutureInterface<T> &), Class>(fn, object))->start();
}
} // namespace QtConcurrent
QT_END_NAMESPACE
#endif // QTCONCURRENT_RUNEX_H

View File

@ -1,151 +0,0 @@
/**
******************************************************************************
*
* @file classnamevalidatinglineedit.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "classnamevalidatinglineedit.h"
#include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QRegExp>
namespace Utils {
struct ClassNameValidatingLineEditPrivate {
ClassNameValidatingLineEditPrivate();
const QRegExp m_nameRegexp;
const QString m_namespaceDelimiter;
bool m_namespacesEnabled;
bool m_lowerCaseFileName;
};
// Match something like "Namespace1::Namespace2::ClassName".
ClassNameValidatingLineEditPrivate::ClassNameValidatingLineEditPrivate() :
m_nameRegexp(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*")),
m_namespaceDelimiter(QLatin1String("::")),
m_namespacesEnabled(false),
m_lowerCaseFileName(true)
{
QTC_ASSERT(m_nameRegexp.isValid(), return );
}
// --------------------- ClassNameValidatingLineEdit
ClassNameValidatingLineEdit::ClassNameValidatingLineEdit(QWidget *parent) :
Utils::BaseValidatingLineEdit(parent),
m_d(new ClassNameValidatingLineEditPrivate)
{}
ClassNameValidatingLineEdit::~ClassNameValidatingLineEdit()
{
delete m_d;
}
bool ClassNameValidatingLineEdit::namespacesEnabled() const
{
return m_d->m_namespacesEnabled;
}
void ClassNameValidatingLineEdit::setNamespacesEnabled(bool b)
{
m_d->m_namespacesEnabled = b;
}
bool ClassNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{
if (!m_d->m_namespacesEnabled && value.contains(QLatin1Char(':'))) {
if (errorMessage) {
*errorMessage = tr("The class name must not contain namespace delimiters.");
}
return false;
} else if (value.isEmpty()) {
if (errorMessage) {
*errorMessage = tr("Please enter a class name.");
}
return false;
} else if (!m_d->m_nameRegexp.exactMatch(value)) {
if (errorMessage) {
*errorMessage = tr("The class name contains invalid characters.");
}
return false;
}
return true;
}
void ClassNameValidatingLineEdit::slotChanged(const QString &t)
{
Utils::BaseValidatingLineEdit::slotChanged(t);
if (isValid()) {
// Suggest file names, strip namespaces
QString fileName = m_d->m_lowerCaseFileName ? t.toLower() : t;
if (m_d->m_namespacesEnabled) {
const int namespaceIndex = fileName.lastIndexOf(m_d->m_namespaceDelimiter);
if (namespaceIndex != -1) {
fileName.remove(0, namespaceIndex + m_d->m_namespaceDelimiter.size());
}
}
emit updateFileName(fileName);
}
}
QString ClassNameValidatingLineEdit::createClassName(const QString &name)
{
// Remove spaces and convert the adjacent characters to uppercase
QString className = name;
QRegExp spaceMatcher(QLatin1String(" +(\\w)"), Qt::CaseSensitive, QRegExp::RegExp2);
QTC_ASSERT(spaceMatcher.isValid(), /**/);
int pos;
while ((pos = spaceMatcher.indexIn(className)) != -1) {
className.replace(pos, spaceMatcher.matchedLength(),
spaceMatcher.cap(1).toUpper());
}
// Filter out any remaining invalid characters
className.remove(QRegExp(QLatin1String("[^a-zA-Z0-9_]")));
// If the first character is numeric, prefix the name with a "_"
if (className.at(0).isNumber()) {
className.prepend(QLatin1Char('_'));
} else {
// Convert the first character to uppercase
className.replace(0, 1, className.left(1).toUpper());
}
return className;
}
bool ClassNameValidatingLineEdit::lowerCaseFileName() const
{
return m_d->m_lowerCaseFileName;
}
void ClassNameValidatingLineEdit::setLowerCaseFileName(bool v)
{
m_d->m_lowerCaseFileName = v;
}
} // namespace Utils

View File

@ -1,75 +0,0 @@
/**
******************************************************************************
*
* @file classnamevalidatinglineedit.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef CLASSNAMEVALIDATINGLINEEDIT_H
#define CLASSNAMEVALIDATINGLINEEDIT_H
#include "utils_global.h"
#include "basevalidatinglineedit.h"
namespace Utils {
struct ClassNameValidatingLineEditPrivate;
/* A Line edit that validates a C++ class name and emits a signal
* to derive suggested file names from it. */
class QTCREATOR_UTILS_EXPORT ClassNameValidatingLineEdit
: public Utils::BaseValidatingLineEdit {
Q_DISABLE_COPY(ClassNameValidatingLineEdit)
Q_PROPERTY(bool namespacesEnabled READ namespacesEnabled WRITE setNamespacesEnabled DESIGNABLE true)
Q_PROPERTY(bool lowerCaseFileName READ lowerCaseFileName WRITE setLowerCaseFileName)
Q_OBJECT
public:
explicit ClassNameValidatingLineEdit(QWidget *parent = 0);
virtual ~ClassNameValidatingLineEdit();
bool namespacesEnabled() const;
void setNamespacesEnabled(bool b);
bool lowerCaseFileName() const;
void setLowerCaseFileName(bool v);
// Clean an input string to get a valid class name.
static QString createClassName(const QString &name);
signals:
// Will be emitted with a suggestion for a base name of the
// source/header file of the class.
void updateFileName(const QString &t);
protected:
virtual bool validate(const QString &value, QString *errorMessage) const;
virtual void slotChanged(const QString &t);
private:
ClassNameValidatingLineEditPrivate *m_d;
};
} // namespace Utils
#endif // CLASSNAMEVALIDATINGLINEEDIT_H

View File

@ -1,105 +0,0 @@
/**
******************************************************************************
*
* @file codegeneration.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "codegeneration.h"
#include <QtCore/QTextStream>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>
namespace Utils {
QTCREATOR_UTILS_EXPORT QString fileNameToCppIdentifier(const QString &s)
{
QString rc;
const int len = s.size();
const QChar underscore = QLatin1Char('_');
const QChar dot = QLatin1Char('.');
for (int i = 0; i < len; i++) {
const QChar c = s.at(i);
if (c == underscore || c.isLetterOrNumber()) {
rc += c;
} else if (c == dot) {
rc += underscore;
}
}
return rc;
}
QTCREATOR_UTILS_EXPORT QString headerGuard(const QString &file)
{
const QFileInfo fi(file);
QString rc = fileNameToCppIdentifier(fi.completeBaseName()).toUpper();
rc += QLatin1Char('_');
rc += fileNameToCppIdentifier(fi.suffix()).toUpper();
return rc;
}
QTCREATOR_UTILS_EXPORT
void writeIncludeFileDirective(const QString &file, bool globalInclude,
QTextStream &str)
{
const QChar opening = globalInclude ? QLatin1Char('<') : QLatin1Char('"');
const QChar closing = globalInclude ? QLatin1Char('>') : QLatin1Char('"');
str << QLatin1String("#include ") << opening << file << closing << QLatin1Char('\n');
}
QTCREATOR_UTILS_EXPORT
QString writeOpeningNameSpaces(const QStringList &l, const QString &indent,
QTextStream &str)
{
const int count = l.size();
QString rc;
if (count) {
str << '\n';
for (int i = 0; i < count; i++) {
str << rc << "namespace " << l.at(i) << " {\n";
rc += indent;
}
}
return rc;
}
QTCREATOR_UTILS_EXPORT
void writeClosingNameSpaces(const QStringList &l, const QString &indent,
QTextStream &str)
{
if (!l.empty()) {
str << '\n';
}
for (int i = l.size() - 1; i >= 0; i--) {
if (i) {
str << QString(indent.size() * i, QLatin1Char(' '));
}
str << "} // namespace " << l.at(i) << '\n';
}
}
} // namespace Utils

View File

@ -1,66 +0,0 @@
/**
******************************************************************************
*
* @file codegeneration.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef CODEGENERATION_H
#define CODEGENERATION_H
#include "utils_global.h"
#include <QtCore/QString>
QT_BEGIN_NAMESPACE
class QTextStream;
class QStringList;
QT_END_NAMESPACE
namespace Utils {
// Convert a file name to a Cpp identifier (stripping invalid characters
// or replacing them by an underscore).
QTCREATOR_UTILS_EXPORT QString fileNameToCppIdentifier(const QString &s);
QTCREATOR_UTILS_EXPORT QString headerGuard(const QString &file);
QTCREATOR_UTILS_EXPORT
void writeIncludeFileDirective(const QString &file,
bool globalInclude,
QTextStream &str);
// Write opening namespaces and return an indentation string to be used
// in the following code if there are any.
QTCREATOR_UTILS_EXPORT
QString writeOpeningNameSpaces(const QStringList &namespaces,
const QString &indent,
QTextStream &str);
// Close namespacesnamespaces
QTCREATOR_UTILS_EXPORT
void writeClosingNameSpaces(const QStringList &namespaces,
const QString &indent,
QTextStream &str);
} // namespace Utils
#endif // CODEGENERATION_H

View File

@ -1,138 +0,0 @@
/**
******************************************************************************
*
* @file filenamevalidatinglineedit.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "filenamevalidatinglineedit.h"
#include "qtcassert.h"
#include <QtCore/QRegExp>
#include <QtCore/QDebug>
namespace Utils {
#define WINDOWS_DEVICES "CON|AUX|PRN|COM1|COM2|LPT1|LPT2|NUL"
// Naming a file like a device name will break on Windows, even if it is
// "com1.txt". Since we are cross-platform, we generally disallow such file
// names.
static const QRegExp &windowsDeviceNoSubDirPattern()
{
static const QRegExp rc(QLatin1String(WINDOWS_DEVICES),
Qt::CaseInsensitive);
QTC_ASSERT(rc.isValid(), return rc);
return rc;
}
static const QRegExp &windowsDeviceSubDirPattern()
{
static const QRegExp rc(QLatin1String(".*[/\\\\](" WINDOWS_DEVICES ")"), Qt::CaseInsensitive);
QTC_ASSERT(rc.isValid(), return rc);
return rc;
}
// ----------- FileNameValidatingLineEdit
FileNameValidatingLineEdit::FileNameValidatingLineEdit(QWidget *parent) :
BaseValidatingLineEdit(parent),
m_allowDirectories(false),
m_unused(0)
{}
bool FileNameValidatingLineEdit::allowDirectories() const
{
return m_allowDirectories;
}
void FileNameValidatingLineEdit::setAllowDirectories(bool v)
{
m_allowDirectories = v;
}
/* Validate a file base name, check for forbidden characters/strings. */
#ifdef Q_OS_WIN
# define SLASHES "/\\"
#else
# define SLASHES "/"
#endif
static const char *notAllowedCharsSubDir = "?:&*\"|#%<> ";
static const char *notAllowedCharsNoSubDir = "?:&*\"|#%<> " SLASHES;
static const char *notAllowedSubStrings[] = { ".." };
bool FileNameValidatingLineEdit::validateFileName(const QString &name,
bool allowDirectories,
QString *errorMessage /* = 0*/)
{
if (name.isEmpty()) {
if (errorMessage) {
*errorMessage = tr("The name must not be empty");
}
return false;
}
// Characters
const char *notAllowedChars = allowDirectories ? notAllowedCharsSubDir : notAllowedCharsNoSubDir;
for (const char *c = notAllowedChars; *c; c++) {
if (name.contains(QLatin1Char(*c))) {
if (errorMessage) {
*errorMessage = tr("The name must not contain any of the characters '%1'.").arg(QLatin1String(notAllowedChars));
}
return false;
}
}
// Substrings
const int notAllowedSubStringCount = sizeof(notAllowedSubStrings) / sizeof(const char *);
for (int s = 0; s < notAllowedSubStringCount; s++) {
const QLatin1String notAllowedSubString(notAllowedSubStrings[s]);
if (name.contains(notAllowedSubString)) {
if (errorMessage) {
*errorMessage = tr("The name must not contain '%1'.").arg(QString(notAllowedSubString));
}
return false;
}
}
// Windows devices
bool matchesWinDevice = windowsDeviceNoSubDirPattern().exactMatch(name);
if (!matchesWinDevice && allowDirectories) {
matchesWinDevice = windowsDeviceSubDirPattern().exactMatch(name);
}
if (matchesWinDevice) {
if (errorMessage) {
*errorMessage = tr("The name must not match that of a MS Windows device. (%1).").
arg(windowsDeviceNoSubDirPattern().pattern().replace(QLatin1Char('|'), QLatin1Char(',')));
}
return false;
}
return true;
}
bool FileNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{
return validateFileName(value, m_allowDirectories, errorMessage);
}
} // namespace Utils

View File

@ -1,65 +0,0 @@
/**
******************************************************************************
*
* @file filenamevalidatinglineedit.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef FILENAMEVALIDATINGLINEEDIT_H
#define FILENAMEVALIDATINGLINEEDIT_H
#include "basevalidatinglineedit.h"
namespace Utils {
/**
* A control that let's the user choose a file name, based on a QLineEdit. Has
* some validation logic for embedding into QWizardPage.
*/
class QTCREATOR_UTILS_EXPORT FileNameValidatingLineEdit : public BaseValidatingLineEdit {
Q_OBJECT Q_DISABLE_COPY(FileNameValidatingLineEdit)
Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories)
public:
explicit FileNameValidatingLineEdit(QWidget *parent = 0);
static bool validateFileName(const QString &name,
bool allowDirectories = false,
QString *errorMessage = 0);
/**
* Sets whether entering directories is allowed. This will enable the user
* to enter slashes in the filename. Default is off.
*/
bool allowDirectories() const;
void setAllowDirectories(bool v);
protected:
virtual bool validate(const QString &value, QString *errorMessage) const;
private:
bool m_allowDirectories;
void *m_unused;
};
} // namespace Utils
#endif // FILENAMEVALIDATINGLINEEDIT_H

View File

@ -1,267 +0,0 @@
/**
******************************************************************************
*
* @file filesearch.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "filesearch.h"
#include <cctype>
#include <QtCore/QIODevice>
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtCore/QFutureInterface>
#include <QtConcurrent/QtConcurrentRun>
#include <QtCore/QRegExp>
#include <QtCore/QCoreApplication>
#include <qtconcurrent/runextensions.h>
using namespace Utils;
static inline QString msgCanceled(const QString &searchTerm, int numMatches, int numFilesSearched)
{
return QCoreApplication::translate("Utils::FileSearch",
"%1: canceled. %n occurrences found in %2 files.",
NULL, numMatches).
arg(searchTerm).arg(numFilesSearched);
}
static inline QString msgFound(const QString &searchTerm, int numMatches, int numFilesSearched)
{
return QCoreApplication::translate("Utils::FileSearch",
"%1: %n occurrences found in %2 files.",
NULL, numMatches).
arg(searchTerm).arg(numFilesSearched);
}
static inline QString msgFound(const QString &searchTerm, int numMatches, int numFilesSearched, int filesSize)
{
return QCoreApplication::translate("Utils::FileSearch",
"%1: %n occurrences found in %2 of %3 files.",
NULL, numMatches).
arg(searchTerm).arg(numFilesSearched).arg(filesSize);
}
namespace {
void runFileSearch(QFutureInterface<FileSearchResult> &future,
QString searchTerm,
QStringList files,
QTextDocument::FindFlags flags,
QMap<QString, QString> fileToContentsMap)
{
future.setProgressRange(0, files.size());
int numFilesSearched = 0;
int numMatches = 0;
bool caseInsensitive = !(flags & QTextDocument::FindCaseSensitively);
bool wholeWord = (flags & QTextDocument::FindWholeWords);
QByteArray sa = searchTerm.toUtf8();
int scMaxIndex = sa.length() - 1;
const char *sc = sa.constData();
QByteArray sal = searchTerm.toLower().toUtf8();
const char *scl = sal.constData();
QByteArray sau = searchTerm.toUpper().toUtf8();
const char *scu = sau.constData();
int chunkSize = qMax(100000, sa.length());
QFile file;
QBuffer buffer;
foreach(QString s, files) {
if (future.isPaused()) {
future.waitForResume();
}
if (future.isCanceled()) {
future.setProgressValueAndText(numFilesSearched, msgCanceled(searchTerm, numMatches, numFilesSearched));
break;
}
QIODevice *device;
if (fileToContentsMap.contains(s)) {
buffer.setData(fileToContentsMap.value(s).toLocal8Bit());
device = &buffer;
} else {
file.setFileName(s);
device = &file;
}
if (!device->open(QIODevice::ReadOnly)) {
continue;
}
int lineNr = 1;
const char *startOfLastLine = NULL;
bool firstChunk = true;
while (!device->atEnd()) {
if (!firstChunk) {
device->seek(device->pos() - sa.length() + 1);
}
const QByteArray chunk = device->read(chunkSize);
const char *chunkPtr = chunk.constData();
startOfLastLine = chunkPtr;
for (const char *regionPtr = chunkPtr; regionPtr < chunkPtr + chunk.length() - scMaxIndex; ++regionPtr) {
const char *regionEnd = regionPtr + scMaxIndex;
if (*regionPtr == '\n') {
startOfLastLine = regionPtr + 1;
++lineNr;
} else if (
// case sensitive
(!caseInsensitive && *regionPtr == sc[0] && *regionEnd == sc[scMaxIndex])
||
// case insensitive
(caseInsensitive && (*regionPtr == scl[0] || *regionPtr == scu[0])
&& (*regionEnd == scl[scMaxIndex] || *regionEnd == scu[scMaxIndex]))
) {
const char *afterRegion = regionEnd + 1;
const char *beforeRegion = regionPtr - 1;
bool equal = true;
if (wholeWord &&
(isalnum(*beforeRegion)
|| (*beforeRegion == '_')
|| isalnum(*afterRegion)
|| (*afterRegion == '_'))) {
equal = false;
}
int regionIndex = 1;
for (const char *regionCursor = regionPtr + 1; regionCursor < regionEnd; ++regionCursor, ++regionIndex) {
if ( // case sensitive
(!caseInsensitive && equal && *regionCursor != sc[regionIndex])
||
// case insensitive
(caseInsensitive && equal && *regionCursor != sc[regionIndex] && *regionCursor != scl[regionIndex] && *regionCursor != scu[regionIndex])
) {
equal = false;
}
}
if (equal) {
int textLength = chunk.length() - (startOfLastLine - chunkPtr);
if (textLength > 0) {
QByteArray res;
res.reserve(256);
int i = 0;
int n = 0;
while (startOfLastLine[i] != '\n' && startOfLastLine[i] != '\r' && i < textLength && n++ < 256) {
res.append(startOfLastLine[i++]);
}
future.reportResult(FileSearchResult(s, lineNr, QString(res),
regionPtr - startOfLastLine, sa.length()));
++numMatches;
}
}
}
}
firstChunk = false;
}
++numFilesSearched;
future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched, files.size()));
device->close();
}
if (!future.isCanceled()) {
future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched));
}
}
void runFileSearchRegExp(QFutureInterface<FileSearchResult> &future,
QString searchTerm,
QStringList files,
QTextDocument::FindFlags flags,
QMap<QString, QString> fileToContentsMap)
{
future.setProgressRange(0, files.size());
int numFilesSearched = 0;
int numMatches = 0;
if (flags & QTextDocument::FindWholeWords) {
searchTerm = QString::fromLatin1("\\b%1\\b").arg(searchTerm);
}
const Qt::CaseSensitivity caseSensitivity = (flags & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive;
const QRegExp expression(searchTerm, caseSensitivity);
QFile file;
QString str;
QTextStream stream;
foreach(const QString &s, files) {
if (future.isPaused()) {
future.waitForResume();
}
if (future.isCanceled()) {
future.setProgressValueAndText(numFilesSearched, msgCanceled(searchTerm, numMatches, numFilesSearched));
break;
}
bool needsToCloseFile = false;
if (fileToContentsMap.contains(s)) {
str = fileToContentsMap.value(s);
stream.setString(&str);
} else {
file.setFileName(s);
if (!file.open(QIODevice::ReadOnly)) {
continue;
}
needsToCloseFile = true;
stream.setDevice(&file);
}
int lineNr = 1;
QString line;
while (!stream.atEnd()) {
line = stream.readLine();
int pos = 0;
while ((pos = expression.indexIn(line, pos)) != -1) {
future.reportResult(FileSearchResult(s, lineNr, line,
pos, expression.matchedLength()));
pos += expression.matchedLength();
}
++lineNr;
}
++numFilesSearched;
future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched, files.size()));
if (needsToCloseFile) {
file.close();
}
}
if (!future.isCanceled()) {
future.setProgressValueAndText(numFilesSearched, msgFound(searchTerm, numMatches, numFilesSearched));
}
}
} // namespace
QFuture<FileSearchResult> Utils::findInFiles(const QString &searchTerm, const QStringList &files,
QTextDocument::FindFlags flags, QMap<QString, QString> fileToContentsMap)
{
return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags, QMap<QString, QString> >
(runFileSearch, searchTerm, files, flags, fileToContentsMap);
}
QFuture<FileSearchResult> Utils::findInFilesRegExp(const QString &searchTerm, const QStringList &files,
QTextDocument::FindFlags flags, QMap<QString, QString> fileToContentsMap)
{
return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags, QMap<QString, QString> >
(runFileSearchRegExp, searchTerm, files, flags, fileToContentsMap);
}

View File

@ -1,60 +0,0 @@
/**
******************************************************************************
*
* @file filesearch.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef FILESEARCH_H
#define FILESEARCH_H
#include "utils_global.h"
#include <QtCore/QStringList>
#include <QtCore/QFuture>
#include <QtCore/QMap>
#include <QTextDocument>
namespace Utils {
class QTCREATOR_UTILS_EXPORT FileSearchResult {
public:
FileSearchResult() {}
FileSearchResult(QString fileName, int lineNumber, QString matchingLine, int matchStart, int matchLength)
: fileName(fileName), lineNumber(lineNumber), matchingLine(matchingLine), matchStart(matchStart), matchLength(matchLength)
{}
QString fileName;
int lineNumber;
QString matchingLine;
int matchStart;
int matchLength;
};
QTCREATOR_UTILS_EXPORT QFuture<FileSearchResult> findInFiles(const QString &searchTerm, const QStringList &files,
QTextDocument::FindFlags flags, QMap<QString, QString> fileToContentsMap = QMap<QString, QString>());
QTCREATOR_UTILS_EXPORT QFuture<FileSearchResult> findInFilesRegExp(const QString &searchTerm, const QStringList &files,
QTextDocument::FindFlags flags, QMap<QString, QString> fileToContentsMap = QMap<QString, QString>());
} // namespace Utils
#endif // FILESEARCH_H

View File

@ -1,66 +0,0 @@
/**
******************************************************************************
*
* @file filewizarddialog.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "filewizarddialog.h"
#include "filewizardpage.h"
#include <QAbstractButton>
namespace Utils {
FileWizardDialog::FileWizardDialog(QWidget *parent) :
QWizard(parent),
m_filePage(new FileWizardPage)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setOption(QWizard::NoCancelButton, false);
setOption(QWizard::NoDefaultButton, false);
setPixmap(QWizard::WatermarkPixmap, QPixmap(QLatin1String(":/core/images/qtwatermark.png")));
addPage(m_filePage);
connect(m_filePage, SIGNAL(activated()), button(QWizard::FinishButton), SLOT(animateClick()));
}
QString FileWizardDialog::name() const
{
return m_filePage->name();
}
QString FileWizardDialog::path() const
{
return m_filePage->path();
}
void FileWizardDialog::setPath(const QString &path)
{
m_filePage->setPath(path);
}
void FileWizardDialog::setName(const QString &name)
{
m_filePage->setName(name);
}
} // namespace Utils

View File

@ -1,61 +0,0 @@
/**
******************************************************************************
*
* @file filewizarddialog.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef FILEWIZARDDIALOG_H
#define FILEWIZARDDIALOG_H
#include "utils_global.h"
#include <QWizard>
namespace Utils {
class FileWizardPage;
/*
Standard wizard for a single file letting the user choose name
and path. Custom pages can be added via Core::IWizardExtension.
*/
class QTCREATOR_UTILS_EXPORT FileWizardDialog : public QWizard {
Q_OBJECT Q_DISABLE_COPY(FileWizardDialog)
public:
explicit FileWizardDialog(QWidget *parent = 0);
QString name() const;
QString path() const;
public slots:
void setPath(const QString &path);
void setName(const QString &name);
private:
FileWizardPage *m_filePage;
};
} // namespace Utils
#endif // FILEWIZARDDIALOG_H

View File

@ -1,129 +0,0 @@
/**
******************************************************************************
*
* @file filewizardpage.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "filewizardpage.h"
#include "ui_filewizardpage.h"
namespace Utils {
struct FileWizardPagePrivate {
FileWizardPagePrivate();
Ui::WizardPage m_ui;
bool m_complete;
};
FileWizardPagePrivate::FileWizardPagePrivate() :
m_complete(false)
{}
FileWizardPage::FileWizardPage(QWidget *parent) :
QWizardPage(parent),
m_d(new FileWizardPagePrivate)
{
m_d->m_ui.setupUi(this);
connect(m_d->m_ui.pathChooser, SIGNAL(validChanged()), this, SLOT(slotValidChanged()));
connect(m_d->m_ui.nameLineEdit, SIGNAL(validChanged()), this, SLOT(slotValidChanged()));
connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()), this, SLOT(slotActivated()));
connect(m_d->m_ui.nameLineEdit, SIGNAL(validReturnPressed()), this, SLOT(slotActivated()));
}
FileWizardPage::~FileWizardPage()
{
delete m_d;
}
QString FileWizardPage::name() const
{
return m_d->m_ui.nameLineEdit->text();
}
QString FileWizardPage::path() const
{
return m_d->m_ui.pathChooser->path();
}
void FileWizardPage::setPath(const QString &path)
{
m_d->m_ui.pathChooser->setPath(path);
}
void FileWizardPage::setName(const QString &name)
{
m_d->m_ui.nameLineEdit->setText(name);
}
void FileWizardPage::changeEvent(QEvent *e)
{
QWizardPage::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_d->m_ui.retranslateUi(this);
break;
default:
break;
}
}
bool FileWizardPage::isComplete() const
{
return m_d->m_complete;
}
void FileWizardPage::setNameLabel(const QString &label)
{
m_d->m_ui.nameLabel->setText(label);
}
void FileWizardPage::setPathLabel(const QString &label)
{
m_d->m_ui.pathLabel->setText(label);
}
void FileWizardPage::slotValidChanged()
{
const bool newComplete = m_d->m_ui.pathChooser->isValid() && m_d->m_ui.nameLineEdit->isValid();
if (newComplete != m_d->m_complete) {
m_d->m_complete = newComplete;
emit completeChanged();
}
}
void FileWizardPage::slotActivated()
{
if (m_d->m_complete) {
emit activated();
}
}
bool FileWizardPage::validateBaseName(const QString &name, QString *errorMessage /* = 0*/)
{
return FileNameValidatingLineEdit::validateFileName(name, false, errorMessage);
}
} // namespace Utils

View File

@ -1,85 +0,0 @@
/**
******************************************************************************
*
* @file filewizardpage.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef FILEWIZARDPAGE_H
#define FILEWIZARDPAGE_H
#include "utils_global.h"
#include <QWizardPage>
namespace Utils {
struct FileWizardPagePrivate;
/**
* Standard wizard page for a single file letting the user choose name
* and path. Sets the "FileNames" QWizard field.
*
* The name and path labels can be changed. By default they are simply "Name:"
* and "Path:".
*/
class QTCREATOR_UTILS_EXPORT FileWizardPage : public QWizardPage {
Q_OBJECT Q_DISABLE_COPY(FileWizardPage)
Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true)
Q_PROPERTY(QString name READ name WRITE setName DESIGNABLE true)
public:
explicit FileWizardPage(QWidget *parent = 0);
virtual ~FileWizardPage();
QString name() const;
QString path() const;
virtual bool isComplete() const;
void setNameLabel(const QString &label);
void setPathLabel(const QString &label);
// Validate a base name entry field (potentially containing extension)
static bool validateBaseName(const QString &name, QString *errorMessage = 0);
signals:
void activated();
void pathChanged();
public slots:
void setPath(const QString &path);
void setName(const QString &name);
private slots:
void slotValidChanged();
void slotActivated();
protected:
virtual void changeEvent(QEvent *e);
private:
FileWizardPagePrivate *m_d;
};
} // namespace Utils
#endif // FILEWIZARDPAGE_H

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Utils::WizardPage</class>
<widget class="QWizardPage" name="Utils::WizardPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>196</width>
<height>68</height>
</rect>
</property>
<property name="title">
<string>Choose the location</string>
</property>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="nameLabel">
<property name="text">
<string>Name:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="Utils::FileNameValidatingLineEdit" name="nameLineEdit"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="pathLabel">
<property name="text">
<string>Path:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="Utils::PathChooser" name="pathChooser" native="true"/>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>Utils::PathChooser</class>
<extends>QWidget</extends>
<header>pathchooser.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>Utils::FileNameValidatingLineEdit</class>
<extends>QLineEdit</extends>
<header>filenamevalidatinglineedit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -1,535 +0,0 @@
/**
******************************************************************************
*
* @file newclasswidget.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "newclasswidget.h"
#include "ui_newclasswidget.h"
#include <utils/filewizardpage.h>
#include <QFileDialog>
#include <QtCore/QFileInfo>
#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QRegExp>
enum { debugNewClassWidget = 0 };
namespace Utils {
struct NewClassWidgetPrivate {
NewClassWidgetPrivate();
Ui::NewClassWidget m_ui;
QString m_headerExtension;
QString m_sourceExtension;
QString m_formExtension;
bool m_valid;
bool m_classEdited;
// Store the "visible" values to prevent the READ accessors from being
// fooled by a temporarily hidden widget
bool m_baseClassInputVisible;
bool m_formInputVisible;
bool m_pathInputVisible;
bool m_qobjectCheckBoxVisible;
bool m_formInputCheckable;
};
NewClassWidgetPrivate::NewClassWidgetPrivate() :
m_headerExtension(QLatin1String("h")),
m_sourceExtension(QLatin1String("cpp")),
m_formExtension(QLatin1String("ui")),
m_valid(false),
m_classEdited(false),
m_baseClassInputVisible(true),
m_formInputVisible(true),
m_pathInputVisible(true),
m_qobjectCheckBoxVisible(false),
m_formInputCheckable(false)
{}
// --------------------- NewClassWidget
NewClassWidget::NewClassWidget(QWidget *parent) :
QWidget(parent),
m_d(new NewClassWidgetPrivate)
{
m_d->m_ui.setupUi(this);
m_d->m_ui.baseClassComboBox->setEditable(false);
connect(m_d->m_ui.classLineEdit, SIGNAL(updateFileName(QString)),
this, SLOT(slotUpdateFileNames(QString)));
connect(m_d->m_ui.classLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(classNameEdited()));
connect(m_d->m_ui.baseClassComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(suggestClassNameFromBase()));
connect(m_d->m_ui.baseClassComboBox, SIGNAL(editTextChanged(QString)),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.classLineEdit, SIGNAL(validChanged()),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.headerFileLineEdit, SIGNAL(validChanged()),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.sourceFileLineEdit, SIGNAL(validChanged()),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.formFileLineEdit, SIGNAL(validChanged()),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.pathChooser, SIGNAL(validChanged()),
this, SLOT(slotValidChanged()));
connect(m_d->m_ui.classLineEdit, SIGNAL(validReturnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.headerFileLineEdit, SIGNAL(validReturnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.sourceFileLineEdit, SIGNAL(validReturnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.formFileLineEdit, SIGNAL(validReturnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.formFileLineEdit, SIGNAL(validReturnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()),
this, SLOT(slotActivated()));
connect(m_d->m_ui.generateFormCheckBox, SIGNAL(stateChanged(int)),
this, SLOT(slotFormInputChecked()));
m_d->m_ui.generateFormCheckBox->setChecked(true);
setFormInputCheckable(false, true);
setClassType(NoClassType);
}
NewClassWidget::~NewClassWidget()
{
delete m_d;
}
void NewClassWidget::classNameEdited()
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << m_d->m_headerExtension << m_d->m_sourceExtension;
}
m_d->m_classEdited = true;
}
void NewClassWidget::suggestClassNameFromBase()
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << m_d->m_headerExtension << m_d->m_sourceExtension;
}
if (m_d->m_classEdited) {
return;
}
// Suggest a class unless edited ("QMainWindow"->"MainWindow")
QString base = baseClassName();
if (base.startsWith(QLatin1Char('Q'))) {
base.remove(0, 1);
setClassName(base);
}
}
QStringList NewClassWidget::baseClassChoices() const
{
QStringList rc;
const int count = m_d->m_ui.baseClassComboBox->count();
for (int i = 0; i < count; i++) {
rc.push_back(m_d->m_ui.baseClassComboBox->itemText(i));
}
return rc;
}
void NewClassWidget::setBaseClassChoices(const QStringList &choices)
{
m_d->m_ui.baseClassComboBox->clear();
m_d->m_ui.baseClassComboBox->addItems(choices);
}
void NewClassWidget::setBaseClassInputVisible(bool visible)
{
m_d->m_baseClassInputVisible = visible;
m_d->m_ui.baseClassLabel->setVisible(visible);
m_d->m_ui.baseClassComboBox->setVisible(visible);
}
void NewClassWidget::setBaseClassEditable(bool editable)
{
m_d->m_ui.baseClassComboBox->setEditable(editable);
}
bool NewClassWidget::isBaseClassInputVisible() const
{
return m_d->m_baseClassInputVisible;
}
bool NewClassWidget::isBaseClassEditable() const
{
return m_d->m_ui.baseClassComboBox->isEditable();
}
void NewClassWidget::setFormInputVisible(bool visible)
{
m_d->m_formInputVisible = visible;
m_d->m_ui.formLabel->setVisible(visible);
m_d->m_ui.formFileLineEdit->setVisible(visible);
}
bool NewClassWidget::isFormInputVisible() const
{
return m_d->m_formInputVisible;
}
void NewClassWidget::setFormInputCheckable(bool checkable)
{
setFormInputCheckable(checkable, false);
}
void NewClassWidget::setFormInputCheckable(bool checkable, bool force)
{
if (!force && checkable == m_d->m_formInputCheckable) {
return;
}
m_d->m_formInputCheckable = checkable;
m_d->m_ui.generateFormLabel->setVisible(checkable);
m_d->m_ui.generateFormCheckBox->setVisible(checkable);
}
void NewClassWidget::setFormInputChecked(bool v)
{
m_d->m_ui.generateFormCheckBox->setChecked(v);
}
bool NewClassWidget::formInputCheckable() const
{
return m_d->m_formInputCheckable;
}
bool NewClassWidget::formInputChecked() const
{
return m_d->m_ui.generateFormCheckBox->isChecked();
}
void NewClassWidget::slotFormInputChecked()
{
const bool checked = formInputChecked();
m_d->m_ui.formLabel->setEnabled(checked);
m_d->m_ui.formFileLineEdit->setEnabled(checked);
}
void NewClassWidget::setPathInputVisible(bool visible)
{
m_d->m_pathInputVisible = visible;
m_d->m_ui.pathLabel->setVisible(visible);
m_d->m_ui.pathChooser->setVisible(visible);
}
bool NewClassWidget::isPathInputVisible() const
{
return m_d->m_pathInputVisible;
}
void NewClassWidget::setClassName(const QString &suggestedName)
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << suggestedName << m_d->m_headerExtension << m_d->m_sourceExtension;
}
m_d->m_ui.classLineEdit->setText(ClassNameValidatingLineEdit::createClassName(suggestedName));
}
QString NewClassWidget::className() const
{
return m_d->m_ui.classLineEdit->text();
}
QString NewClassWidget::baseClassName() const
{
return m_d->m_ui.baseClassComboBox->currentText();
}
void NewClassWidget::setBaseClassName(const QString &c)
{
const int index = m_d->m_ui.baseClassComboBox->findText(c);
if (index != -1) {
m_d->m_ui.baseClassComboBox->setCurrentIndex(index);
suggestClassNameFromBase();
}
}
QString NewClassWidget::sourceFileName() const
{
return m_d->m_ui.sourceFileLineEdit->text();
}
QString NewClassWidget::headerFileName() const
{
return m_d->m_ui.headerFileLineEdit->text();
}
QString NewClassWidget::formFileName() const
{
return m_d->m_ui.formFileLineEdit->text();
}
QString NewClassWidget::path() const
{
return m_d->m_ui.pathChooser->path();
}
void NewClassWidget::setPath(const QString &path)
{
m_d->m_ui.pathChooser->setPath(path);
}
bool NewClassWidget::namespacesEnabled() const
{
return m_d->m_ui.classLineEdit->namespacesEnabled();
}
void NewClassWidget::setNamespacesEnabled(bool b)
{
m_d->m_ui.classLineEdit->setNamespacesEnabled(b);
}
QString NewClassWidget::sourceExtension() const
{
return m_d->m_sourceExtension;
}
void NewClassWidget::setSourceExtension(const QString &e)
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << e;
}
m_d->m_sourceExtension = fixSuffix(e);
}
QString NewClassWidget::headerExtension() const
{
return m_d->m_headerExtension;
}
void NewClassWidget::setHeaderExtension(const QString &e)
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << e;
}
m_d->m_headerExtension = fixSuffix(e);
}
QString NewClassWidget::formExtension() const
{
return m_d->m_formExtension;
}
void NewClassWidget::setFormExtension(const QString &e)
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << e;
}
m_d->m_formExtension = fixSuffix(e);
}
bool NewClassWidget::allowDirectories() const
{
return m_d->m_ui.headerFileLineEdit->allowDirectories();
}
void NewClassWidget::setAllowDirectories(bool v)
{
// We keep all in sync
if (allowDirectories() != v) {
m_d->m_ui.sourceFileLineEdit->setAllowDirectories(v);
m_d->m_ui.headerFileLineEdit->setAllowDirectories(v);
m_d->m_ui.formFileLineEdit->setAllowDirectories(v);
}
}
bool NewClassWidget::lowerCaseFiles() const
{
return m_d->m_ui.classLineEdit->lowerCaseFileName();
}
void NewClassWidget::setLowerCaseFiles(bool v)
{
m_d->m_ui.classLineEdit->setLowerCaseFileName(v);
}
NewClassWidget::ClassType NewClassWidget::classType() const
{
return static_cast<ClassType>(m_d->m_ui.classTypeComboBox->currentIndex());
}
void NewClassWidget::setClassType(ClassType ct)
{
m_d->m_ui.classTypeComboBox->setCurrentIndex(ct);
}
bool NewClassWidget::isClassTypeComboVisible() const
{
return m_d->m_ui.classTypeLabel->isVisible();
}
void NewClassWidget::setClassTypeComboVisible(bool v)
{
m_d->m_ui.classTypeLabel->setVisible(v);
m_d->m_ui.classTypeComboBox->setVisible(v);
}
void NewClassWidget::slotValidChanged()
{
const bool newValid = isValid();
if (newValid != m_d->m_valid) {
m_d->m_valid = newValid;
emit validChanged();
}
}
bool NewClassWidget::isValid(QString *error) const
{
if (!m_d->m_ui.classLineEdit->isValid()) {
if (error) {
*error = m_d->m_ui.classLineEdit->errorMessage();
}
return false;
}
if (isBaseClassInputVisible() && isBaseClassEditable()) {
// TODO: Should this be a ClassNameValidatingComboBox?
QRegExp classNameValidator(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*"));
const QString baseClass = m_d->m_ui.baseClassComboBox->currentText().trimmed();
if (!baseClass.isEmpty() && !classNameValidator.exactMatch(baseClass)) {
if (error) {
*error = tr("Invalid base class name");
}
return false;
}
}
if (!m_d->m_ui.headerFileLineEdit->isValid()) {
if (error) {
*error = tr("Invalid header file name: '%1'").arg(m_d->m_ui.headerFileLineEdit->errorMessage());
}
return false;
}
if (!m_d->m_ui.sourceFileLineEdit->isValid()) {
if (error) {
*error = tr("Invalid source file name: '%1'").arg(m_d->m_ui.sourceFileLineEdit->errorMessage());
}
return false;
}
if (isFormInputVisible()) {
if (!m_d->m_ui.formFileLineEdit->isValid()) {
if (error) {
*error = tr("Invalid form file name: '%1'").arg(m_d->m_ui.formFileLineEdit->errorMessage());
}
return false;
}
}
if (isPathInputVisible()) {
if (!m_d->m_ui.pathChooser->isValid()) {
if (error) {
*error = m_d->m_ui.pathChooser->errorMessage();
}
return false;
}
}
return true;
}
void NewClassWidget::triggerUpdateFileNames()
{
m_d->m_ui.classLineEdit->triggerChanged();
}
void NewClassWidget::slotUpdateFileNames(const QString &baseName)
{
if (debugNewClassWidget) {
qDebug() << Q_FUNC_INFO << baseName << m_d->m_headerExtension << m_d->m_sourceExtension;
}
const QChar dot = QLatin1Char('.');
m_d->m_ui.sourceFileLineEdit->setText(baseName + dot + m_d->m_sourceExtension);
m_d->m_ui.headerFileLineEdit->setText(baseName + dot + m_d->m_headerExtension);
m_d->m_ui.formFileLineEdit->setText(baseName + dot + m_d->m_formExtension);
}
void NewClassWidget::slotActivated()
{
if (m_d->m_valid) {
emit activated();
}
}
QString NewClassWidget::fixSuffix(const QString &suffix)
{
QString s = suffix;
if (s.startsWith(QLatin1Char('.'))) {
s.remove(0, 1);
}
return s;
}
// Utility to add a suffix to a file unless the user specified one
static QString ensureSuffix(QString f, const QString &extension)
{
const QChar dot = QLatin1Char('.');
if (f.contains(dot)) {
return f;
}
f += dot;
f += extension;
return f;
}
// If a non-empty name was passed, expand to directory and suffix
static QString expandFileName(const QDir &dir, const QString name, const QString &extension)
{
if (name.isEmpty()) {
return QString();
}
return dir.absoluteFilePath(ensureSuffix(name, extension));
}
QStringList NewClassWidget::files() const
{
QStringList rc;
const QDir dir = QDir(path());
rc.push_back(expandFileName(dir, headerFileName(), headerExtension()));
rc.push_back(expandFileName(dir, sourceFileName(), sourceExtension()));
if (isFormInputVisible()) {
rc.push_back(expandFileName(dir, formFileName(), formExtension()));
}
return rc;
}
} // namespace Utils

View File

@ -1,163 +0,0 @@
/**
******************************************************************************
*
* @file newclasswidget.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef NEWCLASSWIDGET_H
#define NEWCLASSWIDGET_H
#include "utils_global.h"
#include <QWidget>
QT_BEGIN_NAMESPACE
class QStringList;
QT_END_NAMESPACE
namespace Utils {
struct NewClassWidgetPrivate;
/**
* NewClassWidget: Utility widget for 'New Class' wizards. Prompts the user
* to enter a class name (optionally derived from some base class) and file
* names for header, source and form files. Has some smart logic to derive
* the file names from the class name.
*/
class QTCREATOR_UTILS_EXPORT NewClassWidget : public QWidget {
Q_DISABLE_COPY(NewClassWidget)
Q_OBJECT Q_PROPERTY(bool namespacesEnabled READ namespacesEnabled WRITE setNamespacesEnabled DESIGNABLE true)
Q_PROPERTY(bool baseClassInputVisible READ isBaseClassInputVisible WRITE setBaseClassInputVisible DESIGNABLE true)
Q_PROPERTY(bool baseClassEditable READ isBaseClassEditable WRITE setBaseClassEditable DESIGNABLE false)
Q_PROPERTY(bool formInputVisible READ isFormInputVisible WRITE setFormInputVisible DESIGNABLE true)
Q_PROPERTY(bool pathInputVisible READ isPathInputVisible WRITE setPathInputVisible DESIGNABLE true)
Q_PROPERTY(bool classTypeComboVisible READ isClassTypeComboVisible WRITE setClassTypeComboVisible DESIGNABLE true)
Q_PROPERTY(QString className READ className WRITE setClassName DESIGNABLE true)
Q_PROPERTY(QString baseClassName READ baseClassName WRITE setBaseClassName DESIGNABLE true)
Q_PROPERTY(QString sourceFileName READ sourceFileName DESIGNABLE false)
Q_PROPERTY(QString headerFileName READ headerFileName DESIGNABLE false)
Q_PROPERTY(QString formFileName READ formFileName DESIGNABLE false)
Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true)
Q_PROPERTY(QStringList baseClassChoices READ baseClassChoices WRITE setBaseClassChoices DESIGNABLE true)
Q_PROPERTY(QString sourceExtension READ sourceExtension WRITE setSourceExtension DESIGNABLE true)
Q_PROPERTY(QString headerExtension READ headerExtension WRITE setHeaderExtension DESIGNABLE true)
Q_PROPERTY(QString formExtension READ formExtension WRITE setFormExtension DESIGNABLE true)
Q_PROPERTY(bool formInputCheckable READ formInputCheckable WRITE setFormInputCheckable DESIGNABLE true)
Q_PROPERTY(bool formInputChecked READ formInputChecked WRITE setFormInputChecked DESIGNABLE true)
Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories)
Q_PROPERTY(bool lowerCaseFiles READ lowerCaseFiles WRITE setLowerCaseFiles)
Q_PROPERTY(ClassType classType READ classType WRITE setClassType)
// Utility "USER" property for wizards containing file names.
Q_PROPERTY(QStringList files READ files DESIGNABLE false USER true)
Q_ENUMS(ClassType)
public:
enum ClassType { NoClassType, ClassInheritsQObject, ClassInheritsQWidget };
explicit NewClassWidget(QWidget *parent = 0);
~NewClassWidget();
bool namespacesEnabled() const;
bool isBaseClassInputVisible() const;
bool isBaseClassEditable() const;
bool isFormInputVisible() const;
bool isPathInputVisible() const;
bool formInputCheckable() const;
bool formInputChecked() const;
QString className() const;
QString baseClassName() const;
QString sourceFileName() const;
QString headerFileName() const;
QString formFileName() const;
QString path() const;
QStringList baseClassChoices() const;
QString sourceExtension() const;
QString headerExtension() const;
QString formExtension() const;
bool allowDirectories() const;
bool lowerCaseFiles() const;
ClassType classType() const;
bool isClassTypeComboVisible() const;
bool isValid(QString *error = 0) const;
QStringList files() const;
signals:
void validChanged();
void activated();
public slots:
void setNamespacesEnabled(bool b);
void setBaseClassInputVisible(bool visible);
void setBaseClassEditable(bool editable);
void setFormInputVisible(bool visible);
void setPathInputVisible(bool visible);
void setFormInputCheckable(bool v);
void setFormInputChecked(bool v);
/**
* The name passed into the new class widget will be reformatted to be a
* valid class name.
*/
void setClassName(const QString &suggestedName);
void setBaseClassName(const QString &);
void setPath(const QString &path);
void setBaseClassChoices(const QStringList &choices);
void setSourceExtension(const QString &e);
void setHeaderExtension(const QString &e);
void setFormExtension(const QString &e);
void setAllowDirectories(bool v);
void setLowerCaseFiles(bool v);
void setClassType(ClassType ct);
void setClassTypeComboVisible(bool v);
/**
* Suggest a class name from the base class by stripping the leading 'Q'
* character. This will happen automagically if the base class combo
* changes until the class line edited is manually edited.
*/
void suggestClassNameFromBase();
public slots:
/** Trigger an update (after changing settings) */
void triggerUpdateFileNames();
private slots:
void slotUpdateFileNames(const QString &t);
void slotValidChanged();
void slotActivated();
void classNameEdited();
void slotFormInputChecked();
private:
void setFormInputCheckable(bool checkable, bool force);
QString fixSuffix(const QString &suffix);
NewClassWidgetPrivate *m_d;
};
} // namespace Utils
#endif // NEWCLASSWIDGET_H

View File

@ -1,181 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Utils::NewClassWidget</class>
<widget class="QWidget" name="Utils::NewClassWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>418</width>
<height>291</height>
</rect>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::ExpandingFieldsGrow</enum>
</property>
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QLabel" name="classNameLabel">
<property name="text">
<string>Class name:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="Utils::ClassNameValidatingLineEdit" name="classLineEdit"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="baseClassLabel">
<property name="text">
<string>Base class:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="baseClassComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="classTypeLabel">
<property name="text">
<string>Type information:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="classTypeComboBox">
<item>
<property name="text">
<string>None</string>
</property>
</item>
<item>
<property name="text">
<string>Inherits QObject</string>
</property>
</item>
<item>
<property name="text">
<string>Inherits QWidget</string>
</property>
</item>
</widget>
</item>
<item row="3" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
<item row="4" column="0">
<widget class="QLabel" name="headerLabel">
<property name="text">
<string>Header file:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="Utils::FileNameValidatingLineEdit" name="headerFileLineEdit"/>
</item>
<item row="5" column="0">
<widget class="QLabel" name="sourceLabel">
<property name="text">
<string>Source file:</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="Utils::FileNameValidatingLineEdit" name="sourceFileLineEdit"/>
</item>
<item row="6" column="0">
<widget class="QLabel" name="generateFormLabel">
<property name="text">
<string>Generate form:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QCheckBox" name="generateFormCheckBox">
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="formLabel">
<property name="text">
<string>Form file:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="Utils::FileNameValidatingLineEdit" name="formFileLineEdit"/>
</item>
<item row="8" column="0">
<widget class="QLabel" name="pathLabel">
<property name="text">
<string>Path:</string>
</property>
</widget>
</item>
<item row="8" column="1">
<widget class="Utils::PathChooser" name="pathChooser"/>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>Utils::ClassNameValidatingLineEdit</class>
<extends>QLineEdit</extends>
<header location="global">utils/classnamevalidatinglineedit.h</header>
</customwidget>
<customwidget>
<class>Utils::FileNameValidatingLineEdit</class>
<extends>QLineEdit</extends>
<header location="global">utils/filenamevalidatinglineedit.h</header>
</customwidget>
<customwidget>
<class>Utils::PathChooser</class>
<extends>QWidget</extends>
<header location="global">utils/pathchooser.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -1,85 +0,0 @@
/**
******************************************************************************
*
* @file parameteraction.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "parameteraction.h"
namespace Utils {
ParameterAction::ParameterAction(const QString &emptyText,
const QString &parameterText,
EnablingMode mode,
QObject *parent) :
QAction(emptyText, parent),
m_emptyText(emptyText),
m_parameterText(parameterText),
m_enablingMode(mode)
{}
QString ParameterAction::emptyText() const
{
return m_emptyText;
}
void ParameterAction::setEmptyText(const QString &t)
{
m_emptyText = t;
}
QString ParameterAction::parameterText() const
{
return m_parameterText;
}
void ParameterAction::setParameterText(const QString &t)
{
m_parameterText = t;
}
ParameterAction::EnablingMode ParameterAction::enablingMode() const
{
return m_enablingMode;
}
void ParameterAction::setEnablingMode(EnablingMode m)
{
m_enablingMode = m;
}
void ParameterAction::setParameter(const QString &p)
{
const bool enabled = !p.isEmpty();
if (enabled) {
setText(m_parameterText.arg(p));
} else {
setText(m_emptyText);
}
if (m_enablingMode == EnabledWithParameter) {
setEnabled(enabled);
}
}
}

View File

@ -1,79 +0,0 @@
/**
******************************************************************************
*
* @file parameteraction.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PARAMETERACTION_H
#define PARAMETERACTION_H
#include "utils_global.h"
#include <QAction>
namespace Utils {
/* ParameterAction: Intended for actions that act on a 'current',
* string-type parameter (typically file name) and have 2 states:
* 1) <no current parameter> displaying "Do XX" (empty text)
* 2) <parameter present> displaying "Do XX with %1".
* Provides a slot to set the parameter, changing display
* and enabled state accordingly.
* The text passed in should already be translated; parameterText
* should contain a %1 where the parameter is to be inserted. */
class QTCREATOR_UTILS_EXPORT ParameterAction : public QAction {
Q_ENUMS(EnablingMode)
Q_PROPERTY(QString emptyText READ emptyText WRITE setEmptyText)
Q_PROPERTY(QString parameterText READ parameterText WRITE setParameterText)
Q_PROPERTY(EnablingMode enablingMode READ enablingMode WRITE setEnablingMode)
Q_OBJECT
public:
enum EnablingMode { AlwaysEnabled, EnabledWithParameter };
explicit ParameterAction(const QString &emptyText,
const QString &parameterText,
EnablingMode em = AlwaysEnabled,
QObject *parent = 0);
QString emptyText() const;
void setEmptyText(const QString &);
QString parameterText() const;
void setParameterText(const QString &);
EnablingMode enablingMode() const;
void setEnablingMode(EnablingMode m);
public slots:
void setParameter(const QString &);
private:
QString m_emptyText;
QString m_parameterText;
EnablingMode m_enablingMode;
};
}
#endif // PARAMETERACTION_H

View File

@ -1,324 +0,0 @@
/**
******************************************************************************
*
* @file pathlisteditor.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "pathlisteditor.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPlainTextEdit>
#include <QToolButton>
#include <QSpacerItem>
#include <QFileDialog>
#include <QTextCursor>
#include <QTextBlock>
#include <QMenu>
#include <QAction>
#include <QtCore/QSignalMapper>
#include <QtCore/QMimeData>
#include <QtCore/QSharedPointer>
#include <QtCore/QDir>
#include <QtCore/QDebug>
namespace Utils {
// ------------ PathListPlainTextEdit:
// Replaces the platform separator ';',':' by '\n'
// when inserting, allowing for pasting in paths
// from the terminal or such.
class PathListPlainTextEdit : public QPlainTextEdit {
public:
explicit PathListPlainTextEdit(QWidget *parent = 0);
protected:
virtual void insertFromMimeData(const QMimeData *source);
};
PathListPlainTextEdit::PathListPlainTextEdit(QWidget *parent) :
QPlainTextEdit(parent)
{
// No wrapping, scroll at all events
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setLineWrapMode(QPlainTextEdit::NoWrap);
}
void PathListPlainTextEdit::insertFromMimeData(const QMimeData *source)
{
if (source->hasText()) {
// replace separator
QString text = source->text().trimmed();
text.replace(PathListEditor::separator(), QLatin1Char('\n'));
QSharedPointer<QMimeData> fixed(new QMimeData);
fixed->setText(text);
QPlainTextEdit::insertFromMimeData(fixed.data());
} else {
QPlainTextEdit::insertFromMimeData(source);
}
}
// ------------ PathListEditorPrivate
struct PathListEditorPrivate {
PathListEditorPrivate();
QHBoxLayout *layout;
QVBoxLayout *buttonLayout;
QToolButton *toolButton;
QMenu *buttonMenu;
QPlainTextEdit *edit;
QSignalMapper *envVarMapper;
QString fileDialogTitle;
};
PathListEditorPrivate::PathListEditorPrivate() :
layout(new QHBoxLayout),
buttonLayout(new QVBoxLayout),
toolButton(new QToolButton),
buttonMenu(new QMenu),
edit(new PathListPlainTextEdit),
envVarMapper(0)
{
layout->setMargin(0);
layout->addWidget(edit);
buttonLayout->addWidget(toolButton);
buttonLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
layout->addLayout(buttonLayout);
}
PathListEditor::PathListEditor(QWidget *parent) :
QWidget(parent),
m_d(new PathListEditorPrivate)
{
setLayout(m_d->layout);
m_d->toolButton->setPopupMode(QToolButton::MenuButtonPopup);
m_d->toolButton->setText(tr("Insert..."));
m_d->toolButton->setMenu(m_d->buttonMenu);
connect(m_d->toolButton, SIGNAL(clicked()), this, SLOT(slotInsert()));
addAction(tr("Add..."), this, SLOT(slotAdd()));
addAction(tr("Delete line"), this, SLOT(deletePathAtCursor()));
addAction(tr("Clear"), this, SLOT(clear()));
}
PathListEditor::~PathListEditor()
{
delete m_d;
}
static inline QAction *createAction(QObject *parent, const QString &text, QObject *receiver, const char *slotFunc)
{
QAction *rc = new QAction(text, parent);
QObject::connect(rc, SIGNAL(triggered()), receiver, slotFunc);
return rc;
}
QAction *PathListEditor::addAction(const QString &text, QObject *receiver, const char *slotFunc)
{
QAction *rc = createAction(this, text, receiver, slotFunc);
m_d->buttonMenu->addAction(rc);
return rc;
}
QAction *PathListEditor::insertAction(int index /* -1 */, const QString &text, QObject *receiver, const char *slotFunc)
{
// Find the 'before' action
QAction *beforeAction = 0;
if (index >= 0) {
const QList<QAction *> actions = m_d->buttonMenu->actions();
if (index < actions.size()) {
beforeAction = actions.at(index);
}
}
QAction *rc = createAction(this, text, receiver, slotFunc);
if (beforeAction) {
m_d->buttonMenu->insertAction(beforeAction, rc);
} else {
m_d->buttonMenu->addAction(rc);
}
return rc;
}
int PathListEditor::lastAddActionIndex()
{
return 0; // Insert/Add
}
QString PathListEditor::pathListString() const
{
return pathList().join(separator());
}
QStringList PathListEditor::pathList() const
{
const QString text = m_d->edit->toPlainText().trimmed();
if (text.isEmpty()) {
return QStringList();
}
// trim each line
QStringList rc = text.split(QLatin1Char('\n'), QString::SkipEmptyParts);
const QStringList::iterator end = rc.end();
for (QStringList::iterator it = rc.begin(); it != end; ++it) {
*it = it->trimmed();
}
return rc;
}
void PathListEditor::setPathList(const QStringList &l)
{
m_d->edit->setPlainText(l.join(QString(QLatin1Char('\n'))));
}
void PathListEditor::setPathList(const QString &pathString)
{
if (pathString.isEmpty()) {
clear();
} else {
setPathList(pathString.split(separator(), QString::SkipEmptyParts));
}
}
void PathListEditor::setPathListFromEnvVariable(const QString &var)
{
setPathList(qgetenv(var.toLocal8Bit()));
}
QString PathListEditor::fileDialogTitle() const
{
return m_d->fileDialogTitle;
}
void PathListEditor::setFileDialogTitle(const QString &l)
{
m_d->fileDialogTitle = l;
}
void PathListEditor::clear()
{
m_d->edit->clear();
}
void PathListEditor::slotAdd()
{
const QString dir = QFileDialog::getExistingDirectory(this, m_d->fileDialogTitle);
if (!dir.isEmpty()) {
appendPath(QDir::toNativeSeparators(dir));
}
}
void PathListEditor::slotInsert()
{
const QString dir = QFileDialog::getExistingDirectory(this, m_d->fileDialogTitle);
if (!dir.isEmpty()) {
insertPathAtCursor(QDir::toNativeSeparators(dir));
}
}
QChar PathListEditor::separator()
{
#ifdef Q_OS_WIN
static const QChar rc(QLatin1Char(';'));
#else
static const QChar rc(QLatin1Char(':'));
#endif
return rc;
}
// Add a button "Import from 'Path'"
void PathListEditor::addEnvVariableImportAction(const QString &var)
{
if (!m_d->envVarMapper) {
m_d->envVarMapper = new QSignalMapper(this);
connect(m_d->envVarMapper, SIGNAL(mapped(QString)), this, SLOT(setPathListFromEnvVariable(QString)));
}
QAction *a = insertAction(lastAddActionIndex() + 1,
tr("From \"%1\"").arg(var), m_d->envVarMapper, SLOT(map()));
m_d->envVarMapper->setMapping(a, var);
}
QString PathListEditor::text() const
{
return m_d->edit->toPlainText();
}
void PathListEditor::setText(const QString &t)
{
m_d->edit->setPlainText(t);
}
void PathListEditor::insertPathAtCursor(const QString &path)
{
// If the cursor is at an empty line or at end(),
// just insert. Else insert line before
QTextCursor cursor = m_d->edit->textCursor();
QTextBlock block = cursor.block();
const bool needNewLine = !block.text().isEmpty();
if (needNewLine) {
cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
cursor.insertBlock();
cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor);
}
cursor.insertText(path);
if (needNewLine) {
cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
m_d->edit->setTextCursor(cursor);
}
}
void PathListEditor::appendPath(const QString &path)
{
QString paths = text().trimmed();
if (!paths.isEmpty()) {
paths += QLatin1Char('\n');
}
paths += path;
setText(paths);
}
void PathListEditor::deletePathAtCursor()
{
// Delete current line
QTextCursor cursor = m_d->edit->textCursor();
if (cursor.block().isValid()) {
cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
// Select down or until end of [last] line
if (!cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor)) {
cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
}
cursor.removeSelectedText();
m_d->edit->setTextCursor(cursor);
}
}
} // namespace Utils

View File

@ -1,103 +0,0 @@
/**
******************************************************************************
*
* @file pathlisteditor.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PATHLISTEDITOR_H
#define PATHLISTEDITOR_H
#include "utils_global.h"
#include <QWidget>
#include <QtCore/QStringList>
QT_BEGIN_NAMESPACE
class QAction;
QT_END_NAMESPACE
namespace Utils {
struct PathListEditorPrivate;
/**
* A control that let's the user edit a list of (directory) paths
* using the platform separator (';',':'). Typically used for
* path lists controlled by environment variables, such as
* PATH. It is based on a QPlainTextEdit as it should
* allow for convenient editing and non-directory type elements like
* "etc/mydir1:$SPECIAL_SYNTAX:/etc/mydir2".
* When pasting text into it, the platform separator will be replaced
* by new line characters for convenience.
*/
class QTCREATOR_UTILS_EXPORT PathListEditor : public QWidget {
Q_DISABLE_COPY(PathListEditor)
Q_OBJECT Q_PROPERTY(QStringList pathList READ pathList WRITE setPathList DESIGNABLE true)
Q_PROPERTY(QString fileDialogTitle READ fileDialogTitle WRITE setFileDialogTitle DESIGNABLE true)
public:
explicit PathListEditor(QWidget *parent = 0);
virtual ~PathListEditor();
QString pathListString() const;
QStringList pathList() const;
QString fileDialogTitle() const;
static QChar separator();
// Add a convenience action "Import from 'Path'" (environment variable)
void addEnvVariableImportAction(const QString &var);
public slots:
void clear();
void setPathList(const QStringList &l);
void setPathList(const QString &pathString);
void setPathListFromEnvVariable(const QString &var);
void setFileDialogTitle(const QString &l);
protected:
// Index after which to insert further "Add" actions
static int lastAddActionIndex();
QAction *insertAction(int index /* -1 */, const QString &text, QObject *receiver, const char *slotFunc);
QAction *addAction(const QString &text, QObject *receiver, const char *slotFunc);
QString text() const;
void setText(const QString &);
protected slots:
void insertPathAtCursor(const QString &);
void deletePathAtCursor();
void appendPath(const QString &);
private slots:
void slotAdd();
void slotInsert();
private:
PathListEditorPrivate *m_d;
};
} // namespace Utils
#endif // PATHLISTEDITOR_H

View File

@ -1,210 +0,0 @@
/**
******************************************************************************
*
* @file projectintropage.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "projectintropage.h"
#include "filewizardpage.h"
#include "ui_projectintropage.h"
#include <QMessageBox>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
namespace Utils {
struct ProjectIntroPagePrivate {
ProjectIntroPagePrivate();
Ui::ProjectIntroPage m_ui;
bool m_complete;
// Status label style sheets
const QString m_errorStyleSheet;
const QString m_warningStyleSheet;
const QString m_hintStyleSheet;
};
ProjectIntroPagePrivate::ProjectIntroPagePrivate() :
m_complete(false),
m_errorStyleSheet(QLatin1String("background : red;")),
m_warningStyleSheet(QLatin1String("background : yellow;")),
m_hintStyleSheet()
{}
ProjectIntroPage::ProjectIntroPage(QWidget *parent) :
QWizardPage(parent),
m_d(new ProjectIntroPagePrivate)
{
m_d->m_ui.setupUi(this);
hideStatusLabel();
m_d->m_ui.nameLineEdit->setInitialText(tr("<Enter_Name>"));
m_d->m_ui.nameLineEdit->setFocus(Qt::TabFocusReason);
connect(m_d->m_ui.pathChooser, SIGNAL(changed(QString)), this, SLOT(slotChanged()));
connect(m_d->m_ui.nameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(slotChanged()));
connect(m_d->m_ui.pathChooser, SIGNAL(returnPressed()), this, SLOT(slotActivated()));
connect(m_d->m_ui.nameLineEdit, SIGNAL(validReturnPressed()), this, SLOT(slotActivated()));
}
void ProjectIntroPage::insertControl(int row, QWidget *label, QWidget *control)
{
m_d->m_ui.formLayout->insertRow(row, label, control);
}
ProjectIntroPage::~ProjectIntroPage()
{
delete m_d;
}
QString ProjectIntroPage::name() const
{
return m_d->m_ui.nameLineEdit->text();
}
QString ProjectIntroPage::path() const
{
return m_d->m_ui.pathChooser->path();
}
void ProjectIntroPage::setPath(const QString &path)
{
m_d->m_ui.pathChooser->setPath(path);
}
void ProjectIntroPage::setName(const QString &name)
{
m_d->m_ui.nameLineEdit->setText(name);
}
QString ProjectIntroPage::description() const
{
return m_d->m_ui.descriptionLabel->text();
}
void ProjectIntroPage::setDescription(const QString &description)
{
m_d->m_ui.descriptionLabel->setText(description);
}
void ProjectIntroPage::changeEvent(QEvent *e)
{
QWizardPage::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_d->m_ui.retranslateUi(this);
break;
default:
break;
}
}
bool ProjectIntroPage::isComplete() const
{
return m_d->m_complete;
}
bool ProjectIntroPage::validate()
{
// Validate and display status
if (!m_d->m_ui.pathChooser->isValid()) {
displayStatusMessage(Error, m_d->m_ui.pathChooser->errorMessage());
return false;
}
// Name valid? Ignore 'DisplayingInitialText' state.
bool nameValid = false;
switch (m_d->m_ui.nameLineEdit->state()) {
case BaseValidatingLineEdit::Invalid:
displayStatusMessage(Error, m_d->m_ui.nameLineEdit->errorMessage());
return false;
case BaseValidatingLineEdit::DisplayingInitialText:
break;
case BaseValidatingLineEdit::Valid:
nameValid = true;
break;
}
// Check existence of the directory
QString projectDir = path();
projectDir += QDir::separator();
projectDir += m_d->m_ui.nameLineEdit->text();
const QFileInfo projectDirFile(projectDir);
if (!projectDirFile.exists()) { // All happy
hideStatusLabel();
return nameValid;
}
if (projectDirFile.isDir()) {
displayStatusMessage(Warning, tr("The project already exists."));
return nameValid;;
}
// Not a directory, but something else, likely causing directory creation to fail
displayStatusMessage(Error, tr("A file with that name already exists."));
return false;
}
void ProjectIntroPage::slotChanged()
{
const bool newComplete = validate();
if (newComplete != m_d->m_complete) {
m_d->m_complete = newComplete;
emit completeChanged();
}
}
void ProjectIntroPage::slotActivated()
{
if (m_d->m_complete) {
emit activated();
}
}
bool ProjectIntroPage::validateProjectDirectory(const QString &name, QString *errorMessage)
{
return ProjectNameValidatingLineEdit::validateProjectName(name, errorMessage);
}
void ProjectIntroPage::displayStatusMessage(StatusLabelMode m, const QString &s)
{
switch (m) {
case Error:
m_d->m_ui.stateLabel->setStyleSheet(m_d->m_errorStyleSheet);
break;
case Warning:
m_d->m_ui.stateLabel->setStyleSheet(m_d->m_warningStyleSheet);
break;
case Hint:
m_d->m_ui.stateLabel->setStyleSheet(m_d->m_hintStyleSheet);
break;
}
m_d->m_ui.stateLabel->setText(s);
}
void ProjectIntroPage::hideStatusLabel()
{
displayStatusMessage(Hint, QString());
}
} // namespace Utils

View File

@ -1,99 +0,0 @@
/**
******************************************************************************
*
* @file projectintropage.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PROJECTINTROPAGE_H
#define PROJECTINTROPAGE_H
#include "utils_global.h"
#include <QWizardPage>
namespace Utils {
struct ProjectIntroPagePrivate;
/* Standard wizard page for a single file letting the user choose name
* and path. Looks similar to FileWizardPage, but provides additional
* functionality:
* - Description label at the top for displaying introductory text
* - It does on the fly validation (connected to changed()) and displays
* warnings/errors in a status label at the bottom (the page is complete
* when fully validated, validatePage() is thus not implemented).
*
* Note: Careful when changing projectintropage.ui. It must have main
* geometry cleared and QLayout::SetMinimumSize constraint on the main
* layout, otherwise, QWizard will squeeze it due to its strange expanding
* hacks. */
class QTCREATOR_UTILS_EXPORT ProjectIntroPage : public QWizardPage {
Q_OBJECT Q_DISABLE_COPY(ProjectIntroPage)
Q_PROPERTY(QString description READ description WRITE setPath DESIGNABLE true)
Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true)
Q_PROPERTY(QString name READ name WRITE setName DESIGNABLE true)
public:
explicit ProjectIntroPage(QWidget *parent = 0);
virtual ~ProjectIntroPage();
QString name() const;
QString path() const;
QString description() const;
// Insert an additional control into the form layout for the target.
void insertControl(int row, QWidget *label, QWidget *control);
virtual bool isComplete() const;
// Validate a project directory name entry field
static bool validateProjectDirectory(const QString &name, QString *errorMessage);
signals:
void activated();
public slots:
void setPath(const QString &path);
void setName(const QString &name);
void setDescription(const QString &description);
private slots:
void slotChanged();
void slotActivated();
protected:
virtual void changeEvent(QEvent *e);
private:
enum StatusLabelMode { Error, Warning, Hint };
bool validate();
void displayStatusMessage(StatusLabelMode m, const QString &);
void hideStatusLabel();
ProjectIntroPagePrivate *m_d;
};
} // namespace Utils
#endif // PROJECTINTROPAGE_H

View File

@ -1,116 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Utils::ProjectIntroPage</class>
<widget class="QWizardPage" name="Utils::ProjectIntroPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>208</width>
<height>143</height>
</rect>
</property>
<property name="title">
<string>Introduction and project location</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetMinimumSize</enum>
</property>
<item>
<widget class="QLabel" name="descriptionLabel">
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::MinimumExpanding</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QFrame" name="frame">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="nameLabel">
<property name="text">
<string>Name:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="Utils::ProjectNameValidatingLineEdit" name="nameLineEdit"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="pathLabel">
<property name="text">
<string>Create in:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="Utils::PathChooser" name="pathChooser" native="true"/>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="stateLabel">
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>Utils::PathChooser</class>
<extends>QWidget</extends>
<header>pathchooser.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>Utils::ProjectNameValidatingLineEdit</class>
<extends>QLineEdit</extends>
<header>projectnamevalidatinglineedit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -1,59 +0,0 @@
/**
******************************************************************************
*
* @file projectnamevalidatinglineedit.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "projectnamevalidatinglineedit.h"
#include "filenamevalidatinglineedit.h"
namespace Utils {
ProjectNameValidatingLineEdit::ProjectNameValidatingLineEdit(QWidget *parent)
: BaseValidatingLineEdit(parent)
{}
bool ProjectNameValidatingLineEdit::validateProjectName(const QString &name, QString *errorMessage /* = 0*/)
{
// Validation is file name + checking for dots
if (!FileNameValidatingLineEdit::validateFileName(name, false, errorMessage)) {
return false;
}
// We don't want dots in the directory name for some legacy Windows
// reason. Since we are cross-platform, we generally disallow it.
if (name.contains(QLatin1Char('.'))) {
if (errorMessage) {
*errorMessage = tr("The name must not contain the '.'-character.");
}
return false;
}
return true;
}
bool ProjectNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{
return validateProjectName(value, errorMessage);
}
} // namespace Utils

View File

@ -1,48 +0,0 @@
/**
******************************************************************************
*
* @file projectnamevalidatinglineedit.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PROJECTNAMEVALIDATINGLINEEDIT_H
#define PROJECTNAMEVALIDATINGLINEEDIT_H
#include "basevalidatinglineedit.h"
namespace Utils {
class QTCREATOR_UTILS_EXPORT ProjectNameValidatingLineEdit : public BaseValidatingLineEdit {
Q_OBJECT Q_DISABLE_COPY(ProjectNameValidatingLineEdit)
public:
explicit ProjectNameValidatingLineEdit(QWidget *parent = 0);
static bool validateProjectName(const QString &name, QString *errorMessage /* = 0*/);
protected:
virtual bool validate(const QString &value, QString *errorMessage) const;
};
} // namespace Utils
#endif // PROJECTNAMEVALIDATINGLINEEDIT_H

View File

@ -1,70 +0,0 @@
/**
******************************************************************************
*
* @file reloadpromptutils.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "reloadpromptutils.h"
#include <QMessageBox>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
using namespace Utils;
QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)
{
const QString title = QCoreApplication::translate("Utils::reloadPrompt", "File Changed");
QString msg;
if (modified) {
msg = QCoreApplication::translate("Utils::reloadPrompt",
"The unsaved file %1 has been changed outside Qt Creator. Do you want to reload it and discard your changes?").arg(QDir::toNativeSeparators(fileName));
} else {
msg = QCoreApplication::translate("Utils::reloadPrompt",
"The file %1 has changed outside Qt Creator. Do you want to reload it?").arg(QDir::toNativeSeparators(fileName));
}
return reloadPrompt(title, msg, parent);
}
QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer Utils::reloadPrompt(const QString &title, const QString &prompt, QWidget *parent)
{
switch (QMessageBox::question(parent, title, prompt,
QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll,
QMessageBox::YesToAll)) {
case QMessageBox::Yes:
return ReloadCurrent;
case QMessageBox::YesToAll:
return ReloadAll;
case QMessageBox::No:
return ReloadSkipCurrent;
default:
break;
}
return ReloadNone;
}

View File

@ -1,46 +0,0 @@
/**
******************************************************************************
*
* @file reloadpromptutils.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef RELOADPROMPTUTILS_H
#define RELOADPROMPTUTILS_H
#include "utils_global.h"
QT_BEGIN_NAMESPACE
class QString;
class QWidget;
QT_END_NAMESPACE
namespace Utils {
enum ReloadPromptAnswer { ReloadCurrent, ReloadAll, ReloadSkipCurrent, ReloadNone };
QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName, bool modified, QWidget *parent);
QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title, const QString &prompt, QWidget *parent);
} // namespace Utils
#endif // RELOADPROMPTUTILS_H

View File

@ -1,489 +0,0 @@
/**
******************************************************************************
*
* @file savedaction.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <utils/savedaction.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
#include <QtCore/QDebug>
#include <QtCore/QSettings>
#include <QAbstractButton>
#include <QAction>
#include <QActionGroup>
#include <QCheckBox>
#include <QLineEdit>
#include <QRadioButton>
#include <QSpinBox>
using namespace Utils;
//////////////////////////////////////////////////////////////////////////
//
// SavedAction
//
//////////////////////////////////////////////////////////////////////////
/*!
\class Utils::SavedAction
\brief The SavedAction class is a helper class for actions with persistent
state.
\ingroup utils
*/
SavedAction::SavedAction(QObject *parent)
: QAction(parent)
{
m_widget = 0;
connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool)));
}
/*!
Returns the current value of the object.
\sa setValue()
*/
QVariant SavedAction::value() const
{
return m_value;
}
/*!
Sets the current value of the object. If the value changed and
\a doemit is true, the \c valueChanged() signal will be emitted.
\sa value()
*/
void SavedAction::setValue(const QVariant &value, bool doemit)
{
if (value == m_value) {
return;
}
m_value = value;
if (this->isCheckable()) {
this->setChecked(m_value.toBool());
}
if (doemit) {
emit valueChanged(m_value);
}
}
/*!
Returns the default value to be used when the item does not exist yet
in the settings.
\sa setDefaultValue()
*/
QVariant SavedAction::defaultValue() const
{
return m_defaultValue;
}
/*!
Sets the default value to be used when the item does not exist yet
in the settings.
\sa defaultValue()
*/
void SavedAction::setDefaultValue(const QVariant &value)
{
m_defaultValue = value;
}
/*!
Returns the key to be used when accessing the settings.
\sa settingsKey()
*/
QString SavedAction::settingsKey() const
{
return m_settingsKey;
}
/*!
Sets the key to be used when accessing the settings.
\sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &key)
{
m_settingsKey = key;
}
/*!
Sets the key and group to be used when accessing the settings.
\sa settingsKey()
*/
void SavedAction::setSettingsKey(const QString &group, const QString &key)
{
m_settingsKey = key;
m_settingsGroup = group;
}
/*!
Sets the key to be used when accessing the settings.
\sa settingsKey()
*/
QString SavedAction::settingsGroup() const
{
return m_settingsGroup;
}
/*!
Sets the group to be used when accessing the settings.
\sa settingsGroup()
*/
void SavedAction::setSettingsGroup(const QString &group)
{
m_settingsGroup = group;
}
QString SavedAction::textPattern() const
{
return m_textPattern;
}
void SavedAction::setTextPattern(const QString &value)
{
m_textPattern = value;
}
QString SavedAction::toString() const
{
return QLatin1String("value: ") + m_value.toString()
+ QLatin1String(" defaultvalue: ") + m_defaultValue.toString()
+ QLatin1String(" settingskey: ") + m_settingsGroup
+ '/' + m_settingsKey;
}
/*!
\fn QAction *SavedAction::updatedAction(const QString &text)
Adjust the \c text() of the underlying action.
This can be used to update the item shortly before e.g. a menu is shown.
If the item's \c textPattern() is empty the \a text will be used
verbatim.
Otherwise, the behaviour depends on \a text: if it is non-empty,
\c QString(textPattern()).arg(text), otherwise, \c textPattern()
with the "%1" placeholder removed will be used.
\sa textPattern(), setTextPattern()
*/
QAction *SavedAction::updatedAction(const QString &text0)
{
QString text = text0;
bool enabled = true;
if (!m_textPattern.isEmpty()) {
if (text.isEmpty()) {
text = m_textPattern;
text.remove("\"%1\"");
text.remove("%1");
enabled = false;
} else {
text = m_textPattern.arg(text0);
}
}
this->setEnabled(enabled);
this->setData(text0);
this->setText(text);
return this;
}
/*
Uses \c settingsGroup() and \c settingsKey() to restore the
item from \a settings,
\sa settingsKey(), settingsGroup(), writeSettings()
*/
void SavedAction::readSettings(QSettings *settings)
{
if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty()) {
return;
}
settings->beginGroup(m_settingsGroup);
QVariant var = settings->value(m_settingsKey, m_defaultValue);
// work around old ini files containing @Invalid() entries
if (isCheckable() && !var.isValid()) {
var = false;
}
setValue(var);
// qDebug() << "READING: " << var.isValid() << m_settingsKey << " -> " << m_value
// << " (default: " << m_defaultValue << ")" << var;
settings->endGroup();
}
/*
Uses \c settingsGroup() and \c settingsKey() to write the
item to \a settings,
\sa settingsKey(), settingsGroup(), readSettings()
*/
void SavedAction::writeSettings(QSettings *settings)
{
if (m_settingsGroup.isEmpty() || m_settingsKey.isEmpty()) {
return;
}
settings->beginGroup(m_settingsGroup);
settings->setValue(m_settingsKey, m_value);
// qDebug() << "WRITING: " << m_settingsKey << " -> " << toString();
settings->endGroup();
}
/*
A \c SavedAction can be connected to a widget, typically a
checkbox, radiobutton, or a lineedit in some configuration dialog.
The widget will retrieve its contents from the SavedAction's
value, and - depending on the \a ApplyMode - either write
changes back immediately, or when \s SavedAction::apply()
is called explicitly.
\sa apply(), disconnectWidget()
*/
void SavedAction::connectWidget(QWidget *widget, ApplyMode applyMode)
{
QTC_ASSERT(!m_widget,
qDebug() << "ALREADY CONNECTED: " << widget << m_widget << toString(); return );
m_widget = widget;
m_applyMode = applyMode;
if (QAbstractButton * button = qobject_cast<QAbstractButton *>(widget)) {
if (button->isCheckable()) {
button->setChecked(m_value.toBool());
connect(button, SIGNAL(clicked(bool)),
this, SLOT(checkableButtonClicked(bool)));
} else {
connect(button, SIGNAL(clicked()),
this, SLOT(uncheckableButtonClicked()));
}
} else if (QSpinBox * spinBox = qobject_cast<QSpinBox *>(widget)) {
spinBox->setValue(m_value.toInt());
// qDebug() << "SETTING VALUE" << spinBox->value();
connect(spinBox, SIGNAL(valueChanged(int)),
this, SLOT(spinBoxValueChanged(int)));
connect(spinBox, SIGNAL(valueChanged(QString)),
this, SLOT(spinBoxValueChanged(QString)));
} else if (QDoubleSpinBox * doubleSpinBox = qobject_cast<QDoubleSpinBox *>(widget)) {
doubleSpinBox->setValue(m_value.toDouble());
// qDebug() << "SETTING VALUE" << doubleSpinBox->value();
connect(doubleSpinBox, SIGNAL(valueChanged(double)),
this, SLOT(doubleSpinBoxValueChanged(double)));
connect(doubleSpinBox, SIGNAL(valueChanged(QString)),
this, SLOT(doubleSpinBoxValueChanged(QString)));
} else if (QLineEdit * lineEdit = qobject_cast<QLineEdit *>(widget)) {
lineEdit->setText(m_value.toString());
// qDebug() << "SETTING TEXT" << lineEdit->text();
connect(lineEdit, SIGNAL(editingFinished()),
this, SLOT(lineEditEditingFinished()));
} else if (PathChooser * pathChooser = qobject_cast<PathChooser *>(widget)) {
pathChooser->setPath(m_value.toString());
connect(pathChooser, SIGNAL(editingFinished()),
this, SLOT(pathChooserEditingFinished()));
connect(pathChooser, SIGNAL(browsingFinished()),
this, SLOT(pathChooserEditingFinished()));
} else {
qDebug() << "Cannot connect widget " << widget << toString();
}
}
/*
Disconnects the \c SavedAction from a widget.
\sa apply(), connectWidget()
*/
void SavedAction::disconnectWidget()
{
m_widget = 0;
}
void SavedAction::apply(QSettings *s)
{
if (QAbstractButton * button = qobject_cast<QAbstractButton *>(m_widget)) {
setValue(button->isChecked());
} else if (QLineEdit * lineEdit = qobject_cast<QLineEdit *>(m_widget)) {
setValue(lineEdit->text());
} else if (QSpinBox * spinBox = qobject_cast<QSpinBox *>(m_widget)) {
setValue(spinBox->value());
} else if (QDoubleSpinBox * doubleSpinBox = qobject_cast<QDoubleSpinBox *>(m_widget)) {
setValue(doubleSpinBox->value());
} else if (PathChooser * pathChooser = qobject_cast<PathChooser *>(m_widget)) {
setValue(pathChooser->path());
}
if (s) {
writeSettings(s);
}
}
void SavedAction::uncheckableButtonClicked()
{
QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
QTC_ASSERT(button, return );
// qDebug() << "UNCHECKABLE BUTTON: " << sender();
QAction::trigger();
}
void SavedAction::checkableButtonClicked(bool)
{
QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
QTC_ASSERT(button, return );
// qDebug() << "CHECKABLE BUTTON: " << sender();
if (m_applyMode == ImmediateApply) {
setValue(button->isChecked());
}
}
void SavedAction::lineEditEditingFinished()
{
QLineEdit *lineEdit = qobject_cast<QLineEdit *>(sender());
QTC_ASSERT(lineEdit, return );
if (m_applyMode == ImmediateApply) {
setValue(lineEdit->text());
}
}
void SavedAction::spinBoxValueChanged(int value)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
QTC_ASSERT(spinBox, return );
if (m_applyMode == ImmediateApply) {
setValue(value);
}
}
void SavedAction::spinBoxValueChanged(QString value)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(sender());
QTC_ASSERT(spinBox, return );
if (m_applyMode == ImmediateApply) {
setValue(value);
}
}
void SavedAction::doubleSpinBoxValueChanged(double value)
{
QDoubleSpinBox *doubleSpinBox = qobject_cast<QDoubleSpinBox *>(sender());
QTC_ASSERT(doubleSpinBox, return );
if (m_applyMode == ImmediateApply) {
setValue(value);
}
}
void SavedAction::doubleSpinBoxValueChanged(QString value)
{
QDoubleSpinBox *doubleSpinBox = qobject_cast<QDoubleSpinBox *>(sender());
QTC_ASSERT(doubleSpinBox, return );
if (m_applyMode == ImmediateApply) {
setValue(value);
}
}
void SavedAction::pathChooserEditingFinished()
{
PathChooser *pathChooser = qobject_cast<PathChooser *>(sender());
QTC_ASSERT(pathChooser, return );
if (m_applyMode == ImmediateApply) {
setValue(pathChooser->path());
}
}
void SavedAction::actionTriggered(bool)
{
if (isCheckable()) {
setValue(isChecked());
}
if (actionGroup() && actionGroup()->isExclusive()) {
// FIXME: should be taken care of more directly
foreach(QAction * act, actionGroup()->actions())
if (SavedAction * dact = qobject_cast<SavedAction *>(act)) {
dact->setValue(bool(act == this));
}
}
}
void SavedAction::trigger(const QVariant &data)
{
setData(data);
QAction::trigger();
}
//////////////////////////////////////////////////////////////////////////
//
// SavedActionSet
//
//////////////////////////////////////////////////////////////////////////
void SavedActionSet::insert(SavedAction *action, QWidget *widget)
{
m_list.append(action);
if (widget) {
action->connectWidget(widget);
}
}
void SavedActionSet::apply(QSettings *settings)
{
foreach(SavedAction * action, m_list)
action->apply(settings);
}
void SavedActionSet::finish()
{
foreach(SavedAction * action, m_list)
action->disconnectWidget();
}

View File

@ -1,124 +0,0 @@
/**
******************************************************************************
*
* @file savedaction.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef SAVED_ACTION_H
#define SAVED_ACTION_H
#include "utils_global.h"
#include <QtCore/QString>
#include <QtCore/QVariant>
#include <QtCore/QList>
#include <QAction>
QT_BEGIN_NAMESPACE
class QSettings;
QT_END_NAMESPACE
namespace Utils {
enum ApplyMode { ImmediateApply, DeferedApply };
class QTCREATOR_UTILS_EXPORT SavedAction : public QAction {
Q_OBJECT
public:
SavedAction(QObject *parent = 0);
virtual QVariant value() const;
Q_SLOT virtual void setValue(const QVariant &value, bool doemit = true);
virtual QVariant defaultValue() const;
Q_SLOT virtual void setDefaultValue(const QVariant &value);
virtual QAction *updatedAction(const QString &newText);
Q_SLOT virtual void trigger(const QVariant &data);
// used for persistency
virtual QString settingsKey() const;
Q_SLOT virtual void setSettingsKey(const QString &key);
Q_SLOT virtual void setSettingsKey(const QString &group, const QString &key);
virtual QString settingsGroup() const;
Q_SLOT virtual void setSettingsGroup(const QString &group);
virtual void readSettings(QSettings *settings);
Q_SLOT virtual void writeSettings(QSettings *settings);
virtual void connectWidget(QWidget *widget, ApplyMode applyMode = DeferedApply);
virtual void disconnectWidget();
Q_SLOT virtual void apply(QSettings *settings);
virtual QString textPattern() const;
Q_SLOT virtual void setTextPattern(const QString &value);
QString toString() const;
signals:
void valueChanged(const QVariant &newValue);
private:
Q_SLOT void uncheckableButtonClicked();
Q_SLOT void checkableButtonClicked(bool);
Q_SLOT void lineEditEditingFinished();
Q_SLOT void pathChooserEditingFinished();
Q_SLOT void actionTriggered(bool);
Q_SLOT void spinBoxValueChanged(int);
Q_SLOT void spinBoxValueChanged(QString);
Q_SLOT void doubleSpinBoxValueChanged(double);
Q_SLOT void doubleSpinBoxValueChanged(QString);
QVariant m_value;
QVariant m_defaultValue;
QString m_settingsKey;
QString m_settingsGroup;
QString m_textPattern;
QString m_textData;
QWidget *m_widget;
ApplyMode m_applyMode;
};
class QTCREATOR_UTILS_EXPORT SavedActionSet {
public:
SavedActionSet() {}
~SavedActionSet() {}
void insert(SavedAction *action, QWidget *widget);
void apply(QSettings *settings);
void finish();
void clear()
{
m_list.clear();
}
private:
QList<SavedAction *> m_list;
};
} // namespace Utils
#endif // SAVED_ACTION_H

View File

@ -1,537 +0,0 @@
/**
******************************************************************************
*
* @file submiteditorwidget.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "submiteditorwidget.h"
#include "submitfieldwidget.h"
#include "ui_submiteditorwidget.h"
#include <QtCore/QDebug>
#include <QtCore/QPointer>
#include <QtCore/QTimer>
#include <QPushButton>
#include <QMenu>
#include <QHBoxLayout>
#include <QToolButton>
#include <QSpacerItem>
enum { debug = 0 };
enum { defaultLineWidth = 72 };
namespace Utils {
// QActionPushButton: A push button tied to an action
// (similar to a QToolButton)
class QActionPushButton : public QPushButton {
Q_OBJECT
public:
explicit QActionPushButton(QAction *a);
private slots:
void actionChanged();
};
QActionPushButton::QActionPushButton(QAction *a) :
QPushButton(a->icon(), a->text())
{
connect(a, SIGNAL(changed()), this, SLOT(actionChanged()));
connect(this, SIGNAL(clicked()), a, SLOT(trigger()));
setEnabled(a->isEnabled());
}
void QActionPushButton::actionChanged()
{
if (const QAction * a = qobject_cast<QAction *>(sender())) {
setEnabled(a->isEnabled());
}
}
// Helpers to retrieve model data
static inline bool listModelChecked(const QAbstractItemModel *model, int row, int column = 0)
{
const QModelIndex checkableIndex = model->index(row, column, QModelIndex());
return model->data(checkableIndex, Qt::CheckStateRole).toInt() == Qt::Checked;
}
static inline QString listModelText(const QAbstractItemModel *model, int row, int column)
{
const QModelIndex index = model->index(row, column, QModelIndex());
return model->data(index, Qt::DisplayRole).toString();
}
// Find a check item in a model
static bool listModelContainsCheckedItem(const QAbstractItemModel *model)
{
const int count = model->rowCount();
for (int i = 0; i < count; i++) {
if (listModelChecked(model, i, 0)) {
return true;
}
}
return false;
}
// Convenience to extract a list of selected indexes
QList<int> selectedRows(const QAbstractItemView *view)
{
const QModelIndexList indexList = view->selectionModel()->selectedRows(0);
if (indexList.empty()) {
return QList<int>();
}
QList<int> rc;
const QModelIndexList::const_iterator cend = indexList.constEnd();
for (QModelIndexList::const_iterator it = indexList.constBegin(); it != cend; ++it) {
rc.push_back(it->row());
}
return rc;
}
// ----------- SubmitEditorWidgetPrivate
struct SubmitEditorWidgetPrivate {
// A pair of position/action to extend context menus
typedef QPair<int, QPointer<QAction> > AdditionalContextMenuAction;
SubmitEditorWidgetPrivate();
Ui::SubmitEditorWidget m_ui;
bool m_filesSelected;
bool m_filesChecked;
int m_fileNameColumn;
int m_activatedRow;
QList<AdditionalContextMenuAction> descriptionEditContextMenuActions;
QVBoxLayout *m_fieldLayout;
QList<SubmitFieldWidget *> m_fieldWidgets;
int m_lineWidth;
};
SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() :
m_filesSelected(false),
m_filesChecked(false),
m_fileNameColumn(1),
m_activatedRow(-1),
m_fieldLayout(0),
m_lineWidth(defaultLineWidth)
{}
SubmitEditorWidget::SubmitEditorWidget(QWidget *parent) :
QWidget(parent),
m_d(new SubmitEditorWidgetPrivate)
{
m_d->m_ui.setupUi(this);
m_d->m_ui.description->setContextMenuPolicy(Qt::CustomContextMenu);
m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap);
m_d->m_ui.description->setWordWrapMode(QTextOption::WordWrap);
connect(m_d->m_ui.description, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(editorCustomContextMenuRequested(QPoint)));
// File List
m_d->m_ui.fileView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_d->m_ui.fileView->setRootIsDecorated(false);
connect(m_d->m_ui.fileView, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(diffActivated(QModelIndex)));
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(m_d->m_ui.description);
}
SubmitEditorWidget::~SubmitEditorWidget()
{
delete m_d;
}
void SubmitEditorWidget::registerActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction, QAction *diffAction)
{
if (editorUndoAction) {
editorUndoAction->setEnabled(m_d->m_ui.description->document()->isUndoAvailable());
connect(m_d->m_ui.description, SIGNAL(undoAvailable(bool)), editorUndoAction, SLOT(setEnabled(bool)));
connect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo()));
}
if (editorRedoAction) {
editorRedoAction->setEnabled(m_d->m_ui.description->document()->isRedoAvailable());
connect(m_d->m_ui.description, SIGNAL(redoAvailable(bool)), editorRedoAction, SLOT(setEnabled(bool)));
connect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo()));
}
if (submitAction) {
if (debug) {
int count = 0;
if (const QAbstractItemModel * model = m_d->m_ui.fileView->model()) {
count = model->rowCount();
}
qDebug() << Q_FUNC_INFO << submitAction << count << "items" << m_d->m_filesChecked;
}
submitAction->setEnabled(m_d->m_filesChecked);
connect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool)));
m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(submitAction));
}
if (diffAction) {
if (debug) {
qDebug() << diffAction << m_d->m_filesSelected;
}
diffAction->setEnabled(m_d->m_filesSelected);
connect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool)));
connect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected()));
m_d->m_ui.buttonLayout->addWidget(new QActionPushButton(diffAction));
}
}
void SubmitEditorWidget::unregisterActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction, QAction *diffAction)
{
if (editorUndoAction) {
disconnect(m_d->m_ui.description, SIGNAL(undoAvailableChanged(bool)), editorUndoAction, SLOT(setEnabled(bool)));
disconnect(editorUndoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(undo()));
}
if (editorRedoAction) {
disconnect(m_d->m_ui.description, SIGNAL(redoAvailableChanged(bool)), editorRedoAction, SLOT(setEnabled(bool)));
disconnect(editorRedoAction, SIGNAL(triggered()), m_d->m_ui.description, SLOT(redo()));
}
if (submitAction) {
disconnect(this, SIGNAL(fileCheckStateChanged(bool)), submitAction, SLOT(setEnabled(bool)));
}
if (diffAction) {
disconnect(this, SIGNAL(fileSelectionChanged(bool)), diffAction, SLOT(setEnabled(bool)));
disconnect(diffAction, SIGNAL(triggered()), this, SLOT(triggerDiffSelected()));
}
}
// Make sure we have one terminating NL
static inline QString trimMessageText(const QString &t)
{
QString rc = t.trimmed();
rc += QLatin1Char('\n');
return rc;
}
// Extract the wrapped text from a text edit, which performs
// the wrapping only optically.
static QString wrappedText(const QTextEdit *e)
{
const QChar newLine = QLatin1Char('\n');
QString rc;
QTextCursor cursor(e->document());
cursor.movePosition(QTextCursor::Start);
while (!cursor.atEnd()) {
cursor.select(QTextCursor::LineUnderCursor);
rc += cursor.selectedText();
rc += newLine;
cursor.movePosition(QTextCursor::EndOfLine); // Mac needs it
cursor.movePosition(QTextCursor::Right);
}
return rc;
}
QString SubmitEditorWidget::descriptionText() const
{
QString rc = trimMessageText(lineWrap() ? wrappedText(m_d->m_ui.description) : m_d->m_ui.description->toPlainText());
// append field entries
foreach(const SubmitFieldWidget * fw, m_d->m_fieldWidgets)
rc += fw->fieldValues();
return rc;
}
void SubmitEditorWidget::setDescriptionText(const QString &text)
{
m_d->m_ui.description->setPlainText(text);
}
bool SubmitEditorWidget::lineWrap() const
{
return m_d->m_ui.description->lineWrapMode() != QTextEdit::NoWrap;
}
void SubmitEditorWidget::setLineWrap(bool v)
{
if (debug) {
qDebug() << Q_FUNC_INFO << v;
}
if (v) {
m_d->m_ui.description->setLineWrapColumnOrWidth(m_d->m_lineWidth);
m_d->m_ui.description->setLineWrapMode(QTextEdit::FixedColumnWidth);
} else {
m_d->m_ui.description->setLineWrapMode(QTextEdit::NoWrap);
}
}
int SubmitEditorWidget::lineWrapWidth() const
{
return m_d->m_lineWidth;
}
void SubmitEditorWidget::setLineWrapWidth(int v)
{
if (debug) {
qDebug() << Q_FUNC_INFO << v << lineWrap();
}
if (m_d->m_lineWidth == v) {
return;
}
m_d->m_lineWidth = v;
if (lineWrap()) {
m_d->m_ui.description->setLineWrapColumnOrWidth(v);
}
}
int SubmitEditorWidget::fileNameColumn() const
{
return m_d->m_fileNameColumn;
}
void SubmitEditorWidget::setFileNameColumn(int c)
{
m_d->m_fileNameColumn = c;
}
QAbstractItemView::SelectionMode SubmitEditorWidget::fileListSelectionMode() const
{
return m_d->m_ui.fileView->selectionMode();
}
void SubmitEditorWidget::setFileListSelectionMode(QAbstractItemView::SelectionMode sm)
{
m_d->m_ui.fileView->setSelectionMode(sm);
}
void SubmitEditorWidget::setFileModel(QAbstractItemModel *model)
{
m_d->m_ui.fileView->clearSelection(); // trigger the change signals
m_d->m_ui.fileView->setModel(model);
if (model->rowCount()) {
const int columnCount = model->columnCount();
for (int c = 0; c < columnCount; c++) {
m_d->m_ui.fileView->resizeColumnToContents(c);
}
}
connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(modelReset()),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SLOT(updateSubmitAction()));
connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
this, SLOT(updateSubmitAction()));
connect(m_d->m_ui.fileView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(updateDiffAction()));
updateActions();
}
QAbstractItemModel *SubmitEditorWidget::fileModel() const
{
return m_d->m_ui.fileView->model();
}
QStringList SubmitEditorWidget::selectedFiles() const
{
const QList<int> selection = selectedRows(m_d->m_ui.fileView);
if (selection.empty()) {
return QStringList();
}
QStringList rc;
const QAbstractItemModel *model = m_d->m_ui.fileView->model();
const int count = selection.size();
for (int i = 0; i < count; i++) {
rc.push_back(listModelText(model, selection.at(i), fileNameColumn()));
}
return rc;
}
QStringList SubmitEditorWidget::checkedFiles() const
{
QStringList rc;
const QAbstractItemModel *model = m_d->m_ui.fileView->model();
if (!model) {
return rc;
}
const int count = model->rowCount();
for (int i = 0; i < count; i++) {
if (listModelChecked(model, i, 0)) {
rc.push_back(listModelText(model, i, fileNameColumn()));
}
}
return rc;
}
QTextEdit *SubmitEditorWidget::descriptionEdit() const
{
return m_d->m_ui.description;
}
void SubmitEditorWidget::triggerDiffSelected()
{
const QStringList sel = selectedFiles();
if (!sel.empty()) {
emit diffSelected(sel);
}
}
void SubmitEditorWidget::diffActivatedDelayed()
{
const QStringList files = QStringList(listModelText(m_d->m_ui.fileView->model(), m_d->m_activatedRow, fileNameColumn()));
emit diffSelected(files);
}
void SubmitEditorWidget::diffActivated(const QModelIndex &index)
{
// We need to delay the signal, otherwise, the diff editor will not
// be in the foreground.
m_d->m_activatedRow = index.row();
QTimer::singleShot(0, this, SLOT(diffActivatedDelayed()));
}
void SubmitEditorWidget::updateActions()
{
updateSubmitAction();
updateDiffAction();
}
// Enable submit depending on having checked files
void SubmitEditorWidget::updateSubmitAction()
{
const bool newFilesCheckedState = hasCheckedFiles();
if (m_d->m_filesChecked != newFilesCheckedState) {
m_d->m_filesChecked = newFilesCheckedState;
emit fileCheckStateChanged(m_d->m_filesChecked);
}
}
// Enable diff depending on selected files
void SubmitEditorWidget::updateDiffAction()
{
const bool filesSelected = hasSelection();
if (m_d->m_filesSelected != filesSelected) {
m_d->m_filesSelected = filesSelected;
emit fileSelectionChanged(m_d->m_filesSelected);
}
}
bool SubmitEditorWidget::hasSelection() const
{
// Not present until model is set
if (const QItemSelectionModel * sm = m_d->m_ui.fileView->selectionModel()) {
return sm->hasSelection();
}
return false;
}
bool SubmitEditorWidget::hasCheckedFiles() const
{
if (const QAbstractItemModel * model = m_d->m_ui.fileView->model()) {
return listModelContainsCheckedItem(model);
}
return false;
}
void SubmitEditorWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_d->m_ui.retranslateUi(this);
break;
default:
break;
}
}
void SubmitEditorWidget::insertTopWidget(QWidget *w)
{
m_d->m_ui.vboxLayout->insertWidget(0, w);
}
void SubmitEditorWidget::addSubmitFieldWidget(SubmitFieldWidget *f)
{
if (!m_d->m_fieldLayout) {
// VBox with horizontal, expanding spacer
m_d->m_fieldLayout = new QVBoxLayout;
QHBoxLayout *outerLayout = new QHBoxLayout;
outerLayout->addLayout(m_d->m_fieldLayout);
outerLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
QBoxLayout *descrLayout = qobject_cast<QBoxLayout *>(m_d->m_ui.descriptionBox->layout());
Q_ASSERT(descrLayout);
descrLayout->addLayout(outerLayout);
}
m_d->m_fieldLayout->addWidget(f);
m_d->m_fieldWidgets.push_back(f);
}
QList<SubmitFieldWidget *> SubmitEditorWidget::submitFieldWidgets() const
{
return m_d->m_fieldWidgets;
}
void SubmitEditorWidget::addDescriptionEditContextMenuAction(QAction *a)
{
m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(-1, a));
}
void SubmitEditorWidget::insertDescriptionEditContextMenuAction(int pos, QAction *a)
{
m_d->descriptionEditContextMenuActions.push_back(SubmitEditorWidgetPrivate::AdditionalContextMenuAction(pos, a));
}
void SubmitEditorWidget::editorCustomContextMenuRequested(const QPoint &pos)
{
QMenu *menu = m_d->m_ui.description->createStandardContextMenu();
// Extend
foreach(const SubmitEditorWidgetPrivate::AdditionalContextMenuAction & a, m_d->descriptionEditContextMenuActions) {
if (a.second) {
if (a.first >= 0) {
menu->insertAction(menu->actions().at(a.first), a.second);
} else {
menu->addAction(a.second);
}
}
}
menu->exec(m_d->m_ui.description->mapToGlobal(pos));
delete menu;
}
} // namespace Utils
#include "submiteditorwidget.moc"

View File

@ -1,142 +0,0 @@
/**
******************************************************************************
*
* @file submiteditorwidget.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef SUBMITEDITORWIDGET_H
#define SUBMITEDITORWIDGET_H
#include "utils_global.h"
#include <QWidget>
#include <QAbstractItemView>
QT_BEGIN_NAMESPACE
class QTextEdit;
class QListWidgetItem;
class QAction;
class QAbstractItemModel;
class QModelIndex;
class QLineEdit;
QT_END_NAMESPACE
namespace Utils {
class SubmitFieldWidget;
struct SubmitEditorWidgetPrivate;
/* The submit editor presents the commit message in a text editor and an
* checkable list of modified files in a list window. The user can delete
* files from the list by unchecking them or diff the selection
* by doubleclicking. A list model which contains the file in a column
* specified by fileNameColumn should be set using setFileModel().
*
* Additionally, standard creator actions can be registered:
* Undo/redo will be set up to work with the description editor.
* Submit will be set up to be enabled according to checkstate.
* Diff will be set up to trigger diffSelected().
*
* Note that the actions are connected by signals; in the rare event that there
* are several instances of the SubmitEditorWidget belonging to the same
* context active, the actions must be registered/unregistered in the editor
* change event.
* Care should be taken to ensure the widget is deleted properly when the
* editor closes. */
class QTCREATOR_UTILS_EXPORT SubmitEditorWidget : public QWidget {
Q_OBJECT Q_DISABLE_COPY(SubmitEditorWidget)
Q_PROPERTY(QString descriptionText READ descriptionText WRITE setDescriptionText DESIGNABLE true)
Q_PROPERTY(int fileNameColumn READ fileNameColumn WRITE setFileNameColumn DESIGNABLE false)
Q_PROPERTY(QAbstractItemView::SelectionMode fileListSelectionMode READ fileListSelectionMode WRITE setFileListSelectionMode DESIGNABLE true)
Q_PROPERTY(bool lineWrap READ lineWrap WRITE setLineWrap DESIGNABLE true)
Q_PROPERTY(int lineWrapWidth READ lineWrapWidth WRITE setLineWrapWidth DESIGNABLE true)
public:
explicit SubmitEditorWidget(QWidget *parent = 0);
virtual ~SubmitEditorWidget();
void registerActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction = 0, QAction *diffAction = 0);
void unregisterActions(QAction *editorUndoAction, QAction *editorRedoAction,
QAction *submitAction = 0, QAction *diffAction = 0);
QString descriptionText() const;
void setDescriptionText(const QString &text);
int fileNameColumn() const;
void setFileNameColumn(int c);
bool lineWrap() const;
void setLineWrap(bool);
int lineWrapWidth() const;
void setLineWrapWidth(int);
QAbstractItemView::SelectionMode fileListSelectionMode() const;
void setFileListSelectionMode(QAbstractItemView::SelectionMode sm);
void setFileModel(QAbstractItemModel *model);
QAbstractItemModel *fileModel() const;
// Files to be included in submit
QStringList checkedFiles() const;
// Selected files for diff
QStringList selectedFiles() const;
QTextEdit *descriptionEdit() const;
void addDescriptionEditContextMenuAction(QAction *a);
void insertDescriptionEditContextMenuAction(int pos, QAction *a);
void addSubmitFieldWidget(SubmitFieldWidget *f);
QList<SubmitFieldWidget *> submitFieldWidgets() const;
signals:
void diffSelected(const QStringList &);
void fileSelectionChanged(bool someFileSelected);
void fileCheckStateChanged(bool someFileChecked);
protected:
virtual void changeEvent(QEvent *e);
void insertTopWidget(QWidget *w);
private slots:
void triggerDiffSelected();
void diffActivated(const QModelIndex &index);
void diffActivatedDelayed();
void updateActions();
void updateSubmitAction();
void updateDiffAction();
void editorCustomContextMenuRequested(const QPoint &);
private:
bool hasSelection() const;
bool hasCheckedFiles() const;
SubmitEditorWidgetPrivate *m_d;
};
} // namespace Utils
#endif // SUBMITEDITORWIDGET_H

View File

@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Utils::SubmitEditorWidget</class>
<widget class="QWidget" name="Utils::SubmitEditorWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>582</width>
<height>502</height>
</rect>
</property>
<property name="windowTitle">
<string>Subversion Submit</string>
</property>
<layout class="QVBoxLayout">
<item>
<widget class="QGroupBox" name="descriptionBox">
<property name="title">
<string>Des&amp;cription</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="description">
<property name="acceptRichText">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>F&amp;iles</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTreeView" name="fileView"/>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -1,389 +0,0 @@
/**
******************************************************************************
*
* @file submitfieldwidget.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "submitfieldwidget.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QToolButton>
#include <QCompleter>
#include <QIcon>
#include <QToolBar>
#include <QtCore/QList>
#include <QtCore/QDebug>
enum { debug = 0 };
enum { spacing = 2 };
static void inline setComboBlocked(QComboBox *cb, int index)
{
const bool blocked = cb->blockSignals(true);
cb->setCurrentIndex(index);
cb->blockSignals(blocked);
}
namespace Utils {
// Field/Row entry
struct FieldEntry {
FieldEntry();
void createGui(const QIcon &removeIcon);
void deleteGuiLater();
QComboBox *combo;
QHBoxLayout *layout;
QLineEdit *lineEdit;
QToolBar *toolBar;
QToolButton *clearButton;
QToolButton *browseButton;
int comboIndex;
};
FieldEntry::FieldEntry() :
combo(0),
layout(0),
lineEdit(0),
toolBar(0),
clearButton(0),
browseButton(0),
comboIndex(0)
{}
void FieldEntry::createGui(const QIcon &removeIcon)
{
layout = new QHBoxLayout;
layout->setMargin(0);
layout->setSpacing(spacing);
combo = new QComboBox;
layout->addWidget(combo);
lineEdit = new QLineEdit;
layout->addWidget(lineEdit);
toolBar = new QToolBar;
toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
layout->addWidget(toolBar);
clearButton = new QToolButton;
clearButton->setIcon(removeIcon);
toolBar->addWidget(clearButton);
browseButton = new QToolButton;
browseButton->setText(QLatin1String("..."));
toolBar->addWidget(browseButton);
}
void FieldEntry::deleteGuiLater()
{
clearButton->deleteLater();
browseButton->deleteLater();
toolBar->deleteLater();
lineEdit->deleteLater();
combo->deleteLater();
layout->deleteLater();
}
// ------- SubmitFieldWidgetPrivate
struct SubmitFieldWidgetPrivate {
SubmitFieldWidgetPrivate();
int findSender(const QObject *o) const;
int findField(const QString &f, int excluded = -1) const;
inline QString fieldText(int) const;
inline QString fieldValue(int) const;
inline void focusField(int);
const QIcon removeFieldIcon;
QStringList fields;
QCompleter *completer;
bool hasBrowseButton;
bool allowDuplicateFields;
QList <FieldEntry> fieldEntries;
QVBoxLayout *layout;
};
SubmitFieldWidgetPrivate::SubmitFieldWidgetPrivate() :
removeFieldIcon(QLatin1String(":/utils/images/removesubmitfield.png")),
completer(0),
hasBrowseButton(false),
allowDuplicateFields(false),
layout(0)
{}
int SubmitFieldWidgetPrivate::findSender(const QObject *o) const
{
const int count = fieldEntries.size();
for (int i = 0; i < count; i++) {
const FieldEntry &fe = fieldEntries.at(i);
if (fe.combo == o || fe.browseButton == o || fe.clearButton == o || fe.lineEdit == o) {
return i;
}
}
return -1;
}
int SubmitFieldWidgetPrivate::findField(const QString &ft, int excluded) const
{
const int count = fieldEntries.size();
for (int i = 0; i < count; i++) {
if (i != excluded && fieldText(i) == ft) {
return i;
}
}
return -1;
}
QString SubmitFieldWidgetPrivate::fieldText(int pos) const
{
return fieldEntries.at(pos).combo->currentText();
}
QString SubmitFieldWidgetPrivate::fieldValue(int pos) const
{
return fieldEntries.at(pos).lineEdit->text();
}
void SubmitFieldWidgetPrivate::focusField(int pos)
{
fieldEntries.at(pos).lineEdit->setFocus(Qt::TabFocusReason);
}
// SubmitFieldWidget
SubmitFieldWidget::SubmitFieldWidget(QWidget *parent) :
QWidget(parent),
m_d(new SubmitFieldWidgetPrivate)
{
m_d->layout = new QVBoxLayout;
m_d->layout->setMargin(0);
m_d->layout->setSpacing(spacing);
setLayout(m_d->layout);
}
SubmitFieldWidget::~SubmitFieldWidget()
{
delete m_d;
}
void SubmitFieldWidget::setFields(const QStringList & f)
{
// remove old fields
for (int i = m_d->fieldEntries.size() - 1; i >= 0; i--) {
removeField(i);
}
m_d->fields = f;
if (!f.empty()) {
createField(f.front());
}
}
QStringList SubmitFieldWidget::fields() const
{
return m_d->fields;
}
bool SubmitFieldWidget::hasBrowseButton() const
{
return m_d->hasBrowseButton;
}
void SubmitFieldWidget::setHasBrowseButton(bool d)
{
if (m_d->hasBrowseButton == d) {
return;
}
m_d->hasBrowseButton = d;
foreach(const FieldEntry &fe, m_d->fieldEntries)
fe.browseButton->setVisible(d);
}
bool SubmitFieldWidget::allowDuplicateFields() const
{
return m_d->allowDuplicateFields;
}
void SubmitFieldWidget::setAllowDuplicateFields(bool v)
{
m_d->allowDuplicateFields = v;
}
QCompleter *SubmitFieldWidget::completer() const
{
return m_d->completer;
}
void SubmitFieldWidget::setCompleter(QCompleter *c)
{
if (c == m_d->completer) {
return;
}
m_d->completer = c;
foreach(const FieldEntry &fe, m_d->fieldEntries)
fe.lineEdit->setCompleter(c);
}
QString SubmitFieldWidget::fieldValue(int pos) const
{
return m_d->fieldValue(pos);
}
void SubmitFieldWidget::setFieldValue(int pos, const QString &value)
{
m_d->fieldEntries.at(pos).lineEdit->setText(value);
}
QString SubmitFieldWidget::fieldValues() const
{
const QChar blank = QLatin1Char(' ');
const QChar newLine = QLatin1Char('\n');
// Format as "RevBy: value\nSigned-Off: value\n"
QString rc;
foreach(const FieldEntry &fe, m_d->fieldEntries) {
const QString value = fe.lineEdit->text().trimmed();
if (!value.isEmpty()) {
rc += fe.combo->currentText();
rc += blank;
rc += value;
rc += newLine;
}
}
return rc;
}
void SubmitFieldWidget::createField(const QString &f)
{
FieldEntry fe;
fe.createGui(m_d->removeFieldIcon);
fe.combo->addItems(m_d->fields);
if (!f.isEmpty()) {
const int index = fe.combo->findText(f);
if (index != -1) {
setComboBlocked(fe.combo, index);
fe.comboIndex = index;
}
}
connect(fe.browseButton, SIGNAL(clicked()), this, SLOT(slotBrowseButtonClicked()));
if (!m_d->hasBrowseButton) {
fe.browseButton->setVisible(false);
}
if (m_d->completer) {
fe.lineEdit->setCompleter(m_d->completer);
}
connect(fe.combo, SIGNAL(currentIndexChanged(int)),
this, SLOT(slotComboIndexChanged(int)));
connect(fe.clearButton, SIGNAL(clicked()),
this, SLOT(slotRemove()));
m_d->layout->addLayout(fe.layout);
m_d->fieldEntries.push_back(fe);
}
void SubmitFieldWidget::slotRemove()
{
// Never remove first entry
const int index = m_d->findSender(sender());
switch (index) {
case -1:
break;
case 0:
m_d->fieldEntries.front().lineEdit->clear();
break;
default:
removeField(index);
break;
}
}
void SubmitFieldWidget::removeField(int index)
{
FieldEntry fe = m_d->fieldEntries.takeAt(index);
QLayoutItem *item = m_d->layout->takeAt(index);
fe.deleteGuiLater();
delete item;
}
void SubmitFieldWidget::slotComboIndexChanged(int comboIndex)
{
const int pos = m_d->findSender(sender());
if (debug) {
qDebug() << '>' << Q_FUNC_INFO << pos;
}
if (pos == -1) {
return;
}
// Accept new index or reset combo to previous value?
int &previousIndex = m_d->fieldEntries[pos].comboIndex;
if (comboIndexChange(pos, comboIndex)) {
previousIndex = comboIndex;
} else {
setComboBlocked(m_d->fieldEntries.at(pos).combo, previousIndex);
}
if (debug) {
qDebug() << '<' << Q_FUNC_INFO << pos;
}
}
// Handle change of a combo. Return "false" if the combo
// is to be reset (refuse new field).
bool SubmitFieldWidget::comboIndexChange(int pos, int index)
{
const QString newField = m_d->fieldEntries.at(pos).combo->itemText(index);
// If the field is visible elsewhere: focus the existing one and refuse
if (!m_d->allowDuplicateFields) {
const int existingFieldIndex = m_d->findField(newField, pos);
if (existingFieldIndex != -1) {
m_d->focusField(existingFieldIndex);
return false;
}
}
// Empty value: just change the field
if (m_d->fieldValue(pos).isEmpty()) {
return true;
}
// Non-empty: Create a new field and reset the triggering combo
createField(newField);
return false;
}
void SubmitFieldWidget::slotBrowseButtonClicked()
{
const int pos = m_d->findSender(sender());
emit browseButtonClicked(pos, m_d->fieldText(pos));
}
}

View File

@ -1,93 +0,0 @@
/**
******************************************************************************
*
* @file submitfieldwidget.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef SUBMITFIELDWIDGET_H
#define SUBMITFIELDWIDGET_H
#include "utils_global.h"
#include <QWidget>
QT_BEGIN_NAMESPACE
class QCompleter;
QT_END_NAMESPACE
namespace Utils {
struct SubmitFieldWidgetPrivate;
/* A widget for editing submit message fields like "reviewed-by:",
* "signed-off-by:". It displays them in a vertical row of combo/line edit fields
* that is modeled after the target address controls of mail clients.
* When choosing a different field in the combo, a new row is opened if text
* has been entered for the current field. Optionally, a "Browse..." button and
* completer can be added. */
class QTCREATOR_UTILS_EXPORT SubmitFieldWidget : public QWidget {
Q_OBJECT Q_PROPERTY(QStringList fields READ fields WRITE setFields DESIGNABLE true)
Q_PROPERTY(bool hasBrowseButton READ hasBrowseButton WRITE setHasBrowseButton DESIGNABLE true)
Q_PROPERTY(bool allowDuplicateFields READ allowDuplicateFields WRITE setAllowDuplicateFields DESIGNABLE true)
public:
explicit SubmitFieldWidget(QWidget *parent = 0);
virtual ~SubmitFieldWidget();
QStringList fields() const;
void setFields(const QStringList &);
bool hasBrowseButton() const;
void setHasBrowseButton(bool d);
// Allow several entries for fields ("reviewed-by: a", "reviewed-by: b")
bool allowDuplicateFields() const;
void setAllowDuplicateFields(bool);
QCompleter *completer() const;
void setCompleter(QCompleter *c);
QString fieldValue(int pos) const;
void setFieldValue(int pos, const QString &value);
QString fieldValues() const;
signals:
void browseButtonClicked(int pos, const QString &field);
private slots:
void slotRemove();
void slotComboIndexChanged(int);
void slotBrowseButtonClicked();
private:
void removeField(int index);
bool comboIndexChange(int fieldNumber, int index);
void createField(const QString &f);
SubmitFieldWidgetPrivate *m_d;
};
}
#endif // SUBMITFIELDWIDGET_H

View File

@ -1,161 +0,0 @@
/**
******************************************************************************
*
* @file uncommentselection.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "uncommentselection.h"
#include <QPlainTextEdit>
#include <QTextCursor>
#include <QTextBlock>
#include <QTextDocument>
void Utils::unCommentSelection(QPlainTextEdit *edit)
{
QTextCursor cursor = edit->textCursor();
QTextDocument *doc = cursor.document();
cursor.beginEditBlock();
int pos = cursor.position();
int anchor = cursor.anchor();
int start = qMin(anchor, pos);
int end = qMax(anchor, pos);
bool anchorIsStart = (anchor == start);
QTextBlock startBlock = doc->findBlock(start);
QTextBlock endBlock = doc->findBlock(end);
if (end > start && endBlock.position() == end) {
--end;
endBlock = endBlock.previous();
}
bool doCStyleUncomment = false;
bool doCStyleComment = false;
bool doCppStyleUncomment = false;
bool hasSelection = cursor.hasSelection();
if (hasSelection) {
QString startText = startBlock.text();
int startPos = start - startBlock.position();
bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty();
if ((startPos >= 2
&& startText.at(startPos - 2) == QLatin1Char('/')
&& startText.at(startPos - 1) == QLatin1Char('*'))) {
startPos -= 2;
start -= 2;
}
bool hasSelStart = (startPos < startText.length() - 2
&& startText.at(startPos) == QLatin1Char('/')
&& startText.at(startPos + 1) == QLatin1Char('*'));
QString endText = endBlock.text();
int endPos = end - endBlock.position();
bool hasTrailingCharacters = !endText.left(endPos).remove(QLatin1String("//")).trimmed().isEmpty()
&& !endText.mid(endPos).trimmed().isEmpty();
if ((endPos <= endText.length() - 2
&& endText.at(endPos) == QLatin1Char('*')
&& endText.at(endPos + 1) == QLatin1Char('/'))) {
endPos += 2;
end += 2;
}
bool hasSelEnd = (endPos >= 2
&& endText.at(endPos - 2) == QLatin1Char('*')
&& endText.at(endPos - 1) == QLatin1Char('/'));
doCStyleUncomment = hasSelStart && hasSelEnd;
doCStyleComment = !doCStyleUncomment && (hasLeadingCharacters || hasTrailingCharacters);
}
if (doCStyleUncomment) {
cursor.setPosition(end);
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, 2);
cursor.removeSelectedText();
cursor.setPosition(start);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2);
cursor.removeSelectedText();
} else if (doCStyleComment) {
cursor.setPosition(end);
cursor.insertText(QLatin1String("*/"));
cursor.setPosition(start);
cursor.insertText(QLatin1String("/*"));
} else {
endBlock = endBlock.next();
doCppStyleUncomment = true;
for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
QString text = block.text();
if (!text.trimmed().startsWith(QLatin1String("//"))) {
doCppStyleUncomment = false;
break;
}
}
for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
if (doCppStyleUncomment) {
QString text = block.text();
int i = 0;
while (i < text.size() - 1) {
if (text.at(i) == QLatin1Char('/')
&& text.at(i + 1) == QLatin1Char('/')) {
cursor.setPosition(block.position() + i);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2);
cursor.removeSelectedText();
break;
}
if (!text.at(i).isSpace()) {
break;
}
++i;
}
} else {
cursor.setPosition(block.position());
cursor.insertText(QLatin1String("//"));
}
}
}
// adjust selection when commenting out
if (hasSelection && !doCStyleUncomment && !doCppStyleUncomment) {
cursor = edit->textCursor();
if (!doCStyleComment) {
start = startBlock.position(); // move the double slashes into the selection
}
int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor();
if (anchorIsStart) {
cursor.setPosition(start);
cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor);
} else {
cursor.setPosition(lastSelPos);
cursor.setPosition(start, QTextCursor::KeepAnchor);
}
edit->setTextCursor(cursor);
}
cursor.endEditBlock();
}

View File

@ -1,42 +0,0 @@
/**
******************************************************************************
*
* @file uncommentselection.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
* @brief
* @see The GNU Public License (GPL) Version 3
* @defgroup
* @{
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef UNCOMMENTSELECTION_H
#define UNCOMMENTSELECTION_H
#include "utils_global.h"
QT_BEGIN_NAMESPACE
class QPlainTextEdit;
QT_END_NAMESPACE
namespace Utils {
QTCREATOR_UTILS_EXPORT void unCommentSelection(QPlainTextEdit *edit);
} // end of namespace Utils
#endif // UNCOMMENTSELECTION_H

View File

@ -12,29 +12,13 @@ DEFINES += LIB_REL_PATH=$$shell_quote(\"$$relative_path($$GCS_LIBRARY_PATH, $$GC
DEFINES += PLUGIN_REL_PATH=$$shell_quote(\"$$relative_path($$GCS_PLUGIN_PATH, $$GCS_APP_PATH)\")
SOURCES += \
reloadpromptutils.cpp \
stringutils.cpp \
filesearch.cpp \
pathchooser.cpp \
pathlisteditor.cpp \
filewizardpage.cpp \
filewizarddialog.cpp \
projectintropage.cpp \
basevalidatinglineedit.cpp \
filenamevalidatinglineedit.cpp \
projectnamevalidatinglineedit.cpp \
codegeneration.cpp \
newclasswidget.cpp \
classnamevalidatinglineedit.cpp \
linecolumnlabel.cpp \
qtcolorbutton.cpp \
savedaction.cpp \
submiteditorwidget.cpp \
synchronousprocess.cpp \
submitfieldwidget.cpp \
consoleprocess.cpp \
uncommentselection.cpp \
parameteraction.cpp \
treewidgetcolumnstretcher.cpp \
checkablemessagebox.cpp \
styledbar.cpp \
@ -57,7 +41,6 @@ SOURCES += \
mustache.cpp \
textbubbleslider.cpp
SOURCES += xmlconfig.cpp
win32 {
@ -71,31 +54,15 @@ else:SOURCES += consoleprocess_unix.cpp
HEADERS += \
utils_global.h \
reloadpromptutils.h \
stringutils.h \
filesearch.h \
listutils.h \
pathchooser.h \
pathlisteditor.h \
filewizardpage.h \
filewizarddialog.h \
projectintropage.h \
basevalidatinglineedit.h \
filenamevalidatinglineedit.h \
projectnamevalidatinglineedit.h \
codegeneration.h \
newclasswidget.h \
classnamevalidatinglineedit.h \
linecolumnlabel.h \
qtcolorbutton.h \
savedaction.h \
submiteditorwidget.h \
abstractprocess.h \
consoleprocess.h \
synchronousprocess.h \
submitfieldwidget.h \
uncommentselection.h \
parameteraction.h \
treewidgetcolumnstretcher.h \
checkablemessagebox.h \
qtcassert.h \
@ -123,10 +90,6 @@ HEADERS += \
HEADERS += xmlconfig.h
FORMS += \
filewizardpage.ui \
projectintropage.ui \
newclasswidget.ui \
submiteditorwidget.ui \
checkablemessagebox.ui
RESOURCES += utils.qrc

View File

@ -1,6 +1,5 @@
<RCC>
<qresource prefix="/utils" >
<file>images/removesubmitfield.png</file>
<file>fonts/PTS75F.ttf</file>
</qresource>
</RCC>