Merge branch 'master' of git@scm.dev.nokia.troll.no:creator/mainline

This commit is contained in:
Jarek Kobus
2008-12-11 13:49:12 +01:00
262 changed files with 4081 additions and 2621 deletions

View File

@@ -1674,7 +1674,10 @@ static void qDumpQObjectSignal(QDumper &d)
d.beginHash(); d.beginHash();
P(d, "name", "[" << i << "] slot"); P(d, "name", "[" << i << "] slot");
P(d, "type", ""); P(d, "type", "");
if (conn.receiver)
P(d, "value", conn.receiver->metaObject()->method(conn.method).signature()); P(d, "value", conn.receiver->metaObject()->method(conn.method).signature());
else
P(d, "value", "<invalid receiver>");
P(d, "numchild", "0"); P(d, "numchild", "0");
d.endHash(); d.endHash();
d.beginHash(); d.beginHash();
@@ -1861,17 +1864,25 @@ static void qDumpQSet(QDumper &d)
n = 100; n = 100;
d << ",children=["; d << ",children=[";
int i = 0; int i = 0;
for (int bucket = 0; bucket != hd->numBuckets; ++bucket) { for (int bucket = 0; bucket != hd->numBuckets && i <= 10000; ++bucket) {
for (node = hd->buckets[bucket]; node->next; node = node->next) { for (node = hd->buckets[bucket]; node->next; node = node->next) {
d.beginHash(); d.beginHash();
P(d, "name", "[" << i << "]"); P(d, "name", "[" << i << "]");
P(d, "type", d.innertype); P(d, "type", d.innertype);
P(d, "exp", "(('QHashNode<" << d.innertype P(d, "exp", "(('"NS"QHashNode<" << d.innertype
<< ",QHashDummyValue>'*)" << ","NS"QHashDummyValue>'*)"
<< static_cast<const void*>(node) << ")->key" << static_cast<const void*>(node) << ")->key"
); );
d.endHash(); d.endHash();
++i; ++i;
if (i > 10000) {
d.beginHash();
P(d, "name", "Warning:");
P(d, "value", "<incomplete>");
P(d, "type", "");
d.endHash();
break;
}
} }
} }
d << "]"; d << "]";

Binary file not shown.

View File

@@ -23,6 +23,8 @@
\o \inlineimage qtcreator.png \o \inlineimage qtcreator.png
\o Qt Creator includes a wide range of useful features. Among them are: \o Qt Creator includes a wide range of useful features. Among them are:
\list 1 \list 1
\o \bold{Smart Code Editor}: The code editor provides syntax
highlighting as well as code completion.
\o \bold{Qt4 Project Generating Wizard}: This wizard allows the user \o \bold{Qt4 Project Generating Wizard}: This wizard allows the user
to generate a project for a console application, a GUI application, to generate a project for a console application, a GUI application,
or a C++ library. or a C++ library.
@@ -48,7 +50,7 @@
\o \l{Creating a Project in Qt Creator} \o \l{Creating a Project in Qt Creator}
\o \l{Build Settings} \o \l{Build Settings}
\o \l{Writing a Simple Program with Qt Creator} \o \l{Writing a Simple Program with Qt Creator}
\o \l{Quick Navigation} \o \l{Navigating Quickly Around Your Code}
\o \l{Debugging with Qt Creator} \o \l{Debugging with Qt Creator}
\o \l{Tips and Tricks} \o \l{Tips and Tricks}
\o \l{Glossary} \o \l{Glossary}
@@ -64,86 +66,85 @@
\title A Quick Tour Around Qt Creator \title A Quick Tour Around Qt Creator
The labeled screenshot below shows some of the components of Qt Creator, The labeled screenshot below shows some of the components of Qt Creator, in
in \gui Edit mode. \gui Edit mode.
\image qtcreator-breakdown.png \image qtcreator-breakdown.png
\seection1 The Mode Selectors \section1 The Mode Selectors
When working in Qt Creator, you can be in one of five modes: \bold Project, When working in Qt Creator, you can be in one of six modes: \bold Welcome,
\bold Edit, \bold Debug, \bold Help, and \bold Output. \bold Edit, \bold Debug, \bold Projects, \bold Help, and \bold Output.
Mode selectors allow you to quickly switch between tasks: Editing, Mode selectors allow you to quickly switch between tasks: Editing, browsing
browsing the Qt manual, setting up the build environment, etc. You can the Qt Creator manual, setting up the build environment, etc. You can
activate a mode by either clicking on its mode selector, or using the activate a mode by either clicking on its mode selector, or using the
\l{keyboard-shortcuts}{corresponding shortcut}. Certain actions also \l{keyboard-shortcuts}{corresponding shortcut}. Certain actions also
trigger a mode change, e.g., \gui{Debug}/\gui{Start Debugging} will switch trigger a mode change, e.g., \gui{Debug}/\gui{Start Debugging} will switch
to the \gui Debug mode. to the \gui Debug mode.
\list \list
\o \gui{Welcome Mode} - Displays a welcome screen allowing you to quickly \o \gui{Welcome Mode} - Displays a welcome screen allowing you to quickly
load recent sessions or individual projects. This is the first mode load recent sessions or individual projects. This is the mode you will see
displayed if Qt Creator is run without command line switches. if Qt Creator is run without command line switches.
\o \gui{Edit Mode} - You can edit both project and source files here. An \o \gui{Edit Mode} - Lets you edit both project and source files. A sidebar
optional sidebar on the left provides different views to navigate between on the left provides different views to navigate between files.
files.
\o \gui{Debug Mode} - Provides various ways to inspect the state of the \o \gui{Debug Mode} - Provides various ways to inspect the state of the
program while debugging. See \l{qtcreator-debugging}{Debugging With Qt program while debugging. See \l{qtcreator-debugging}{Debugging With Qt
Creator} for a hands-on description of the mode. Creator} for a hands-on description of how to use this mode.
\o \gui{Build & Run Mode} - Lets you configure how projects can be built \o \gui{Projects Mode} - Lets you configure how projects can be built and
and executed. Under the list of projects, there are tabs to configure the executed. Under the list of projects, there are tabs to configure the
build and run settings. build, run, and editor settings.
\o \gui{Help Mode} - Shows any documentation registered by Qt Assistant, \o \gui{Help Mode} - Shows any documentation registered by Qt Assistant,
such as the Qt library and Qt Creator documentation. such as the Qt library and Qt Creator documentation.
\o \gui{Output Mode} - Lets you examine various logs in detail, for example \o \gui{Output Mode} - Lets you examine various data in detail, for example
the task list, the compiler and application output. Some of these logs can build issues as well as compile and application output. This information
also be viewed in the output panes. is also available in the output panes.
\endlist \endlist
\section1 The Output Panes \section1 The Output Panes
The task pane in Qt Creator can display one out of four different panes: The task pane in Qt Creator can display one of four different panes:
Task List, Search Results, Application Output, and Compile Output. These \gui{Build Issues}, \gui{Search Results}, \gui{Application Output}, and
panes are available in all modes. \gui{Compile}. These panes are available in all modes.
\section2 Task List \section2 Build Issues
The Task List provides a list of important tasks such as error messages The {Build Issues} pane provides a list of issues, e.g., error messages or
that need to be fixed. It filters out irrelevant output from the compiler warnings that need to be fixed. It filters out irrelevant output from the
and collects them in the form of tasks. compiler and collects them in an organized way.
\image qtcreator-task-list.png \image qtcreator-build-issues.png
\section2 Search Results \section2 Search Results
The Search Results pane displays the results for global searches such as The \gui{Search Results} pane displays the results for global searches such
searching within a current document, files on disk, or all projects. as searching within a current document, files on disk, or all projects. In
In the screenshot below, we searched for all occurrences of \c{textfinder} the screenshot below, we searched for all occurrences of \c{textfinder}
within the "/TextFinder" folder. within the \c{"/TextFinder"} folder.
\image qtcreator-search-pane.png \image qtcreator-search-pane.png
\section2 Application Output \section2 Application Output
This pane displays the status of the program when it is executed, as The \gui{Application Output} pane displays the status of the program when
well as debug output, for example, output from qDebug(). it is executed and debug output, e.g., output from qDebug().
\image qtcreator-application-output.png \image qtcreator-application-output.png
\section2 Compile Output \section2 Compile
The Compile Output provides all the output from the compiler. In other The \gui{Compile} pane provides all the output from the compiler. In other
words, it is a more verbose version of the Task List. words, it is a more verbose version of information displayed in the
\gui{Build Issues}
\image qtcreator-compile-pane.png \image qtcreator-compile-pane.png
@@ -521,7 +522,7 @@
\page creator-navigation.html \page creator-navigation.html
\nextpage creator-debugging.html \nextpage creator-debugging.html
\title Quick Navigation \title Navigating Quickly Around Your Code
With Qt Creator, navigating to different locations in your project or on With Qt Creator, navigating to different locations in your project or on
your disk, such as files, classes and methods, is trivial using the input your disk, such as files, classes and methods, is trivial using the input
@@ -613,7 +614,7 @@
\page creator-debugging.html \page creator-debugging.html
\nextpage creator-tips.html \nextpage creator-tips.html
\title Debugging With Qt Creator \title Debugging with Qt Creator
\table \table
\row \row
@@ -677,9 +678,9 @@
\list \list
\o At a particular line you want the program to stop -- click on the \o At a particular line you want the program to stop -- click on the
left margin or press \key F9 (\key F8 for Mac Os X). left margin or press \key F9 (\key F8 for Mac OS X).
\o At the name of a function that you want the program to stop -- enter \o At a function that you want the program to stop -- enter the
the function's name in \gui{Set Breakpoint at Function...} under the function's name in \gui{Set Breakpoint at Function...} under the
\gui Debug menu. \gui Debug menu.
\endlist \endlist
@@ -744,7 +745,7 @@
When the program being debugged is stopped, Qt Creator displays the nested When the program being debugged is stopped, Qt Creator displays the nested
function calls leading to the current position as a \e call stack trace. function calls leading to the current position as a \e call stack trace.
This stack trace is built up from \e call stack frames, each representing a This stack trace is built up from \e{call stack frames}, each representing a
particular function. For each function, Qt Creator will try to retrieve the particular function. For each function, Qt Creator will try to retrieve the
file name and line number of the corresponding source files. This data is file name and line number of the corresponding source files. This data is
shown in the \gui Stack view. shown in the \gui Stack view.
@@ -765,11 +766,10 @@
\section2 Threads \section2 Threads
The \gui Thread view displays the state of the program being debugged one If a multi-threaded program is stopped, the \gui Thread view or the
thread at a time. If a multi-threaded program is stopped, the \gui Thread combobox named \gui Thread in the debugger's status bar can be used to
view or the combobox named \gui Thread in the debugger's status bar can switch from one thread to another. The \gui Stack view will adjust itself
be used to switch from one thread to another. The \gui Stack view will accordingly.
adjust itself accordingly.
\section2 Locals and Watchers \section2 Locals and Watchers
@@ -851,8 +851,7 @@
function, the latter the current state of the CPU registers. function, the latter the current state of the CPU registers.
Both views are mainly useful in connection with the low-level Both views are mainly useful in connection with the low-level
\gui{Step single instruction} and \gui{Step over single instruction} \gui{Step single instruction} and \gui{Step over single instruction}
commands commands.
\section1 A Walkthrough for the Debugger Frontend \section1 A Walkthrough for the Debugger Frontend
@@ -947,27 +946,27 @@
\bold{Running Qt Creator from the Command Line} \bold{Running Qt Creator from the Command Line}
You can start Qt Creator from a command prompt with an existing session or You can start Qt Creator from a command prompt with the name of an existing
\c{.pro} file by giving the name as argument on the command line. session or \c{.pro} file by giving the name as argument on the command
line.
\bold{Sidebar} \bold{Show and Hide the Sidebar}
You can hide/unhide the sidebar in the edit and debug mode You can show and hide the the sidebar in \gui Edit and \gui Debug mode by
by clicking on the corresponding icon on the left bottom. clicking on the corresponding icon, or by pressing \key{Alt+0}.
Keyboard shortcut is \key{Alt+0}.
\bold{Display signals and slots} \bold{Display Signals and Slots}
If you have an instance of a class derived from QObject and If you have an instance of a class that is derived from QObject, and you
want to find all other objects connected to one of its you would like to find all other objects connected to one of your object's
slots by Qt's signals-and-slots mechanism, enable slots using Qt's signals and slots mechanism -- you can enable
\gui{Debug} and \gui{Use Custom Display for Qt Objects}. \gui{Use Custom Display for Qt Objects} feature under the \gui Debug menu.
In the \gui{Locals and Watchers View}, expand the object's
entry and open the wanted slot in the "slots" subitem. The
objects connect to this slot are exposed as children of
this slot. The same works with signals.
\bold{Low level display} In the \gui{Locals and Watchers} view, expand the object's entry and open
the slot in the \e slots subitem. The objects connected to this slot are
exposed as children of the slot. This method works with signals too.
\bold{Display Low Level Data}
If the special debugging of Qt objects fails due to data If the special debugging of Qt objects fails due to data
corruption within the debugged objects, you can switch the corruption within the debugged objects, you can switch the
@@ -983,33 +982,38 @@
\title Glossary \title Glossary
\bold{System Qt} \table
\header
\o Term
\o Meaning
\target glossary-system-qt \row
The version of Qt installed on your system. \o System Qt \target glossary-system-qt
This is the one whose \c qmake command is found in the \c PATH. \o The version of Qt installed on your system. This is the Qt
version for the \c qmake command found in your \c PATH.
\bold{Default Qt} \row
\o Default Qt \target glossary-default-qt
\o The version of Qt configured in \gui{Tools -> Options -> Qt 4
-> Default Qt Version}. This is the Qt version used by your
new projects. It defaults to System Qt.
\target glossary-default-qt \row
The version of Qt configured in \gui{Tools \o Project Qt \target glossary-project-qt
-> Options -> Qt 4 -> Default Qt Version}. This is the version \o The version of Qt configured in \gui{Build&Run -> Build
used by new projects. It defaults to the System Qt. Settings -> Build Configurations}. This is the Qt version that
is actually used by a particular project. It defaults to
Default Qt.
\bold{Project Qt} \row
\o Shadow Build \target glossary-shadow-build
\target glossary-project-qt \o Shadow building means building a project in a separate
The version of Qt configured in \gui{Build&Run directory, the \e{build directory}. The build directory is
-> Build Settings -> Build Configurations}. This is the version different from the source directory. One of the benefits of
actually used by the project. It defaults to the Default Qt. shadow building is that it keeps your source directory clean.
Shadow building is the best practice if you need many build
\bold{Shadow Build} configurations for a single set of source.
\endtable
\target glossary-shadow-build
Shadow building means building the project not in the source directory,
but in a seperate \bold{build directory}. This has the benefit of keeping
the source directory clean. It is also considered "best practice" if
you need many build configurations for a single set of sources.
*/ */

View File

@@ -239,7 +239,7 @@ static void appendFileData(QIODevice *out, const QString &fileName)
static void appendFileData(QIODevice *out, QIODevice *in) static void appendFileData(QIODevice *out, QIODevice *in)
{ {
Q_ASSERT(!in->isSequential()); QTC_ASSERT(!in->isSequential(), return);
qint64 size = in->size(); qint64 size = in->size();
QByteArray &b = theBuffer(size); QByteArray &b = theBuffer(size);
rawRead(in, b.data(), size); rawRead(in, b.data(), size);

View File

@@ -66,8 +66,6 @@ FileDataList splitDiffToFiles(const QByteArray &data)
// The algorithm works like this: // The algorithm works like this:
// On the first match we only get the filename of the first patch part // On the first match we only get the filename of the first patch part
// On the second match (if any) we get the diff content, and the name of the next file patch // On the second match (if any) we get the diff content, and the name of the next file patch
//
while (-1 != (splitIndex = splitExpr.indexIn(strData,splitIndex))) { while (-1 != (splitIndex = splitExpr.indexIn(strData,splitIndex))) {
if (!filename.isEmpty()) { if (!filename.isEmpty()) {

View File

@@ -511,6 +511,12 @@ Identifier *Control::findOrInsertIdentifier(const char *chars)
return findOrInsertIdentifier(chars, length); return findOrInsertIdentifier(chars, length);
} }
Control::IdentifierIterator Control::firstIdentifier() const
{ return d->identifiers.begin(); }
Control::IdentifierIterator Control::lastIdentifier() const
{ return d->identifiers.end(); }
StringLiteral *Control::findOrInsertStringLiteral(const char *chars, unsigned size) StringLiteral *Control::findOrInsertStringLiteral(const char *chars, unsigned size)
{ return d->stringLiterals.findOrInsertLiteral(chars, size); } { return d->stringLiterals.findOrInsertLiteral(chars, size); }

View File

@@ -151,6 +151,11 @@ public:
Identifier *findOrInsertIdentifier(const char *chars, unsigned size); Identifier *findOrInsertIdentifier(const char *chars, unsigned size);
Identifier *findOrInsertIdentifier(const char *chars); Identifier *findOrInsertIdentifier(const char *chars);
typedef const Identifier *const *IdentifierIterator;
IdentifierIterator firstIdentifier() const;
IdentifierIterator lastIdentifier() const;
StringLiteral *findOrInsertStringLiteral(const char *chars, unsigned size); StringLiteral *findOrInsertStringLiteral(const char *chars, unsigned size);
StringLiteral *findOrInsertStringLiteral(const char *chars); StringLiteral *findOrInsertStringLiteral(const char *chars);

View File

@@ -30,17 +30,20 @@
** version 1.2, included in the file GPL_EXCEPTION.txt in this package. ** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
** **
***************************************************************************/ ***************************************************************************/
#include "formresizer.h" #include "formresizer.h"
#include "sizehandlerect.h" #include "sizehandlerect.h"
#include "widgethostconstants.h" #include "widgethostconstants.h"
#include <utils/qtcassert.h>
#include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerFormWindowInterface>
#include <QtGui/QResizeEvent> #include <QtGui/QResizeEvent>
#include <QtGui/QPalette> #include <QtGui/QPalette>
#include <QtGui/QLayout> #include <QtGui/QLayout>
#include <QtGui/QFrame> #include <QtGui/QFrame>
#include <QtGui/QResizeEvent> #include <QtGui/QResizeEvent>
#include <QtCore/QDebug>
enum { debugFormResizer = 0 }; enum { debugFormResizer = 0 };
@@ -140,7 +143,7 @@ void FormResizer::setFormWindow(QDesignerFormWindowInterface *fw)
if (debugFormResizer) if (debugFormResizer)
qDebug() << "FormResizer::setFormWindow " << fw; qDebug() << "FormResizer::setFormWindow " << fw;
QVBoxLayout *layout = qobject_cast<QVBoxLayout *>(m_frame->layout()); QVBoxLayout *layout = qobject_cast<QVBoxLayout *>(m_frame->layout());
Q_ASSERT(layout); QTC_ASSERT(layout, return);
if (layout->count()) if (layout->count())
delete layout->takeAt(0); delete layout->takeAt(0);
m_formWindow = fw; m_formWindow = fw;

View File

@@ -95,8 +95,10 @@ private:
QSortFilterProxyModel *proxyModel; QSortFilterProxyModel *proxyModel;
}; };
class TreeView : public QTreeView { class TreeView : public QTreeView
{
Q_OBJECT Q_OBJECT
public: public:
TreeView(QWidget* parent = 0) : QTreeView(parent) {} TreeView(QWidget* parent = 0) : QTreeView(parent) {}
void subclassKeyPressEvent(QKeyEvent* event) void subclassKeyPressEvent(QKeyEvent* event)

View File

@@ -33,6 +33,8 @@
#include "indenter.h" #include "indenter.h"
#include <utils/qtcassert.h>
using namespace SharedTools::IndenterInternal; using namespace SharedTools::IndenterInternal;
// --- Constants // --- Constants
@@ -57,10 +59,10 @@ Constants::Constants() :
{ {
m_literal.setMinimal(true); m_literal.setMinimal(true);
m_inlineCComment.setMinimal(true); m_inlineCComment.setMinimal(true);
Q_ASSERT(m_literal.isValid()); QTC_ASSERT(m_literal.isValid(), return);
Q_ASSERT(m_label.isValid()); QTC_ASSERT(m_label.isValid(), return);
Q_ASSERT(m_inlineCComment.isValid()); QTC_ASSERT(m_inlineCComment.isValid(), return);
Q_ASSERT(m_braceX.isValid()); QTC_ASSERT(m_braceX.isValid(), return);
Q_ASSERT(m_iflikeKeyword.isValid()); QTC_ASSERT(m_iflikeKeyword.isValid(), return);
Q_ASSERT(m_caseLabel.isValid()); QTC_ASSERT(m_caseLabel.isValid(), return);
} }

View File

@@ -174,7 +174,7 @@ int main(int argc, char **argv)
return 1; return 1;
} }
foreach(QString fileName, fileNames) foreach (const QString &fileName, fileNames)
if (const int rc = format(fileName)) if (const int rc = format(fileName))
return rc; return rc;

View File

@@ -33,6 +33,8 @@
#include "procommandmanager.h" #include "procommandmanager.h"
#include <utils/qtcassert.h>
using namespace Qt4ProjectManager::Internal; using namespace Qt4ProjectManager::Internal;
ProCommandGroup::ProCommandGroup(const QString &name) ProCommandGroup::ProCommandGroup(const QString &name)
@@ -76,7 +78,7 @@ ProCommandManager::~ProCommandManager()
void ProCommandManager::beginGroup(const QString &name) void ProCommandManager::beginGroup(const QString &name)
{ {
Q_ASSERT(!m_group); QTC_ASSERT(!m_group, return);
if (m_pos != m_groups.count()) { if (m_pos != m_groups.count()) {
int removecount = m_groups.count() - m_pos; int removecount = m_groups.count() - m_pos;
@@ -95,7 +97,7 @@ bool ProCommandManager::hasGroup() const
void ProCommandManager::endGroup() void ProCommandManager::endGroup()
{ {
Q_ASSERT(m_group); QTC_ASSERT(m_group, return);
m_groups.append(m_group); m_groups.append(m_group);
m_pos = m_groups.count(); m_pos = m_groups.count();
@@ -106,7 +108,7 @@ void ProCommandManager::endGroup()
bool ProCommandManager::command(ProCommand *cmd) bool ProCommandManager::command(ProCommand *cmd)
{ {
Q_ASSERT(m_group); QTC_ASSERT(m_group, return false);
if (cmd->redo()) { if (cmd->redo()) {
m_group->appendCommand(cmd); m_group->appendCommand(cmd);

View File

@@ -168,11 +168,8 @@ void ProEditor::updatePasteAction()
bool pasteEnabled = false; bool pasteEnabled = false;
const QMimeData *data = QApplication::clipboard()->mimeData(); const QMimeData *data = QApplication::clipboard()->mimeData();
if (data) { if (data && data->hasFormat(QLatin1String("application/x-problock")))
if (data->hasFormat(QLatin1String("application/x-problock"))) {
pasteEnabled = true; pasteEnabled = true;
}
}
m_pasteAction->setEnabled(pasteEnabled); m_pasteAction->setEnabled(pasteEnabled);
} }

View File

@@ -732,13 +732,10 @@ bool ProEditorModel::insertItem(ProItem *item, int row, const QModelIndex &paren
void ProEditorModel::markProFileModified(QModelIndex index) void ProEditorModel::markProFileModified(QModelIndex index)
{ {
while(index.isValid()) while (index.isValid()) {
{ if (proItem(index)->kind() == ProItem::BlockKind) {
if( proItem(index)->kind() == ProItem::BlockKind)
{
ProBlock * block = proBlock(index); ProBlock * block = proBlock(index);
if(block->blockKind() == ProBlock::ProFileKind) if (block->blockKind() == ProBlock::ProFileKind) {
{
ProFile * file = static_cast<ProFile *>(block); ProFile * file = static_cast<ProFile *>(block);
file->setModified(true); file->setModified(true);
return; return;
@@ -808,14 +805,16 @@ QString ProEditorModel::expressionToString(ProBlock *block, bool display) const
} else { } else {
result += v->text(); result += v->text();
} }
break; } break;
}
case ProItem::OperatorKind: { case ProItem::OperatorKind: {
ProOperator *v = static_cast<ProOperator*>(item); ProOperator *v = static_cast<ProOperator*>(item);
if (v->operatorKind() == ProOperator::NotOperator) if (v->operatorKind() == ProOperator::NotOperator)
result += QLatin1Char('!'); result += QLatin1Char('!');
else else
result += QLatin1Char('|'); result += QLatin1Char('|');
break; } break;
}
case ProItem::ValueKind: case ProItem::ValueKind:
case ProItem::BlockKind: case ProItem::BlockKind:
break; // ### unhandled break; // ### unhandled

View File

@@ -35,6 +35,8 @@
#include "proparserutils.h" #include "proparserutils.h"
#include "proitems.h" #include "proitems.h"
#include <utils/qtcassert.h>
#include <QtCore/QByteArray> #include <QtCore/QByteArray>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QDir> #include <QtCore/QDir>
@@ -683,7 +685,7 @@ bool ProFileEvaluator::Private::visitProFunction(ProFunction *func)
QString text = func->text(); QString text = func->text();
int lparen = text.indexOf(QLatin1Char('(')); int lparen = text.indexOf(QLatin1Char('('));
int rparen = text.lastIndexOf(QLatin1Char(')')); int rparen = text.lastIndexOf(QLatin1Char(')'));
Q_ASSERT(lparen < rparen); QTC_ASSERT(lparen < rparen, return false);
QString arguments = text.mid(lparen + 1, rparen - lparen - 1); QString arguments = text.mid(lparen + 1, rparen - lparen - 1);
QString funcName = text.left(lparen); QString funcName = text.left(lparen);

View File

@@ -170,7 +170,7 @@ void ProWriter::writeBlock(ProBlock *block, const QString &indent)
m_writeState &= ~FirstItem; m_writeState &= ~FirstItem;
if (i == 0) if (i == 0)
m_writeState |= FirstItem; m_writeState |= FirstItem;
if (i == (items.count()-1)) if (i == items.count() - 1)
m_writeState |= LastItem; m_writeState |= LastItem;
writeItem(items.at(i), newindent); writeItem(items.at(i), newindent);
} }

View File

@@ -33,13 +33,16 @@
#include "resourcefile_p.h" #include "resourcefile_p.h"
#include <QtCore/QtAlgorithms> #include <utils/qtcassert.h>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QCoreApplication> #include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QMimeData>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QMimeData>
#include <QtCore/QtAlgorithms>
#include <QtCore/QTextStream>
#include <QtGui/QIcon> #include <QtGui/QIcon>
#include <QtGui/QImageReader> #include <QtGui/QImageReader>
@@ -109,14 +112,14 @@ bool ResourceFile::load()
const QString language = relt.attribute(QLatin1String("lang")); const QString language = relt.attribute(QLatin1String("lang"));
const int idx = indexOfPrefix(prefix); const int idx = indexOfPrefix(prefix);
Prefix * p = NULL; Prefix * p = 0;
if (idx == -1) { if (idx == -1) {
p = new Prefix(prefix, language); p = new Prefix(prefix, language);
m_prefix_list.append(p); m_prefix_list.append(p);
} else { } else {
p = m_prefix_list[idx]; p = m_prefix_list[idx];
} }
Q_ASSERT(p != NULL); QTC_ASSERT(p, return false);
QDomElement felt = relt.firstChildElement(QLatin1String("file")); QDomElement felt = relt.firstChildElement(QLatin1String("file"));
for (; !felt.isNull(); felt = felt.nextSiblingElement(QLatin1String("file"))) { for (; !felt.isNull(); felt = felt.nextSiblingElement(QLatin1String("file"))) {
@@ -151,7 +154,7 @@ bool ResourceFile::save()
const QStringList name_list = prefixList(); const QStringList name_list = prefixList();
foreach (QString name, name_list) { foreach (const QString &name, name_list) {
FileList file_list; FileList file_list;
QString lang; QString lang;
foreach (Prefix *pref, m_prefix_list) { foreach (Prefix *pref, m_prefix_list) {
@@ -247,9 +250,9 @@ bool ResourceFile::isEmpty() const
QStringList ResourceFile::fileList(int pref_idx) const QStringList ResourceFile::fileList(int pref_idx) const
{ {
Q_ASSERT((pref_idx >= 0) && (pref_idx < m_prefix_list.count()));
const FileList &abs_file_list = m_prefix_list.at(pref_idx)->file_list;
QStringList result; QStringList result;
QTC_ASSERT(pref_idx >= 0 && pref_idx < m_prefix_list.count(), return result);
const FileList &abs_file_list = m_prefix_list.at(pref_idx)->file_list;
foreach (const File *abs_file, abs_file_list) foreach (const File *abs_file, abs_file_list)
result.append(relativePath(abs_file->name)); result.append(relativePath(abs_file->name));
return result; return result;
@@ -258,9 +261,9 @@ QStringList ResourceFile::fileList(int pref_idx) const
void ResourceFile::addFile(int prefix_idx, const QString &file, int file_idx) void ResourceFile::addFile(int prefix_idx, const QString &file, int file_idx)
{ {
Prefix * const p = m_prefix_list[prefix_idx]; Prefix * const p = m_prefix_list[prefix_idx];
Q_ASSERT(p != NULL); QTC_ASSERT(p, return);
FileList &files = p->file_list; FileList &files = p->file_list;
Q_ASSERT((file_idx >= -1) && (file_idx <= files.size())); QTC_ASSERT(file_idx >= -1 && file_idx <= files.size(), return);
if (file_idx == -1) if (file_idx == -1)
file_idx = files.size(); file_idx = files.size();
files.insert(file_idx, new File(p, absolutePath(file))); files.insert(file_idx, new File(p, absolutePath(file)));
@@ -272,7 +275,7 @@ void ResourceFile::addPrefix(const QString &prefix, int prefix_idx)
if (indexOfPrefix(fixed_prefix) != -1) if (indexOfPrefix(fixed_prefix) != -1)
return; return;
Q_ASSERT((prefix_idx >= -1) && (prefix_idx <= m_prefix_list.size())); QTC_ASSERT(prefix_idx >= -1 && prefix_idx <= m_prefix_list.size(), return);
if (prefix_idx == -1) if (prefix_idx == -1)
prefix_idx = m_prefix_list.size(); prefix_idx = m_prefix_list.size();
m_prefix_list.insert(prefix_idx, new Prefix(fixed_prefix)); m_prefix_list.insert(prefix_idx, new Prefix(fixed_prefix));
@@ -280,7 +283,7 @@ void ResourceFile::addPrefix(const QString &prefix, int prefix_idx)
void ResourceFile::removePrefix(int prefix_idx) void ResourceFile::removePrefix(int prefix_idx)
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return);
Prefix * const p = m_prefix_list.at(prefix_idx); Prefix * const p = m_prefix_list.at(prefix_idx);
delete p; delete p;
m_prefix_list.removeAt(prefix_idx); m_prefix_list.removeAt(prefix_idx);
@@ -288,39 +291,39 @@ void ResourceFile::removePrefix(int prefix_idx)
void ResourceFile::removeFile(int prefix_idx, int file_idx) void ResourceFile::removeFile(int prefix_idx, int file_idx)
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return);
FileList &fileList = m_prefix_list[prefix_idx]->file_list; FileList &fileList = m_prefix_list[prefix_idx]->file_list;
Q_ASSERT((file_idx >= 0) && (file_idx < fileList.count())); QTC_ASSERT(file_idx >= 0 && file_idx < fileList.count(), return);
delete fileList.at(file_idx); delete fileList.at(file_idx);
fileList.removeAt(file_idx); fileList.removeAt(file_idx);
} }
void ResourceFile::replacePrefix(int prefix_idx, const QString &prefix) void ResourceFile::replacePrefix(int prefix_idx, const QString &prefix)
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return);
m_prefix_list[prefix_idx]->name = fixPrefix(prefix); m_prefix_list[prefix_idx]->name = fixPrefix(prefix);
} }
void ResourceFile::replaceLang(int prefix_idx, const QString &lang) void ResourceFile::replaceLang(int prefix_idx, const QString &lang)
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return);
m_prefix_list[prefix_idx]->lang = lang; m_prefix_list[prefix_idx]->lang = lang;
} }
void ResourceFile::replaceAlias(int prefix_idx, int file_idx, const QString &alias) void ResourceFile::replaceAlias(int prefix_idx, int file_idx, const QString &alias)
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return);
FileList &fileList = m_prefix_list.at(prefix_idx)->file_list; FileList &fileList = m_prefix_list.at(prefix_idx)->file_list;
Q_ASSERT((file_idx >= 0) && (file_idx < fileList.count())); QTC_ASSERT(file_idx >= 0 && file_idx < fileList.count(), return);
fileList[file_idx]->alias = alias; fileList[file_idx]->alias = alias;
} }
void ResourceFile::replaceFile(int pref_idx, int file_idx, const QString &file) void ResourceFile::replaceFile(int pref_idx, int file_idx, const QString &file)
{ {
Q_ASSERT((pref_idx >= 0) && (pref_idx < m_prefix_list.count())); QTC_ASSERT(pref_idx >= 0 && pref_idx < m_prefix_list.count(), return);
FileList &fileList = m_prefix_list.at(pref_idx)->file_list; FileList &fileList = m_prefix_list.at(pref_idx)->file_list;
Q_ASSERT((file_idx >= 0) && (file_idx < fileList.count())); QTC_ASSERT(file_idx >= 0 && file_idx < fileList.count(), return);
fileList[file_idx]->name = file; fileList[file_idx]->name = file;
} }
@@ -336,7 +339,7 @@ int ResourceFile::indexOfPrefix(const QString &prefix) const
int ResourceFile::indexOfFile(int pref_idx, const QString &file) const int ResourceFile::indexOfFile(int pref_idx, const QString &file) const
{ {
Q_ASSERT((pref_idx >= 0) && (pref_idx < m_prefix_list.count())); QTC_ASSERT(pref_idx >= 0 && pref_idx < m_prefix_list.count(), return -1);
Prefix * const p = m_prefix_list.at(pref_idx); Prefix * const p = m_prefix_list.at(pref_idx);
File equalFile(p, absolutePath(file)); File equalFile(p, absolutePath(file));
return p->file_list.indexOf(&equalFile); return p->file_list.indexOf(&equalFile);
@@ -370,16 +373,16 @@ bool ResourceFile::contains(const QString &prefix, const QString &file) const
return false; return false;
if (file.isEmpty()) if (file.isEmpty())
return true; return true;
Q_ASSERT((pref_idx >= 0) && (pref_idx < m_prefix_list.count())); QTC_ASSERT(pref_idx >= 0 && pref_idx < m_prefix_list.count(), return false);
Prefix * const p = m_prefix_list.at(pref_idx); Prefix * const p = m_prefix_list.at(pref_idx);
Q_ASSERT(p != NULL); QTC_ASSERT(p, return false);
File equalFile(p, absolutePath(file)); File equalFile(p, absolutePath(file));
return p->file_list.contains(&equalFile); return p->file_list.contains(&equalFile);
} }
bool ResourceFile::contains(int pref_idx, const QString &file) const bool ResourceFile::contains(int pref_idx, const QString &file) const
{ {
Q_ASSERT((pref_idx >= 0) && (pref_idx < m_prefix_list.count())); QTC_ASSERT(pref_idx >= 0 && pref_idx < m_prefix_list.count(), return false);
Prefix * const p = m_prefix_list.at(pref_idx); Prefix * const p = m_prefix_list.at(pref_idx);
File equalFile(p, absolutePath(file)); File equalFile(p, absolutePath(file));
return p->file_list.contains(&equalFile); return p->file_list.contains(&equalFile);
@@ -409,49 +412,49 @@ int ResourceFile::prefixCount() const
QString ResourceFile::prefix(int idx) const QString ResourceFile::prefix(int idx) const
{ {
Q_ASSERT((idx >= 0) && (idx < m_prefix_list.count())); QTC_ASSERT((idx >= 0) && (idx < m_prefix_list.count()), return QString());
return m_prefix_list.at(idx)->name; return m_prefix_list.at(idx)->name;
} }
QString ResourceFile::lang(int idx) const QString ResourceFile::lang(int idx) const
{ {
Q_ASSERT((idx >= 0) && (idx < m_prefix_list.count())); QTC_ASSERT(idx >= 0 && idx < m_prefix_list.count(), return QString());
return m_prefix_list.at(idx)->lang; return m_prefix_list.at(idx)->lang;
} }
int ResourceFile::fileCount(int prefix_idx) const int ResourceFile::fileCount(int prefix_idx) const
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return 0);
return m_prefix_list.at(prefix_idx)->file_list.size(); return m_prefix_list.at(prefix_idx)->file_list.size();
} }
QString ResourceFile::file(int prefix_idx, int file_idx) const QString ResourceFile::file(int prefix_idx, int file_idx) const
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return QString());
FileList &fileList = m_prefix_list.at(prefix_idx)->file_list; FileList &fileList = m_prefix_list.at(prefix_idx)->file_list;
Q_ASSERT((file_idx >= 0) && (file_idx < fileList.count())); QTC_ASSERT(file_idx >= 0 && file_idx < fileList.count(), return QString());
return fileList.at(file_idx)->name; return fileList.at(file_idx)->name;
} }
QString ResourceFile::alias(int prefix_idx, int file_idx) const QString ResourceFile::alias(int prefix_idx, int file_idx) const
{ {
Q_ASSERT((prefix_idx >= 0) && (prefix_idx < m_prefix_list.count())); QTC_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count(), return QString());
FileList &fileList = m_prefix_list.at(prefix_idx)->file_list; FileList &fileList = m_prefix_list.at(prefix_idx)->file_list;
Q_ASSERT((file_idx >= 0) && (file_idx < fileList.count())); QTC_ASSERT(file_idx >= 0 && file_idx < fileList.count(), return QString());
return fileList.at(file_idx)->alias; return fileList.at(file_idx)->alias;
} }
void * ResourceFile::prefixPointer(int prefixIndex) const void * ResourceFile::prefixPointer(int prefixIndex) const
{ {
Q_ASSERT((prefixIndex >= 0) && (prefixIndex < m_prefix_list.count())); QTC_ASSERT(prefixIndex >= 0 && prefixIndex < m_prefix_list.count(), return 0);
return m_prefix_list.at(prefixIndex); return m_prefix_list.at(prefixIndex);
} }
void * ResourceFile::filePointer(int prefixIndex, int fileIndex) const void * ResourceFile::filePointer(int prefixIndex, int fileIndex) const
{ {
Q_ASSERT((prefixIndex >= 0) && (prefixIndex < m_prefix_list.count())); QTC_ASSERT(prefixIndex >= 0 && prefixIndex < m_prefix_list.count(), return 0);
FileList &fileList = m_prefix_list.at(prefixIndex)->file_list; FileList &fileList = m_prefix_list.at(prefixIndex)->file_list;
Q_ASSERT((fileIndex >= 0) && (fileIndex < fileList.count())); QTC_ASSERT(fileIndex >= 0 && fileIndex < fileList.count(), return 0);
return fileList.at(fileIndex); return fileList.at(fileIndex);
} }
@@ -497,28 +500,28 @@ QModelIndex ResourceModel::index(int row, int column, const QModelIndex &parent)
if (column != 0) if (column != 0)
return QModelIndex(); return QModelIndex();
void * internalPointer = NULL; void * internalPointer = 0;
if (parent.isValid()) { if (parent.isValid()) {
void * const pip = parent.internalPointer(); void * const pip = parent.internalPointer();
if (pip == NULL) if (pip == 0)
return QModelIndex(); return QModelIndex();
// File node // File node
Node * const node = reinterpret_cast<Node *>(pip); Node * const node = reinterpret_cast<Node *>(pip);
Prefix * const prefix = node->prefix(); Prefix * const prefix = node->prefix();
Q_ASSERT(prefix != NULL); QTC_ASSERT(prefix, return QModelIndex());
if ((row < 0) || (row >= prefix->file_list.count())) if (row < 0 || row >= prefix->file_list.count())
return QModelIndex(); return QModelIndex();
const int prefixIndex = m_resource_file.prefixPointerIndex(prefix); const int prefixIndex = m_resource_file.prefixPointerIndex(prefix);
const int fileIndex = row; const int fileIndex = row;
internalPointer = m_resource_file.filePointer(prefixIndex, fileIndex); internalPointer = m_resource_file.filePointer(prefixIndex, fileIndex);
} else { } else {
// Prefix node // Prefix node
if ((row < 0) || (row >= m_resource_file.prefixCount())) if (row < 0 || row >= m_resource_file.prefixCount())
return QModelIndex(); return QModelIndex();
internalPointer = m_resource_file.prefixPointer(row); internalPointer = m_resource_file.prefixPointer(row);
} }
Q_ASSERT(internalPointer != NULL); QTC_ASSERT(internalPointer, return QModelIndex());
return createIndex(row, 0, internalPointer); return createIndex(row, 0, internalPointer);
} }
@@ -528,16 +531,16 @@ QModelIndex ResourceModel::parent(const QModelIndex &index) const
return QModelIndex(); return QModelIndex();
void * const internalPointer = index.internalPointer(); void * const internalPointer = index.internalPointer();
if (internalPointer == NULL) if (internalPointer == 0)
return QModelIndex(); return QModelIndex();
Node * const node = reinterpret_cast<Node *>(internalPointer); Node * const node = reinterpret_cast<Node *>(internalPointer);
Prefix * const prefix = node->prefix(); Prefix * const prefix = node->prefix();
Q_ASSERT(prefix != NULL); QTC_ASSERT(prefix, return QModelIndex());
bool const isFileNode = (prefix != node); bool const isFileNode = (prefix != node);
if (isFileNode) { if (isFileNode) {
const int row = m_resource_file.prefixPointerIndex(prefix); const int row = m_resource_file.prefixPointerIndex(prefix);
Q_ASSERT(row >= 0); QTC_ASSERT(row >= 0, return QModelIndex());
return createIndex(row, 0, prefix); return createIndex(row, 0, prefix);
} else { } else {
return QModelIndex(); return QModelIndex();
@@ -550,7 +553,7 @@ int ResourceModel::rowCount(const QModelIndex &parent) const
void * const internalPointer = parent.internalPointer(); void * const internalPointer = parent.internalPointer();
Node * const node = reinterpret_cast<Node *>(internalPointer); Node * const node = reinterpret_cast<Node *>(internalPointer);
Prefix * const prefix = node->prefix(); Prefix * const prefix = node->prefix();
Q_ASSERT(prefix != NULL); QTC_ASSERT(prefix, return 0);
bool const isFileNode = (prefix != node); bool const isFileNode = (prefix != node);
if (isFileNode) { if (isFileNode) {
@@ -609,7 +612,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const
Node * const node = reinterpret_cast<Node *>(internalPointer); Node * const node = reinterpret_cast<Node *>(internalPointer);
Prefix const * const prefix = node->prefix(); Prefix const * const prefix = node->prefix();
File const * const file = node->file(); File const * const file = node->file();
Q_ASSERT(prefix != NULL); QTC_ASSERT(prefix, return QVariant());
bool const isFileNode = (prefix != node); bool const isFileNode = (prefix != node);
QVariant result; QVariant result;
@@ -626,7 +629,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const
appendParenthesized(lang, stringRes); appendParenthesized(lang, stringRes);
} else { } else {
// File node // File node
Q_ASSERT(file != NULL); QTC_ASSERT(file, return result);
stringRes = QFileInfo(file->name).fileName(); stringRes = QFileInfo(file->name).fileName();
const QString alias = file->alias; const QString alias = file->alias;
if (!alias.isEmpty()) if (!alias.isEmpty())
@@ -638,7 +641,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const
case Qt::DecorationRole: case Qt::DecorationRole:
if (isFileNode) { if (isFileNode) {
// File node // File node
Q_ASSERT(file != NULL); QTC_ASSERT(file, return result);
const QString path = m_resource_file.absolutePath(file->name); const QString path = m_resource_file.absolutePath(file->name);
if (iconFileExtension(path)) { if (iconFileExtension(path)) {
const QIcon icon(path); const QIcon icon(path);
@@ -650,7 +653,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const
case Qt::ToolTipRole: case Qt::ToolTipRole:
if (isFileNode) { if (isFileNode) {
// File node // File node
Q_ASSERT(file != NULL); QTC_ASSERT(file, return result);
QString conv_file = m_resource_file.relativePath(file->name); QString conv_file = m_resource_file.relativePath(file->name);
QString stringRes = conv_file.replace(QDir::separator(), QLatin1Char('/')); QString stringRes = conv_file.replace(QDir::separator(), QLatin1Char('/'));
const QString &alias_file = file->alias; const QString &alias_file = file->alias;
@@ -679,12 +682,12 @@ void ResourceModel::getItem(const QModelIndex &index, QString &prefix, QString &
void * const internalPointer = index.internalPointer(); void * const internalPointer = index.internalPointer();
Node * const node = reinterpret_cast<Node *>(internalPointer); Node * const node = reinterpret_cast<Node *>(internalPointer);
Prefix * const p = node->prefix(); Prefix * const p = node->prefix();
Q_ASSERT(p != NULL); QTC_ASSERT(p, return);
bool const isFileNode = (p != node); bool const isFileNode = (p != node);
if (isFileNode) { if (isFileNode) {
File *const f = node->file(); File *const f = node->file();
Q_ASSERT(f != NULL); QTC_ASSERT(f, return);
if (!f->alias.isEmpty()) if (!f->alias.isEmpty())
file = f->alias; file = f->alias;
else else

View File

@@ -36,10 +36,12 @@
#include "namespace_global.h" #include "namespace_global.h"
#include <utils/qtcassert.h>
#include <QtCore/QAbstractItemModel>
#include <QtCore/QMap>
#include <QtCore/QString> #include <QtCore/QString>
#include <QtCore/QStringList> #include <QtCore/QStringList>
#include <QtCore/QMap>
#include <QtCore/QAbstractItemModel>
#include "shared_global_p.h" #include "shared_global_p.h"
@@ -66,11 +68,11 @@ class Node
protected: protected:
Node(File *file, Prefix *prefix) : m_file(file), m_prefix(prefix) Node(File *file, Prefix *prefix) : m_file(file), m_prefix(prefix)
{ {
Q_ASSERT(m_prefix != NULL); QTC_ASSERT(m_prefix, return);
} }
public: public:
File *file() { return m_file; } File *file() { return m_file; }
Prefix * prefix() { Q_ASSERT(m_prefix != NULL); return m_prefix; } Prefix *prefix() { return m_prefix; }
private: private:
File *m_file; File *m_file;
Prefix *m_prefix; Prefix *m_prefix;

View File

@@ -32,16 +32,20 @@
***************************************************************************/ ***************************************************************************/
#include "resourceview.h" #include "resourceview.h"
#include "undocommands_p.h" #include "undocommands_p.h"
#include <QtGui/QHeaderView> #include <utils/qtcassert.h>
#include <QtGui/QMenu>
#include <QtCore/QDebug>
#include <QtGui/QAction> #include <QtGui/QAction>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication> #include <QtGui/QApplication>
#include <QtGui/QInputDialog>
#include <QtGui/QFileDialog> #include <QtGui/QFileDialog>
#include <QtCore/QtDebug> #include <QtGui/QHeaderView>
#include <QtGui/QInputDialog>
#include <QtGui/QMenu>
#include <QtGui/QMouseEvent>
#include <QtGui/QUndoStack> #include <QtGui/QUndoStack>
namespace SharedTools { namespace SharedTools {
@@ -308,14 +312,14 @@ void ResourceView::findSamePlacePostDeletionModelIndex(int &row, QModelIndex &pa
EntryBackup * ResourceView::removeEntry(const QModelIndex &index) EntryBackup * ResourceView::removeEntry(const QModelIndex &index)
{ {
Q_ASSERT(m_qrcModel != NULL); QTC_ASSERT(m_qrcModel, return 0);
return m_qrcModel->removeEntry(index); return m_qrcModel->removeEntry(index);
} }
void ResourceView::addFiles(int prefixIndex, const QStringList &fileNames, int cursorFile, void ResourceView::addFiles(int prefixIndex, const QStringList &fileNames, int cursorFile,
int &firstFile, int &lastFile) int &firstFile, int &lastFile)
{ {
Q_ASSERT(m_qrcModel != NULL); QTC_ASSERT(m_qrcModel, return);
m_qrcModel->addFiles(prefixIndex, fileNames, cursorFile, firstFile, lastFile); m_qrcModel->addFiles(prefixIndex, fileNames, cursorFile, firstFile, lastFile);
// Expand prefix node // Expand prefix node
@@ -327,11 +331,11 @@ void ResourceView::addFiles(int prefixIndex, const QStringList &fileNames, int c
void ResourceView::removeFiles(int prefixIndex, int firstFileIndex, int lastFileIndex) void ResourceView::removeFiles(int prefixIndex, int firstFileIndex, int lastFileIndex)
{ {
Q_ASSERT((prefixIndex >= 0) && (prefixIndex < m_qrcModel->rowCount(QModelIndex()))); QTC_ASSERT(prefixIndex >= 0 && prefixIndex < m_qrcModel->rowCount(QModelIndex()), return);
const QModelIndex prefixModelIndex = m_qrcModel->index(prefixIndex, 0, QModelIndex()); const QModelIndex prefixModelIndex = m_qrcModel->index(prefixIndex, 0, QModelIndex());
Q_ASSERT(prefixModelIndex != QModelIndex()); QTC_ASSERT(prefixModelIndex != QModelIndex(), return);
Q_ASSERT((firstFileIndex >= 0) && (firstFileIndex < m_qrcModel->rowCount(prefixModelIndex))); QTC_ASSERT(firstFileIndex >= 0 && firstFileIndex < m_qrcModel->rowCount(prefixModelIndex), return);
Q_ASSERT((lastFileIndex >= 0) && (lastFileIndex < m_qrcModel->rowCount(prefixModelIndex))); QTC_ASSERT(lastFileIndex >= 0 && lastFileIndex < m_qrcModel->rowCount(prefixModelIndex), return);
for (int i = lastFileIndex; i >= firstFileIndex; i--) { for (int i = lastFileIndex; i >= firstFileIndex; i--) {
const QModelIndex index = m_qrcModel->index(i, 0, prefixModelIndex); const QModelIndex index = m_qrcModel->index(i, 0, prefixModelIndex);
@@ -501,10 +505,9 @@ void ResourceView::changePrefix(const QModelIndex &index)
QString const prefixAfter = QInputDialog::getText(this, tr("Change Prefix"), tr("Input Prefix:"), QString const prefixAfter = QInputDialog::getText(this, tr("Change Prefix"), tr("Input Prefix:"),
QLineEdit::Normal, prefixBefore, &ok); QLineEdit::Normal, prefixBefore, &ok);
if (ok) { if (ok)
addUndoCommand(preindex, PrefixProperty, prefixBefore, prefixAfter); addUndoCommand(preindex, PrefixProperty, prefixBefore, prefixAfter);
} }
}
void ResourceView::changeLang(const QModelIndex &index) void ResourceView::changeLang(const QModelIndex &index)
{ {
@@ -531,10 +534,9 @@ void ResourceView::changeAlias(const QModelIndex &index)
QString const aliasAfter = QInputDialog::getText(this, tr("Change File Alias"), tr("Alias:"), QString const aliasAfter = QInputDialog::getText(this, tr("Change File Alias"), tr("Alias:"),
QLineEdit::Normal, aliasBefore, &ok); QLineEdit::Normal, aliasBefore, &ok);
if (ok) { if (ok)
addUndoCommand(index, AliasProperty, aliasBefore, aliasAfter); addUndoCommand(index, AliasProperty, aliasBefore, aliasAfter);
} }
}
QString ResourceView::currentAlias() const QString ResourceView::currentAlias() const
{ {
@@ -570,7 +572,7 @@ QString ResourceView::getCurrentValue(NodeProperty property) const
case AliasProperty: return currentAlias(); case AliasProperty: return currentAlias();
case PrefixProperty: return currentPrefix(); case PrefixProperty: return currentPrefix();
case LanguageProperty: return currentLanguage(); case LanguageProperty: return currentLanguage();
default: Q_ASSERT(false); return QString(); // Kill warning default: QTC_ASSERT(false, /**/); return QString(); // Kill warning
} }
} }
@@ -581,19 +583,20 @@ void ResourceView::changeValue(const QModelIndex &nodeIndex, NodeProperty proper
case AliasProperty: m_qrcModel->changeAlias(nodeIndex, value); return; case AliasProperty: m_qrcModel->changeAlias(nodeIndex, value); return;
case PrefixProperty: m_qrcModel->changePrefix(nodeIndex, value); return; case PrefixProperty: m_qrcModel->changePrefix(nodeIndex, value); return;
case LanguageProperty: m_qrcModel->changeLang(nodeIndex, value); return; case LanguageProperty: m_qrcModel->changeLang(nodeIndex, value); return;
default: Q_ASSERT(false); default: QTC_ASSERT(false, /**/);
} }
} }
void ResourceView::advanceMergeId() { void ResourceView::advanceMergeId()
{
m_mergeId++; m_mergeId++;
if (m_mergeId < 0) { if (m_mergeId < 0)
m_mergeId = 0; m_mergeId = 0;
} }
}
void ResourceView::addUndoCommand(const QModelIndex &nodeIndex, NodeProperty property, void ResourceView::addUndoCommand(const QModelIndex &nodeIndex, NodeProperty property,
const QString &before, const QString &after) { const QString &before, const QString &after)
{
QUndoCommand * const command = new ModifyPropertyCommand(this, nodeIndex, property, QUndoCommand * const command = new ModifyPropertyCommand(this, nodeIndex, property,
m_mergeId, before, after); m_mergeId, before, after);
m_history->push(command); m_history->push(command);

View File

@@ -92,7 +92,7 @@ bool ModifyPropertyCommand::mergeWith(const QUndoCommand * command)
{ {
const ModifyPropertyCommand * const brother const ModifyPropertyCommand * const brother
= dynamic_cast<const ModifyPropertyCommand *>(command); = dynamic_cast<const ModifyPropertyCommand *>(command);
if (command == NULL || m_property != brother->m_property) if (command == 0 || m_property != brother->m_property)
return false; return false;
// Choose older command (this) and forgot the other // Choose older command (this) and forgot the other
@@ -101,7 +101,7 @@ bool ModifyPropertyCommand::mergeWith(const QUndoCommand * command)
void ModifyPropertyCommand::undo() void ModifyPropertyCommand::undo()
{ {
Q_ASSERT(m_view != NULL); QTC_ASSERT(m_view, return);
// Save current text in m_after for redo() // Save current text in m_after for redo()
m_after = m_view->getCurrentValue(m_property); m_after = m_view->getCurrentValue(m_property);
@@ -117,12 +117,12 @@ void ModifyPropertyCommand::redo()
return; return;
// Bring back text before undo // Bring back text before undo
Q_ASSERT(m_view != NULL); QTC_ASSERT(m_view, return);
m_view->changeValue(makeIndex(), m_property, m_after); m_view->changeValue(makeIndex(), m_property, m_after);
} }
RemoveEntryCommand::RemoveEntryCommand(ResourceView *view, const QModelIndex &index) RemoveEntryCommand::RemoveEntryCommand(ResourceView *view, const QModelIndex &index)
: ModelIndexViewCommand(view), m_entry(NULL), m_isExpanded(true) : ModelIndexViewCommand(view), m_entry(0), m_isExpanded(true)
{ {
storeIndex(index); storeIndex(index);
} }
@@ -142,9 +142,9 @@ void RemoveEntryCommand::redo()
void RemoveEntryCommand::undo() void RemoveEntryCommand::undo()
{ {
if (m_entry != NULL) { if (m_entry == 0) {
m_entry->restore(); m_entry->restore();
Q_ASSERT(m_view != NULL); QTC_ASSERT(m_view != 0, return);
const QModelIndex index = makeIndex(); const QModelIndex index = makeIndex();
m_view->setExpanded(index, m_isExpanded); m_view->setExpanded(index, m_isExpanded);
m_view->setCurrentIndex(index); m_view->setCurrentIndex(index);
@@ -155,7 +155,7 @@ void RemoveEntryCommand::undo()
void RemoveEntryCommand::freeEntry() void RemoveEntryCommand::freeEntry()
{ {
delete m_entry; delete m_entry;
m_entry = NULL; m_entry = 0;
} }
AddFilesCommand::AddFilesCommand(ResourceView *view, int prefixIndex, int cursorFileIndex, AddFilesCommand::AddFilesCommand(ResourceView *view, int prefixIndex, int cursorFileIndex,

View File

@@ -86,8 +86,6 @@ QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
lockFile.open(QIODevice::ReadWrite); lockFile.open(QIODevice::ReadWrite);
} }
bool QtLocalPeer::isClient() bool QtLocalPeer::isClient()
{ {
if (lockFile.isLocked()) if (lockFile.isLocked())
@@ -105,7 +103,6 @@ bool QtLocalPeer::isClient()
return false; return false;
} }
bool QtLocalPeer::sendMessage(const QString &message, int timeout) bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{ {
if (!isClient()) if (!isClient())
@@ -139,7 +136,6 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
return res; return res;
} }
void QtLocalPeer::receiveConnection() void QtLocalPeer::receiveConnection()
{ {
QLocalSocket* socket = server->nextPendingConnection(); QLocalSocket* socket = server->nextPendingConnection();

View File

@@ -34,6 +34,8 @@
#ifndef WRAP_HELPERS_H #ifndef WRAP_HELPERS_H
#define WRAP_HELPERS_H #define WRAP_HELPERS_H
#include <utils/qtcassert.h>
#include <QtScript/QScriptEngine> #include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext> #include <QtScript/QScriptContext>
#include <QtScript/QScriptValue> #include <QtScript/QScriptValue>
@@ -87,7 +89,7 @@ template <class Wrapper, class Wrapped>
Wrapped * (Wrapper::*wrappedAccessor) () const) Wrapped * (Wrapper::*wrappedAccessor) () const)
{ {
Wrapped *wrapped = wrappedFromScriptValue(context->thisObject(), wrappedAccessor); Wrapped *wrapped = wrappedFromScriptValue(context->thisObject(), wrappedAccessor);
Q_ASSERT(wrapped); QTC_ASSERT(wrapped, return 0);
return wrapped; return wrapped;
} }
@@ -314,7 +316,7 @@ static void scriptValueToQObject(const QScriptValue &sv, SomeQObject * &p)
{ {
QObject *qObject = sv.toQObject(); QObject *qObject = sv.toQObject();
p = qobject_cast<SomeQObject*>(qObject); p = qobject_cast<SomeQObject*>(qObject);
Q_ASSERT(p); QTC_ASSERT(p, return);
} }
// Register a QObject-derived class which has Q_DECLARE_METATYPE(Ptr*) // Register a QObject-derived class which has Q_DECLARE_METATYPE(Ptr*)

View File

@@ -32,6 +32,9 @@
***************************************************************************/ ***************************************************************************/
#include "CppDocument.h" #include "CppDocument.h"
#include <utils/qtcassert.h>
#include <Control.h> #include <Control.h>
#include <TranslationUnit.h> #include <TranslationUnit.h>
#include <DiagnosticClient.h> #include <DiagnosticClient.h>
@@ -138,24 +141,14 @@ void Document::addIncludeFile(const QString &fileName)
_includedFiles.append(fileName); _includedFiles.append(fileName);
} }
QByteArray Document::definedMacros() const void Document::appendMacro(const Macro &macro)
{ {
return _definedMacros; _definedMacros.append(macro);
} }
void Document::appendMacro(const QByteArray &macroName, const QByteArray &text) void Document::addMacroUse(const Macro &macro, unsigned offset, unsigned length)
{ {
int index = macroName.indexOf('('); _macroUses.append(MacroUse(macro, offset, offset + length));
if (index == -1)
_macroNames.insert(macroName);
else
_macroNames.insert(macroName.left(index));
_definedMacros += text;
}
void Document::addMacroUse(unsigned offset, unsigned length)
{
_macroUses.append(Block(offset, offset + length));
} }
TranslationUnit *Document::translationUnit() const TranslationUnit *Document::translationUnit() const
@@ -251,11 +244,6 @@ void Document::stopSkippingBlocks(unsigned stop)
_skippedBlocks.back() = Block(start, stop); _skippedBlocks.back() = Block(start, stop);
} }
QSet<QByteArray> Document::macroNames() const
{
return _macroNames;
}
bool Document::parse(ParseMode mode) bool Document::parse(ParseMode mode)
{ {
TranslationUnit::ParseMode m = TranslationUnit::ParseTranlationUnit; TranslationUnit::ParseMode m = TranslationUnit::ParseTranlationUnit;
@@ -285,7 +273,7 @@ bool Document::parse(ParseMode mode)
void Document::check() void Document::check()
{ {
Q_ASSERT(! _globalNamespace); QTC_ASSERT(!_globalNamespace, return);
Semantic semantic(_control); Semantic semantic(_control);

View File

@@ -36,6 +36,8 @@
#include <CPlusPlusForwardDeclarations.h> #include <CPlusPlusForwardDeclarations.h>
#include "pp-macro.h"
#include <QByteArray> #include <QByteArray>
#include <QList> #include <QList>
#include <QSet> #include <QSet>
@@ -45,6 +47,8 @@
namespace CPlusPlus { namespace CPlusPlus {
class Macro;
class CPLUSPLUS_EXPORT Document class CPLUSPLUS_EXPORT Document
{ {
Document(const Document &other); Document(const Document &other);
@@ -63,12 +67,8 @@ public:
QStringList includedFiles() const; QStringList includedFiles() const;
void addIncludeFile(const QString &fileName); void addIncludeFile(const QString &fileName);
QByteArray definedMacros() const; void appendMacro(const Macro &macro);
QSet<QByteArray> macroNames() const; void addMacroUse(const Macro &macro, unsigned offset, unsigned length);
void appendMacro(const QByteArray &macroName, const QByteArray &text);
void addMacroUse(unsigned offset, unsigned length);
Control *control() const; Control *control() const;
TranslationUnit *translationUnit() const; TranslationUnit *translationUnit() const;
@@ -81,6 +81,9 @@ public:
Scope *globalSymbols() const; // ### deprecate? Scope *globalSymbols() const; // ### deprecate?
Namespace *globalNamespace() const; Namespace *globalNamespace() const;
QList<Macro> definedMacros() const
{ return _definedMacros; }
Symbol *findSymbolAt(unsigned line, unsigned column) const; Symbol *findSymbolAt(unsigned line, unsigned column) const;
void setSource(const QByteArray &source); void setSource(const QByteArray &source);
@@ -173,12 +176,30 @@ public:
inline unsigned end() const inline unsigned end() const
{ return _end; } { return _end; }
bool contains(unsigned pos) const
{ return pos >= _begin && pos < _end; }
};
class MacroUse: public Block {
Macro _macro;
public:
inline MacroUse(const Macro &macro,
unsigned begin = 0,
unsigned end = 0)
: Block(begin, end),
_macro(macro)
{ }
const Macro &macro() const
{ return _macro; }
}; };
QList<Block> skippedBlocks() const QList<Block> skippedBlocks() const
{ return _skippedBlocks; } { return _skippedBlocks; }
QList<Block> macroUses() const QList<MacroUse> macroUses() const
{ return _macroUses; } { return _macroUses; }
private: private:
@@ -191,10 +212,9 @@ private:
TranslationUnit *_translationUnit; TranslationUnit *_translationUnit;
Namespace *_globalNamespace; Namespace *_globalNamespace;
QList<DiagnosticMessage> _diagnosticMessages; QList<DiagnosticMessage> _diagnosticMessages;
QByteArray _definedMacros; QList<Macro> _definedMacros;
QSet<QByteArray> _macroNames;
QList<Block> _skippedBlocks; QList<Block> _skippedBlocks;
QList<Block> _macroUses; QList<MacroUse> _macroUses;
}; };
} // end of namespace CPlusPlus } // end of namespace CPlusPlus

View File

@@ -61,11 +61,11 @@ Icons::Icons()
{ {
} }
QIcon Icons::iconForSymbol(Symbol *symbol) const QIcon Icons::iconForSymbol(const Symbol *symbol) const
{ {
if (symbol->isFunction() || (symbol->isDeclaration() && symbol->type()->isFunction())) if (symbol->isFunction() || (symbol->isDeclaration() && symbol->type()->isFunction()))
{ {
Function *function = symbol->asFunction(); const Function *function = symbol->asFunction();
if (!function) if (!function)
function = symbol->type()->asFunction(); function = symbol->type()->asFunction();

View File

@@ -47,7 +47,7 @@ class CPLUSPLUS_EXPORT Icons
public: public:
Icons(); Icons();
QIcon iconForSymbol(Symbol *symbol) const; QIcon iconForSymbol(const Symbol *symbol) const;
QIcon keywordIcon() const; QIcon keywordIcon() const;
QIcon macroIcon() const; QIcon macroIcon() const;

View File

@@ -34,6 +34,8 @@
#include "OverviewModel.h" #include "OverviewModel.h"
#include "Overview.h" #include "Overview.h"
#include <utils/qtcassert.h>
#include <Scope.h> #include <Scope.h>
#include <Semantic.h> #include <Semantic.h>
#include <Literals.h> #include <Literals.h>
@@ -74,20 +76,20 @@ Symbol *OverviewModel::globalSymbolAt(unsigned index) const
QModelIndex OverviewModel::index(int row, int column, const QModelIndex &parent) const QModelIndex OverviewModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (! hasDocument()) { if (!parent.isValid()) {
return QModelIndex(); if (row == 0) // account for no symbol item
} else if (! parent.isValid()) { return createIndex(row, column);
Symbol *symbol = globalSymbolAt(row); Symbol *symbol = globalSymbolAt(row-1); // account for no symbol item
return createIndex(row, column, symbol); return createIndex(row, column, symbol);
} else { } else {
Symbol *parentSymbol = static_cast<Symbol *>(parent.internalPointer()); Symbol *parentSymbol = static_cast<Symbol *>(parent.internalPointer());
Q_ASSERT(parentSymbol != 0); QTC_ASSERT(parentSymbol, return QModelIndex());
ScopedSymbol *scopedSymbol = parentSymbol->asScopedSymbol(); ScopedSymbol *scopedSymbol = parentSymbol->asScopedSymbol();
Q_ASSERT(scopedSymbol != 0); QTC_ASSERT(scopedSymbol, return QModelIndex());
Scope *scope = scopedSymbol->members(); Scope *scope = scopedSymbol->members();
Q_ASSERT(scope != 0); QTC_ASSERT(scope, return QModelIndex());
return createIndex(row, 0, scope->symbolAt(row)); return createIndex(row, 0, scope->symbolAt(row));
} }
@@ -96,12 +98,20 @@ QModelIndex OverviewModel::index(int row, int column, const QModelIndex &parent)
QModelIndex OverviewModel::parent(const QModelIndex &child) const QModelIndex OverviewModel::parent(const QModelIndex &child) const
{ {
Symbol *symbol = static_cast<Symbol *>(child.internalPointer()); Symbol *symbol = static_cast<Symbol *>(child.internalPointer());
Q_ASSERT(symbol != 0); if (!symbol) // account for no symbol item
return QModelIndex();
if (Scope *scope = symbol->scope()) { if (Scope *scope = symbol->scope()) {
Symbol *parentSymbol = scope->owner(); Symbol *parentSymbol = scope->owner();
if (parentSymbol && parentSymbol->scope()) if (parentSymbol && parentSymbol->scope()) {
return createIndex(parentSymbol->index(), 0, parentSymbol); QModelIndex index;
if (parentSymbol->scope() && parentSymbol->scope()->owner()
&& parentSymbol->scope()->owner()->scope()) // the parent doesn't have a parent
index = createIndex(parentSymbol->index(), 0, parentSymbol);
else //+1 to account for no symbol item
index = createIndex(parentSymbol->index() + 1, 0, parentSymbol);
return index;
}
} }
return QModelIndex(); return QModelIndex();
@@ -111,21 +121,26 @@ int OverviewModel::rowCount(const QModelIndex &parent) const
{ {
if (hasDocument()) { if (hasDocument()) {
if (!parent.isValid()) { if (!parent.isValid()) {
return globalSymbolCount(); return globalSymbolCount()+1; // account for no symbol item
} else { } else {
if (!parent.parent().isValid() && parent.row() == 0) // account for no symbol item
return 0;
Symbol *parentSymbol = static_cast<Symbol *>(parent.internalPointer()); Symbol *parentSymbol = static_cast<Symbol *>(parent.internalPointer());
Q_ASSERT(parentSymbol != 0); QTC_ASSERT(parentSymbol, return 0);
if (ScopedSymbol *scopedSymbol = parentSymbol->asScopedSymbol()) { if (ScopedSymbol *scopedSymbol = parentSymbol->asScopedSymbol()) {
if (!scopedSymbol->isFunction()) { if (!scopedSymbol->isFunction()) {
Scope *parentScope = scopedSymbol->members(); Scope *parentScope = scopedSymbol->members();
Q_ASSERT(parentScope != 0); QTC_ASSERT(parentScope, return 0);
return parentScope->symbolCount(); return parentScope->symbolCount();
} }
} }
return 0;
} }
} }
if (!parent.isValid())
return 1; // account for no symbol item
return 0; return 0;
} }
@@ -136,6 +151,19 @@ int OverviewModel::columnCount(const QModelIndex &) const
QVariant OverviewModel::data(const QModelIndex &index, int role) const QVariant OverviewModel::data(const QModelIndex &index, int role) const
{ {
// account for no symbol item
if (!index.parent().isValid() && index.row() == 0) {
switch (role) {
case Qt::DisplayRole:
if (rowCount() > 1)
return tr("<Select Symbol>");
else
return tr("<No Symbols>");
default:
return QVariant();
} //switch
}
switch (role) { switch (role) {
case Qt::DisplayRole: { case Qt::DisplayRole: {
Symbol *symbol = static_cast<Symbol *>(index.internalPointer()); Symbol *symbol = static_cast<Symbol *>(index.internalPointer());

View File

@@ -45,8 +45,10 @@
#include <TypeVisitor.h> #include <TypeVisitor.h>
#include <NameVisitor.h> #include <NameVisitor.h>
#include <QList> #include <utils/qtcassert.h>
#include <QtDebug>
#include <QtCore/QList>
#include <QtCore/QtDebug>
using namespace CPlusPlus; using namespace CPlusPlus;
@@ -98,7 +100,7 @@ protected:
// types // types
virtual void visit(PointerToMemberType * /*ty*/) virtual void visit(PointerToMemberType * /*ty*/)
{ {
Q_ASSERT(0); QTC_ASSERT(false, /**/);
} }
virtual void visit(PointerType *ty) virtual void visit(PointerType *ty)
@@ -150,32 +152,32 @@ protected:
{ /* nothing to do*/ } { /* nothing to do*/ }
virtual void visit(Namespace *) virtual void visit(Namespace *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(Class *) virtual void visit(Class *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(Enum *) virtual void visit(Enum *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
// names // names
virtual void visit(NameId *) virtual void visit(NameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(TemplateNameId *) virtual void visit(TemplateNameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(DestructorNameId *) virtual void visit(DestructorNameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(OperatorNameId *) virtual void visit(OperatorNameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(ConversionNameId *) virtual void visit(ConversionNameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
virtual void visit(QualifiedNameId *) virtual void visit(QualifiedNameId *)
{ Q_ASSERT(0); } { QTC_ASSERT(false, /**/); }
}; };
} // end of anonymous namespace } // end of anonymous namespace

View File

@@ -48,6 +48,7 @@ TypeOfExpression::TypeOfExpression():
void TypeOfExpression::setDocuments(const QMap<QString, Document::Ptr> &documents) void TypeOfExpression::setDocuments(const QMap<QString, Document::Ptr> &documents)
{ {
m_documents = documents; m_documents = documents;
m_lookupContext = LookupContext();
} }
QList<TypeOfExpression::Result> TypeOfExpression::operator()(const QString &expression, QList<TypeOfExpression::Result> TypeOfExpression::operator()(const QString &expression,

View File

@@ -54,6 +54,9 @@ public:
/** /**
* Sets the documents used to evaluate expressions. Should be set before * Sets the documents used to evaluate expressions. Should be set before
* calling this functor. * calling this functor.
*
* Also clears the lookup context, so can be used to make sure references
* to the documents previously used are removed.
*/ */
void setDocuments(const QMap<QString, Document::Ptr> &documents); void setDocuments(const QMap<QString, Document::Ptr> &documents);

View File

@@ -21,7 +21,16 @@ HEADERS += \
TypeOfExpression.h \ TypeOfExpression.h \
TypePrettyPrinter.h \ TypePrettyPrinter.h \
ResolveExpression.h \ ResolveExpression.h \
LookupContext.h LookupContext.h \
pp-cctype.h \
pp-engine.h \
pp-fwd.h \
pp-macro-expander.h \
pp-scanner.h \
pp-client.h \
pp-environment.h \
pp-internal.h \
pp-macro.h
SOURCES += \ SOURCES += \
SimpleLexer.cpp \ SimpleLexer.cpp \
@@ -35,6 +44,9 @@ SOURCES += \
TypeOfExpression.cpp \ TypeOfExpression.cpp \
TypePrettyPrinter.cpp \ TypePrettyPrinter.cpp \
ResolveExpression.cpp \ ResolveExpression.cpp \
LookupContext.cpp LookupContext.cpp \
pp-engine.cpp \
pp-environment.cpp \
pp-macro-expander.cpp
RESOURCES += cplusplus.qrc RESOURCES += cplusplus.qrc

View File

@@ -53,22 +53,24 @@
#ifndef PP_CCTYPE_H #ifndef PP_CCTYPE_H
#define PP_CCTYPE_H #define PP_CCTYPE_H
#include <CPlusPlusForwardDeclarations.h>
#include <cctype> #include <cctype>
namespace rpp { namespace CPlusPlus {
inline bool pp_isalpha (int __ch) inline bool CPLUSPLUS_EXPORT pp_isalpha (int __ch)
{ return std::isalpha ((unsigned char) __ch) != 0; } { return std::isalpha ((unsigned char) __ch) != 0; }
inline bool pp_isalnum (int __ch) inline bool CPLUSPLUS_EXPORT pp_isalnum (int __ch)
{ return std::isalnum ((unsigned char) __ch) != 0; } { return std::isalnum ((unsigned char) __ch) != 0; }
inline bool pp_isdigit (int __ch) inline bool CPLUSPLUS_EXPORT pp_isdigit (int __ch)
{ return std::isdigit ((unsigned char) __ch) != 0; } { return std::isdigit ((unsigned char) __ch) != 0; }
inline bool pp_isspace (int __ch) inline bool CPLUSPLUS_EXPORT pp_isspace (int __ch)
{ return std::isspace ((unsigned char) __ch) != 0; } { return std::isspace ((unsigned char) __ch) != 0; }
} // namespace rpp } // namespace CPlusPlus
#endif // PP_CCTYPE_H #endif // PP_CCTYPE_H

View File

@@ -34,15 +34,17 @@
#ifndef PP_CLIENT_H #ifndef PP_CLIENT_H
#define PP_CLIENT_H #define PP_CLIENT_H
#include <CPlusPlusForwardDeclarations.h>
#include <QByteArray> #include <QByteArray>
#include <QString> #include <QString>
#include <QFile> #include <QFile>
namespace rpp { namespace CPlusPlus {
class Macro; class Macro;
class Client class CPLUSPLUS_EXPORT Client
{ {
Client(const Client &other); Client(const Client &other);
void operator=(const Client &other); void operator=(const Client &other);
@@ -60,7 +62,7 @@ public:
virtual ~Client() virtual ~Client()
{ } { }
virtual void macroAdded(const QByteArray &macroId, const QByteArray &text) = 0; virtual void macroAdded(const Macro &macro) = 0;
virtual void sourceNeeded(QString &fileName, IncludeType mode) = 0; // ### FIX the signature. virtual void sourceNeeded(QString &fileName, IncludeType mode) = 0; // ### FIX the signature.
virtual void startExpandingMacro(unsigned offset, virtual void startExpandingMacro(unsigned offset,
@@ -74,6 +76,6 @@ public:
virtual void stopSkippingBlocks(unsigned offset) = 0; virtual void stopSkippingBlocks(unsigned offset) = 0;
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_CLIENT_H #endif // PP_CLIENT_H

View File

@@ -57,7 +57,6 @@
#include <QtDebug> #include <QtDebug>
#include <algorithm> #include <algorithm>
using namespace rpp;
using namespace CPlusPlus; using namespace CPlusPlus;
namespace { namespace {
@@ -165,7 +164,15 @@ protected:
bool process_primary() bool process_primary()
{ {
if ((*_lex)->is(T_INT_LITERAL)) { if ((*_lex)->is(T_INT_LITERAL)) {
_value.set_long(tokenSpell().toLong()); int base = 10;
const QByteArray spell = tokenSpell();
if (spell.at(0) == '0') {
if (spell.size() > 1 && (spell.at(1) == 'x' || spell.at(1) == 'X'))
base = 16;
else
base = 8;
}
_value.set_long(tokenSpell().toLong(0, base));
++(*_lex); ++(*_lex);
return true; return true;
} else if (isTokenDefined()) { } else if (isTokenDefined()) {
@@ -368,7 +375,7 @@ protected:
{ {
process_xor(); process_xor();
while ((*_lex)->is(T_CARET)) { while ((*_lex)->is(T_PIPE)) {
const Token op = *(*_lex); const Token op = *(*_lex);
++(*_lex); ++(*_lex);
@@ -482,12 +489,12 @@ void pp::operator () (const QByteArray &filename,
const QByteArray &source, const QByteArray &source,
QByteArray *result) QByteArray *result)
{ {
const QByteArray previousFile = env.current_file; const QByteArray previousFile = env.currentFile;
env.current_file = filename; env.currentFile = filename;
operator () (source, result); operator () (source, result);
env.current_file = previousFile; env.currentFile = previousFile;
} }
pp::State pp::createStateFromSource(const QByteArray &source) const pp::State pp::createStateFromSource(const QByteArray &source) const
@@ -519,7 +526,7 @@ void pp::operator()(const QByteArray &source, QByteArray *result)
result->append(QByteArray::number(_dot->lineno)); result->append(QByteArray::number(_dot->lineno));
result->append(' '); result->append(' ');
result->append('"'); result->append('"');
result->append(env.current_file); result->append(env.currentFile);
result->append('"'); result->append('"');
result->append('\n'); result->append('\n');
} else { } else {
@@ -605,28 +612,29 @@ void pp::operator()(const QByteArray &source, QByteArray *result)
m->definition.constEnd(), m->definition.constEnd(),
result); result);
m->hidden = false;
if (client) if (client)
client->stopExpandingMacro(_dot->offset, *m); client->stopExpandingMacro(_dot->offset, *m);
m->hidden = false;
continue; continue;
} else { } else {
QByteArray tmp; QByteArray tmp;
m->hidden = true;
if (client) if (client)
client->startExpandingMacro(identifierToken->offset, client->startExpandingMacro(identifierToken->offset,
*m, spell); *m, spell);
m->hidden = true;
expand(m->definition.constBegin(), expand(m->definition.constBegin(),
m->definition.constEnd(), m->definition.constEnd(),
&tmp); &tmp);
m->hidden = false;
if (client) if (client)
client->stopExpandingMacro(_dot->offset, *m); client->stopExpandingMacro(_dot->offset, *m);
m->hidden = false;
m = 0; // reset the active the macro m = 0; // reset the active the macro
pushState(createStateFromSource(tmp)); pushState(createStateFromSource(tmp));
@@ -844,6 +852,8 @@ void pp::processDefine(TokenIterator firstToken, TokenIterator lastToken)
} }
Macro macro; Macro macro;
macro.fileName = env.currentFile;
macro.line = env.currentLine;
macro.name = tokenText(*tk); macro.name = tokenText(*tk);
++tk; // skip T_IDENTIFIER ++tk; // skip T_IDENTIFIER
@@ -907,16 +917,8 @@ void pp::processDefine(TokenIterator firstToken, TokenIterator lastToken)
env.bind(macro); env.bind(macro);
QByteArray macroText; if (client)
macroText.reserve(64); client->macroAdded(macro);
macroText += "#define ";
macroText += macroId;
macroText += ' ';
macroText += macro.definition;
macroText += '\n';
client->macroAdded(macroId, macroText);
} }
void pp::processIf(TokenIterator firstToken, TokenIterator lastToken) void pp::processIf(TokenIterator firstToken, TokenIterator lastToken)
@@ -1020,13 +1022,10 @@ void pp::processUndef(TokenIterator firstToken, TokenIterator lastToken)
if (tk->is(T_IDENTIFIER)) { if (tk->is(T_IDENTIFIER)) {
const QByteArray macroName = tokenText(*tk); const QByteArray macroName = tokenText(*tk);
env.remove(macroName); const Macro *macro = env.remove(macroName);
QByteArray macroText; if (client && macro)
macroText += "#undef "; client->macroAdded(*macro);
macroText += macroName;
macroText += '\n';
client->macroAdded(macroName, macroText);
} }
} }

View File

@@ -62,7 +62,7 @@ namespace CPlusPlus {
class Token; class Token;
} }
namespace rpp { namespace CPlusPlus {
struct Value struct Value
{ {
@@ -134,7 +134,7 @@ namespace rpp {
#undef PP_DEFINE_BIN_OP #undef PP_DEFINE_BIN_OP
}; };
class pp class CPLUSPLUS_EXPORT pp
{ {
Client *client; Client *client;
Environment &env; Environment &env;
@@ -226,6 +226,6 @@ namespace rpp {
bool isQtReservedWord(const QByteArray &name) const; bool isQtReservedWord(const QByteArray &name) const;
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_ENGINE_H #endif // PP_ENGINE_H

View File

@@ -52,9 +52,12 @@
#include "pp-environment.h" #include "pp-environment.h"
#include "pp.h" #include "pp.h"
#include <utils/qtcassert.h>
#include <cstring> #include <cstring>
using namespace rpp; using namespace CPlusPlus;
Environment::Environment() Environment::Environment()
: currentLine(0), : currentLine(0),
@@ -79,19 +82,21 @@ Environment::~Environment ()
} }
unsigned Environment::macroCount() const unsigned Environment::macroCount() const
{ return _macro_count + 1; } {
return _macro_count + 1;
}
Macro *Environment::macroAt(unsigned index) const Macro *Environment::macroAt(unsigned index) const
{ return _macros[index]; } {
return _macros[index];
}
Macro *Environment::bind(const Macro &__macro) Macro *Environment::bind(const Macro &__macro)
{ {
Q_ASSERT(! __macro.name.isEmpty()); QTC_ASSERT(! __macro.name.isEmpty(), return 0);
Macro *m = new Macro (__macro); Macro *m = new Macro (__macro);
m->hashcode = hash_code(m->name); m->hashcode = hash_code(m->name);
m->fileName = current_file;
m->line = currentLine;
if (++_macro_count == _allocated_macros) { if (++_macro_count == _allocated_macros) {
if (! _allocated_macros) if (! _allocated_macros)
@@ -115,12 +120,14 @@ Macro *Environment::bind(const Macro &__macro)
return m; return m;
} }
void Environment::remove (const QByteArray &name) Macro *Environment::remove(const QByteArray &name)
{ {
Macro macro; Macro macro;
macro.name = name; macro.name = name;
macro.hidden = true; macro.hidden = true;
bind(macro); macro.fileName = currentFile;
macro.line = currentLine;
return bind(macro);
} }
bool Environment::isBuiltinMacro(const QByteArray &s) const bool Environment::isBuiltinMacro(const QByteArray &s) const

View File

@@ -53,14 +53,16 @@
#ifndef PP_ENVIRONMENT_H #ifndef PP_ENVIRONMENT_H
#define PP_ENVIRONMENT_H #define PP_ENVIRONMENT_H
#include "CPlusPlusForwardDeclarations.h"
#include <QVector> #include <QVector>
#include <QByteArray> #include <QByteArray>
namespace rpp { namespace CPlusPlus {
struct Macro; class Macro;
class Environment class CPLUSPLUS_EXPORT Environment
{ {
public: public:
Environment(); Environment();
@@ -70,7 +72,7 @@ public:
Macro *macroAt(unsigned index) const; Macro *macroAt(unsigned index) const;
Macro *bind(const Macro &macro); Macro *bind(const Macro &macro);
void remove(const QByteArray &name); Macro *remove(const QByteArray &name);
Macro *resolve(const QByteArray &name) const; Macro *resolve(const QByteArray &name) const;
bool isBuiltinMacro(const QByteArray &name) const; bool isBuiltinMacro(const QByteArray &name) const;
@@ -92,7 +94,7 @@ private:
void rehash(); void rehash();
public: public:
QByteArray current_file; QByteArray currentFile;
unsigned currentLine; unsigned currentLine;
bool hide_next; bool hide_next;
@@ -104,6 +106,6 @@ private:
int _hash_count; int _hash_count;
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_ENVIRONMENT_H #endif // PP_ENVIRONMENT_H

View File

View File

@@ -55,7 +55,7 @@
#include <QByteArray> #include <QByteArray>
namespace rpp { namespace CPlusPlus {
namespace _PP_internal { namespace _PP_internal {
inline bool comment_p (const char *__first, const char *__last) inline bool comment_p (const char *__first, const char *__last)
@@ -73,6 +73,6 @@ inline bool comment_p (const char *__first, const char *__last)
} }
} // _PP_internal } // _PP_internal
} // namespace rpp } // namespace CPlusPlus
#endif // PP_INTERNAL_H #endif // PP_INTERNAL_H

View File

@@ -35,7 +35,7 @@
#include "pp-macro-expander.h" #include "pp-macro-expander.h"
#include <QDateTime> #include <QDateTime>
using namespace rpp; using namespace CPlusPlus;
MacroExpander::MacroExpander (Environment &env, pp_frame *frame) MacroExpander::MacroExpander (Environment &env, pp_frame *frame)
: env(env), frame(frame), : env(env), frame(frame),
@@ -73,7 +73,7 @@ const char *MacroExpander::operator () (const char *__first, const char *__last,
__result->append(QByteArray::number(env.currentLine)); __result->append(QByteArray::number(env.currentLine));
__result->append(' '); __result->append(' ');
__result->append('"'); __result->append('"');
__result->append(env.current_file); __result->append(env.currentFile);
__result->append('"'); __result->append('"');
__result->append('\n'); __result->append('\n');
++lines; ++lines;
@@ -218,7 +218,7 @@ const char *MacroExpander::operator () (const char *__first, const char *__last,
else if (fast_name == "__FILE__") else if (fast_name == "__FILE__")
{ {
__result->append('"'); __result->append('"');
__result->append(env.current_file); __result->append(env.currentFile);
__result->append('"'); __result->append('"');
continue; continue;
} }

View File

@@ -53,7 +53,7 @@
#ifndef PP_MACRO_EXPANDER_H #ifndef PP_MACRO_EXPANDER_H
#define PP_MACRO_EXPANDER_H #define PP_MACRO_EXPANDER_H
namespace rpp { namespace CPlusPlus {
struct pp_frame struct pp_frame
{ {
@@ -97,7 +97,7 @@ namespace rpp {
int generated_lines; int generated_lines;
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_MACRO_EXPANDER_H #endif // PP_MACRO_EXPANDER_H

View File

@@ -53,19 +53,22 @@
#ifndef PP_MACRO_H #ifndef PP_MACRO_H
#define PP_MACRO_H #define PP_MACRO_H
#include <CPlusPlusForwardDeclarations.h>
#include <QByteArray> #include <QByteArray>
#include <QVector> #include <QVector>
#include <QString>
namespace rpp { namespace CPlusPlus {
struct Macro class CPLUSPLUS_EXPORT Macro
{ {
public:
QByteArray name; QByteArray name;
QByteArray definition; QByteArray definition;
QVector<QByteArray> formals; QVector<QByteArray> formals;
QByteArray fileName; QByteArray fileName;
int line; int line;
int lines;
Macro *next; Macro *next;
unsigned hashcode; unsigned hashcode;
@@ -83,13 +86,39 @@ namespace rpp {
inline Macro(): inline Macro():
line(0), line(0),
lines(0),
next(0), next(0),
hashcode(0), hashcode(0),
state(0) state(0)
{ } { }
QString toString() const
{
QString text;
if (hidden)
text += QLatin1String("#undef ");
else
text += QLatin1String("#define ");
text += QString::fromUtf8(name.constData(), name.size());
if (function_like) {
text += QLatin1Char('(');
bool first = true;
foreach (const QByteArray formal, formals) {
if (! first)
text += QLatin1String(", ");
else
first = false;
text += QString::fromUtf8(formal.constData(), formal.size());
}
if (variadics)
text += QLatin1String("...");
text += QLatin1Char(')');
}
text += QLatin1Char(' ');
text += QString::fromUtf8(definition.constData(), definition.size());
return text;
}
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_MACRO_H #endif // PP_MACRO_H

View File

@@ -53,7 +53,7 @@
#ifndef PP_SCANNER_H #ifndef PP_SCANNER_H
#define PP_SCANNER_H #define PP_SCANNER_H
namespace rpp { namespace CPlusPlus {
struct pp_skip_blanks struct pp_skip_blanks
{ {
@@ -373,7 +373,7 @@ struct pp_skip_argument
} }
}; };
} // namespace rpp } // namespace CPlusPlus
#endif // PP_SCANNER_H #endif // PP_SCANNER_H

View File

@@ -33,6 +33,8 @@
#include "classnamevalidatinglineedit.h" #include "classnamevalidatinglineedit.h"
#include <utils/qtcassert.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QRegExp> #include <QtCore/QRegExp>
@@ -53,7 +55,7 @@ ClassNameValidatingLineEditPrivate:: ClassNameValidatingLineEditPrivate() :
m_namespaceDelimiter(QLatin1String("::")), m_namespaceDelimiter(QLatin1String("::")),
m_namespacesEnabled(false) m_namespacesEnabled(false)
{ {
Q_ASSERT(m_nameRegexp.isValid()); QTC_ASSERT(m_nameRegexp.isValid(), return);
} }
// --------------------- ClassNameValidatingLineEdit // --------------------- ClassNameValidatingLineEdit
@@ -113,7 +115,7 @@ QString ClassNameValidatingLineEdit::createClassName(const QString &name)
// Remove spaces and convert the adjacent characters to uppercase // Remove spaces and convert the adjacent characters to uppercase
QString className = name; QString className = name;
QRegExp spaceMatcher(QLatin1String(" +(\\w)"), Qt::CaseSensitive, QRegExp::RegExp2); QRegExp spaceMatcher(QLatin1String(" +(\\w)"), Qt::CaseSensitive, QRegExp::RegExp2);
Q_ASSERT(spaceMatcher.isValid()); QTC_ASSERT(spaceMatcher.isValid(), /**/);
int pos; int pos;
while ((pos = spaceMatcher.indexIn(className)) != -1) { while ((pos = spaceMatcher.indexIn(className)) != -1) {
className.replace(pos, spaceMatcher.matchedLength(), className.replace(pos, spaceMatcher.matchedLength(),

View File

@@ -32,27 +32,67 @@
***************************************************************************/ ***************************************************************************/
#include "filenamevalidatinglineedit.h" #include "filenamevalidatinglineedit.h"
#include "qtcassert.h"
#include <QtCore/QRegExp>
#include <QtCore/QDebug>
namespace Core { namespace Core {
namespace Utils { namespace Utils {
FileNameValidatingLineEdit::FileNameValidatingLineEdit(QWidget *parent) : // Naming a file like a device name will break on Windows, even if it is
BaseValidatingLineEdit(parent) // "com1.txt". Since we are cross-platform, we generally disallow such file
// names.
static const QRegExp &windowsDeviceNoSubDirPattern()
{ {
static const QRegExp rc(QLatin1String("CON|AUX|PRN|COM1|COM2|LPT1|LPT2|NUL"),
Qt::CaseInsensitive);
QTC_ASSERT(rc.isValid(), return rc);
return rc;
}
static const QRegExp &windowsDeviceSubDirPattern()
{
static const QRegExp rc(QLatin1String(".*[/\\\\]CON|.*[/\\\\]AUX|.*[/\\\\]PRN|.*[/\\\\]COM1|.*[/\\\\]COM2|.*[/\\\\]LPT1|.*[/\\\\]LPT2|.*[/\\\\]NUL"),
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. */ /* Validate a file base name, check for forbidden characters/strings. */
static const char *notAllowedChars = "/?:&\\*\"|#%<> "; #ifdef Q_OS_WIN
# define SLASHES "/\\"
#else
# define SLASHES "/"
#endif
static const char *notAllowedCharsSubDir = "?:&*\"|#%<> ";
static const char *notAllowedCharsNoSubDir = "?:&*\"|#%<> "SLASHES;
static const char *notAllowedSubStrings[] = {".."}; static const char *notAllowedSubStrings[] = {".."};
// Naming a file like a device name will break on Windows, even if it is bool FileNameValidatingLineEdit::validateFileName(const QString &name,
// "com1.txt". Since we are cross-platform, we generally disallow such file bool allowDirectories,
// names. QString *errorMessage /* = 0*/)
static const char *notAllowedStrings[] = {"CON", "AUX", "PRN", "COM1", "COM2", "LPT1", "LPT2" };
bool FileNameValidatingLineEdit::validateFileName(const QString &name, QString *errorMessage /* = 0*/)
{ {
if (name.isEmpty()) { if (name.isEmpty()) {
if (errorMessage) if (errorMessage)
@@ -60,6 +100,7 @@ bool FileNameValidatingLineEdit::validateFileName(const QString &name, QString *
return false; return false;
} }
// Characters // Characters
const char *notAllowedChars = allowDirectories ? notAllowedCharsSubDir : notAllowedCharsNoSubDir;
for (const char *c = notAllowedChars; *c; c++) for (const char *c = notAllowedChars; *c; c++)
if (name.contains(QLatin1Char(*c))) { if (name.contains(QLatin1Char(*c))) {
if (errorMessage) if (errorMessage)
@@ -76,22 +117,22 @@ bool FileNameValidatingLineEdit::validateFileName(const QString &name, QString *
return false; return false;
} }
} }
// Strings // Windows devices
const int notAllowedStringCount = sizeof(notAllowedStrings)/sizeof(const char *); bool matchesWinDevice = windowsDeviceNoSubDirPattern().exactMatch(name);
for (int s = 0; s < notAllowedStringCount; s++) { if (!matchesWinDevice && allowDirectories)
const QLatin1String notAllowedString(notAllowedStrings[s]); matchesWinDevice = windowsDeviceSubDirPattern().exactMatch(name);
if (name == notAllowedString) { if (matchesWinDevice) {
if (errorMessage) if (errorMessage)
*errorMessage = tr("The name must not be '%1'.").arg(QString(notAllowedString)); *errorMessage = tr("The name must not match that of a MS Windows device. (%1).").
arg(windowsDeviceNoSubDirPattern().pattern().replace(QLatin1Char('|'), QLatin1Char(',')));
return false; return false;
} }
}
return true; return true;
} }
bool FileNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const bool FileNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{ {
return validateFileName(value, errorMessage); return validateFileName(value, m_allowDirectories, errorMessage);
} }
} // namespace Utils } // namespace Utils

View File

@@ -43,14 +43,23 @@ class QWORKBENCH_UTILS_EXPORT FileNameValidatingLineEdit : public BaseValidating
{ {
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(FileNameValidatingLineEdit) Q_DISABLE_COPY(FileNameValidatingLineEdit)
Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories)
public: public:
explicit FileNameValidatingLineEdit(QWidget *parent = 0); explicit FileNameValidatingLineEdit(QWidget *parent = 0);
static bool validateFileName(const QString &name, QString *errorMessage /* = 0*/); static bool validateFileName(const QString &name,
bool allowDirectories = false,
QString *errorMessage = 0);
bool allowDirectories() const;
void setAllowDirectories(bool v);
protected: protected:
virtual bool validate(const QString &value, QString *errorMessage) const; virtual bool validate(const QString &value, QString *errorMessage) const;
private:
bool m_allowDirectories;
void *m_unused;
}; };
} // namespace Utils } // namespace Utils

View File

@@ -123,7 +123,7 @@ void FileWizardPage::slotActivated()
bool FileWizardPage::validateBaseName(const QString &name, QString *errorMessage /* = 0*/) bool FileWizardPage::validateBaseName(const QString &name, QString *errorMessage /* = 0*/)
{ {
return FileNameValidatingLineEdit::validateFileName(name, errorMessage); return FileNameValidatingLineEdit::validateFileName(name, false, errorMessage);
} }
} // namespace Utils } // namespace Utils

View File

@@ -346,6 +346,21 @@ void NewClassWidget::setFormExtension(const QString &e)
m_d->m_formExtension = fixSuffix(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);
}
}
void NewClassWidget::slotValidChanged() void NewClassWidget::slotValidChanged()
{ {
const bool newValid = isValid(); const bool newValid = isValid();

View File

@@ -73,6 +73,7 @@ class QWORKBENCH_UTILS_EXPORT NewClassWidget : public QWidget
Q_PROPERTY(QString formExtension READ formExtension WRITE setFormExtension 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 formInputCheckable READ formInputCheckable WRITE setFormInputCheckable DESIGNABLE true)
Q_PROPERTY(bool formInputChecked READ formInputChecked WRITE setFormInputChecked DESIGNABLE true) Q_PROPERTY(bool formInputChecked READ formInputChecked WRITE setFormInputChecked DESIGNABLE true)
Q_PROPERTY(bool allowDirectories READ allowDirectories WRITE setAllowDirectories)
// Utility "USER" property for wizards containing file names. // Utility "USER" property for wizards containing file names.
Q_PROPERTY(QStringList files READ files DESIGNABLE false USER true) Q_PROPERTY(QStringList files READ files DESIGNABLE false USER true)
public: public:
@@ -97,7 +98,7 @@ public:
QString sourceExtension() const; QString sourceExtension() const;
QString headerExtension() const; QString headerExtension() const;
QString formExtension() const; QString formExtension() const;
bool allowDirectories() const;
bool isValid(QString *error = 0) const; bool isValid(QString *error = 0) const;
@@ -125,6 +126,7 @@ public slots:
void setSourceExtension(const QString &e); void setSourceExtension(const QString &e);
void setHeaderExtension(const QString &e); void setHeaderExtension(const QString &e);
void setFormExtension(const QString &e); void setFormExtension(const QString &e);
void setAllowDirectories(bool v);
/* Suggest a class name from the base class by stripping the leading 'Q' /* Suggest a class name from the base class by stripping the leading 'Q'
* character. This will happen automagically if the base class combo * character. This will happen automagically if the base class combo

View File

@@ -32,56 +32,74 @@
***************************************************************************/ ***************************************************************************/
#include "pathchooser.h" #include "pathchooser.h"
#include "basevalidatinglineedit.h" #include "basevalidatinglineedit.h"
#include "qtcassert.h"
#include <QtGui/QLineEdit>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QFileDialog>
#include <QtGui/QDesktopServices>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>
#include <QtGui/QDesktopServices>
#include <QtGui/QFileDialog>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QToolButton>
namespace Core { namespace Core {
namespace Utils { namespace Utils {
#ifdef Q_OS_OSX
/*static*/ const char * const PathChooser::browseButtonLabel = "Choose...";
#else
/*static*/ const char * const PathChooser::browseButtonLabel = "Browse...";
#endif
// ------------------ PathValidatingLineEdit // ------------------ PathValidatingLineEdit
class PathValidatingLineEdit : public BaseValidatingLineEdit { class PathValidatingLineEdit : public BaseValidatingLineEdit
{
public: public:
explicit PathValidatingLineEdit(QWidget *parent = 0); explicit PathValidatingLineEdit(PathChooser *chooser, QWidget *parent = 0);
protected: protected:
virtual bool validate(const QString &value, QString *errorMessage) const; virtual bool validate(const QString &value, QString *errorMessage) const;
private:
PathChooser *m_chooser;
}; };
PathValidatingLineEdit::PathValidatingLineEdit(QWidget *parent) : PathValidatingLineEdit::PathValidatingLineEdit(PathChooser *chooser, QWidget *parent) :
BaseValidatingLineEdit(parent) BaseValidatingLineEdit(parent),
m_chooser(chooser)
{ {
QTC_ASSERT(chooser, return);
} }
bool PathValidatingLineEdit::validate(const QString &value, QString *errorMessage) const bool PathValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{ {
return PathChooser::validatePath(value, errorMessage); return m_chooser->validatePath(value, errorMessage);
} }
// ------------------ PathChooserPrivate // ------------------ PathChooserPrivate
struct PathChooserPrivate { struct PathChooserPrivate
PathChooserPrivate(); {
PathChooserPrivate(PathChooser *chooser);
PathValidatingLineEdit *m_lineEdit; PathValidatingLineEdit *m_lineEdit;
PathChooser::Kind m_acceptingKind;
QString m_dialogTitleOverride;
}; };
PathChooserPrivate::PathChooserPrivate() : PathChooserPrivate::PathChooserPrivate(PathChooser *chooser) :
m_lineEdit(new PathValidatingLineEdit) m_lineEdit(new PathValidatingLineEdit(chooser)),
m_acceptingKind(PathChooser::Directory)
{ {
} }
PathChooser::PathChooser(QWidget *parent) : PathChooser::PathChooser(QWidget *parent) :
QWidget(parent), QWidget(parent),
m_d(new PathChooserPrivate) m_d(new PathChooserPrivate(this))
{ {
QHBoxLayout *hLayout = new QHBoxLayout; QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->setContentsMargins(0, 0, 0, 0); hLayout->setContentsMargins(0, 0, 0, 0);
@@ -90,11 +108,12 @@ PathChooser::PathChooser(QWidget *parent) :
connect(m_d->m_lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(changed())); connect(m_d->m_lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(changed()));
connect(m_d->m_lineEdit, SIGNAL(validChanged()), this, SIGNAL(validChanged())); connect(m_d->m_lineEdit, SIGNAL(validChanged()), this, SIGNAL(validChanged()));
m_d->m_lineEdit->setMinimumWidth(300); m_d->m_lineEdit->setMinimumWidth(260);
hLayout->addWidget(m_d->m_lineEdit); hLayout->addWidget(m_d->m_lineEdit);
hLayout->setSizeConstraint(QLayout::SetMinimumSize);
QToolButton *browseButton = new QToolButton; QToolButton *browseButton = new QToolButton;
browseButton->setText(tr("...")); browseButton->setText(tr(browseButtonLabel));
connect(browseButton, SIGNAL(clicked()), this, SLOT(slotBrowse())); connect(browseButton, SIGNAL(clicked()), this, SLOT(slotBrowse()));
hLayout->addWidget(browseButton); hLayout->addWidget(browseButton);
@@ -123,8 +142,28 @@ void PathChooser::slotBrowse()
QString predefined = path(); QString predefined = path();
if (!predefined.isEmpty() && !QFileInfo(predefined).isDir()) if (!predefined.isEmpty() && !QFileInfo(predefined).isDir())
predefined.clear(); predefined.clear();
// Prompt for a directory, delete trailing slashes unless it is "/", only
QString newPath = QFileDialog::getExistingDirectory(this, tr("Choose a path"), predefined); // Prompt for a file/dir
QString dialogTitle;
QString newPath;
switch (m_d->m_acceptingKind) {
case PathChooser::Directory:
newPath = QFileDialog::getExistingDirectory(this,
makeDialogTitle(tr("Choose a directory")), predefined);
break;
case PathChooser::File: // fall through
case PathChooser::Command:
newPath = QFileDialog::getOpenFileName(this,
makeDialogTitle(tr("Choose a file")), predefined);
break;
default:
;
}
// TODO make cross-platform
// Delete trailing slashes unless it is "/", only
if (!newPath.isEmpty()) { if (!newPath.isEmpty()) {
if (newPath.size() > 1 && newPath.endsWith(QDir::separator())) if (newPath.size() > 1 && newPath.endsWith(QDir::separator()))
newPath.truncate(newPath.size() - 1); newPath.truncate(newPath.size() - 1);
@@ -149,21 +188,55 @@ bool PathChooser::validatePath(const QString &path, QString *errorMessage)
*errorMessage = tr("The path must not be empty."); *errorMessage = tr("The path must not be empty.");
return false; return false;
} }
// Must be a directory?
const QFileInfo fi(path);
if (fi.isDir())
return true; // Happy!
const QFileInfo fi(path);
const bool isDir = fi.isDir();
// Check if existing
switch (m_d->m_acceptingKind) {
case PathChooser::Directory: // fall through
case PathChooser::File:
if (!fi.exists()) { if (!fi.exists()) {
if (errorMessage) if (errorMessage)
*errorMessage = tr("The path '%1' does not exist.").arg(path); *errorMessage = tr("The path '%1' does not exist.").arg(path);
return false; return false;
} }
// Must be something weird break;
case PathChooser::Command: // fall through
default:
;
}
// Check expected kind
switch (m_d->m_acceptingKind) {
case PathChooser::Directory:
if (!isDir) {
if (errorMessage) if (errorMessage)
*errorMessage = tr("The path '%1' is not a directory.").arg(path); *errorMessage = tr("The path '%1' is not a directory.").arg(path);
return false; return false;
} }
break;
case PathChooser::File:
if (isDir) {
if (errorMessage)
*errorMessage = tr("The path '%1' is not a file.").arg(path);
return false;
}
break;
case PathChooser::Command:
// TODO do proper command validation
// i.e. search $PATH for a matching file
break;
default:
;
}
return true;
}
QString PathChooser::label() QString PathChooser::label()
{ {
@@ -182,5 +255,23 @@ QString PathChooser::homePath()
#endif #endif
} }
void PathChooser::setExpectedKind(Kind expected)
{
m_d->m_acceptingKind = expected;
}
void PathChooser::setPromptDialogTitle(const QString &title)
{
m_d->m_dialogTitleOverride = title;
}
QString PathChooser::makeDialogTitle(const QString &title)
{
if (m_d->m_dialogTitleOverride.isNull())
return title;
else
return m_d->m_dialogTitleOverride;
}
} // namespace Utils } // namespace Utils
} // namespace Core } // namespace Core

View File

@@ -30,6 +30,7 @@
** version 1.2, included in the file GPL_EXCEPTION.txt in this package. ** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
** **
***************************************************************************/ ***************************************************************************/
#ifndef PATHCHOOSER_H #ifndef PATHCHOOSER_H
#define PATHCHOOSER_H #define PATHCHOOSER_H
@@ -53,9 +54,23 @@ class QWORKBENCH_UTILS_EXPORT PathChooser : public QWidget
Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true) Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true)
public: public:
static const char * const browseButtonLabel;
explicit PathChooser(QWidget *parent = 0); explicit PathChooser(QWidget *parent = 0);
virtual ~PathChooser(); virtual ~PathChooser();
enum Kind {
Directory,
File,
Command,
// ,Any
};
// Default is <Directory>
void setExpectedKind(Kind expected);
void setPromptDialogTitle(const QString &title);
bool isValid() const; bool isValid() const;
QString errorMessage() const; QString errorMessage() const;
@@ -64,11 +79,15 @@ public:
// Returns the suggested label title when used in a form layout // Returns the suggested label title when used in a form layout
static QString label(); static QString label();
static bool validatePath(const QString &path, QString *errorMessage = 0); bool validatePath(const QString &path, QString *errorMessage = 0);
// Return the home directory, which needs some fixing under Windows. // Return the home directory, which needs some fixing under Windows.
static QString homePath(); static QString homePath();
private:
// Returns overridden title or the one from <title>
QString makeDialogTitle(const QString &title);
signals: signals:
void validChanged(); void validChanged();
void changed(); void changed();

View File

@@ -45,7 +45,7 @@ ProjectNameValidatingLineEdit::ProjectNameValidatingLineEdit(QWidget *parent)
bool ProjectNameValidatingLineEdit::validateProjectName(const QString &name, QString *errorMessage /* = 0*/) bool ProjectNameValidatingLineEdit::validateProjectName(const QString &name, QString *errorMessage /* = 0*/)
{ {
// Validation is file name + checking for dots // Validation is file name + checking for dots
if (!FileNameValidatingLineEdit::validateFileName(name, errorMessage)) if (!FileNameValidatingLineEdit::validateFileName(name, false, errorMessage))
return false; return false;
// We don't want dots in the directory name for some legacy Windows // We don't want dots in the directory name for some legacy Windows

View File

@@ -31,16 +31,16 @@
** **
***************************************************************************/ ***************************************************************************/
#ifndef DEBUGGER_QWB_ASSERT_H #ifndef QTC_ASSERT_H
#define DEBUGGER_QWB_ASSERT_H #define QTC_ASSERT_H
#ifdef Q_OS_UNIX #include <QtCore/QDebug>
#define QWB_ASSERT(cond, action) \
// we do not use the 'do {...} while (0)' idiom here to be able to use
// 'break' and 'continue' as 'actions'.
#define QTC_ASSERT(cond, action) \
if(cond){}else{qDebug()<<"ASSERTION"<<#cond<<"FAILED"<<__FILE__<<__LINE__;action;} if(cond){}else{qDebug()<<"ASSERTION"<<#cond<<"FAILED"<<__FILE__<<__LINE__;action;}
#else
#define QWB_ASSERT(cond, action) \
if(cond){}else{qDebug()<<"ASSERTION"<<#cond<<"FAILED";action;}
#endif
#endif // DEBUGGER_QWB_ASSERT_H #endif // QTC_ASSERT_H

View File

@@ -46,7 +46,8 @@ namespace Utils {
// QActionPushButton: A push button tied to an action // QActionPushButton: A push button tied to an action
// (similar to a QToolButton) // (similar to a QToolButton)
class QActionPushButton : public QPushButton { class QActionPushButton : public QPushButton
{
Q_OBJECT Q_OBJECT
public: public:
explicit QActionPushButton(QAction *a); explicit QActionPushButton(QAction *a);

View File

@@ -32,6 +32,7 @@
***************************************************************************/ ***************************************************************************/
#include "bookmarkmanager.h" #include "bookmarkmanager.h"
#include "bookmark.h" #include "bookmark.h"
#include "bookmarksplugin.h" #include "bookmarksplugin.h"
#include "bookmarks_global.h" #include "bookmarks_global.h"
@@ -41,12 +42,14 @@
#include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <texteditor/basetexteditor.h> #include <texteditor/basetexteditor.h>
#include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtGui/QAction> #include <QtGui/QAction>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtGui/QPainter>
#include <QtGui/QContextMenuEvent> #include <QtGui/QContextMenuEvent>
#include <QtGui/QPainter>
Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*) Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*)
@@ -272,7 +275,7 @@ void BookmarkView::removeAll()
void BookmarkView::setModel(QAbstractItemModel *model) void BookmarkView::setModel(QAbstractItemModel *model)
{ {
BookmarkManager *manager = qobject_cast<BookmarkManager *>(model); BookmarkManager *manager = qobject_cast<BookmarkManager *>(model);
Q_ASSERT(manager); QTC_ASSERT(manager, return);
QListView::setModel(model); QListView::setModel(model);
setSelectionModel(manager->selectionModel()); setSelectionModel(manager->selectionModel());
setSelectionMode(QAbstractItemView::SingleSelection); setSelectionMode(QAbstractItemView::SingleSelection);
@@ -396,11 +399,16 @@ void BookmarkManager::toggleBookmark()
if (!editor) if (!editor)
return; return;
const QFileInfo fi(editor->file()->fileName()); toggleBookmark(editor->file()->fileName(), editor->currentLine());
const int editorLine = editor->currentLine(); }
void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber)
{
const QFileInfo fi(fileName);
const int editorLine = lineNumber;
// Remove any existing bookmark on this line // Remove any existing bookmark on this line
if (Bookmark *mark = findBookmark(fi.path(), fi.fileName(), editorLine)) { if (Bookmark *mark = findBookmark(fi.path(), fi.fileName(), lineNumber)) {
// TODO check if the bookmark is really on the same markable Interface // TODO check if the bookmark is really on the same markable Interface
removeBookmark(mark); removeBookmark(mark);
return; return;

View File

@@ -34,15 +34,15 @@
#ifndef BOOKMARKMANAGER_H #ifndef BOOKMARKMANAGER_H
#define BOOKMARKMANAGER_H #define BOOKMARKMANAGER_H
#include <QtCore/QAbstractItemModel>
#include <QtGui/QListView>
#include <QtCore/QList>
#include <QtGui/QPixmap>
#include <QtGui/QStyledItemDelegate>
#include <coreplugin/icontext.h> #include <coreplugin/icontext.h>
#include <coreplugin/inavigationwidgetfactory.h> #include <coreplugin/inavigationwidgetfactory.h>
#include <QtCore/QAbstractItemModel>
#include <QtCore/QList>
#include <QtGui/QListView>
#include <QtGui/QPixmap>
#include <QtGui/QStyledItemDelegate>
namespace ProjectExplorer { namespace ProjectExplorer {
class SessionManager; class SessionManager;
} }
@@ -89,10 +89,16 @@ public:
// this QItemSelectionModel is shared by all views // this QItemSelectionModel is shared by all views
QItemSelectionModel *selectionModel() const; QItemSelectionModel *selectionModel() const;
enum Roles {Filename = Qt::UserRole, LineNumber = Qt::UserRole + 1, Directory = Qt::UserRole + 2, LineText = Qt::UserRole + 3}; enum Roles {
Filename = Qt::UserRole,
LineNumber = Qt::UserRole + 1,
Directory = Qt::UserRole + 2,
LineText = Qt::UserRole + 3
};
public slots: public slots:
void toggleBookmark(); void toggleBookmark();
void toggleBookmark(const QString &fileName, int lineNumber);
void nextInDocument(); void nextInDocument();
void prevInDocument(); void prevInDocument();
void next(); void next();
@@ -108,6 +114,7 @@ private slots:
void updateActionStatus(); void updateActionStatus();
void gotoBookmark(Bookmark *bookmark); void gotoBookmark(Bookmark *bookmark);
void loadBookmarks(); void loadBookmarks();
private: private:
TextEditor::ITextEditor *currentTextEditor() const; TextEditor::ITextEditor *currentTextEditor() const;
ProjectExplorer::SessionManager* sessionManager() const; ProjectExplorer::SessionManager* sessionManager() const;

View File

@@ -36,17 +36,22 @@
#include "bookmarks_global.h" #include "bookmarks_global.h"
#include <texteditor/texteditorconstants.h> #include <texteditor/texteditorconstants.h>
#include <texteditor/itexteditor.h>
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/coreconstants.h> #include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanagerinterface.h> #include <coreplugin/actionmanager/actionmanagerinterface.h>
#include <QtCore/qplugin.h> #include <QtCore/qplugin.h>
#include <QtCore/QDebug>
#include <QtGui/QMenu> #include <QtGui/QMenu>
#include <QDebug>
using namespace Bookmarks::Constants; using namespace Bookmarks::Constants;
using namespace Bookmarks::Internal; using namespace Bookmarks::Internal;
using namespace TextEditor;
BookmarksPlugin *BookmarksPlugin::m_instance = 0; BookmarksPlugin *BookmarksPlugin::m_instance = 0;
@@ -159,6 +164,19 @@ bool BookmarksPlugin::initialize(const QStringList & /*arguments*/, QString *)
updateActions(m_bookmarkManager->state()); updateActions(m_bookmarkManager->state());
addAutoReleasedObject(new BookmarkViewFactory(m_bookmarkManager)); addAutoReleasedObject(new BookmarkViewFactory(m_bookmarkManager));
m_bookmarkMarginAction = new QAction(this);
m_bookmarkMarginAction->setText("Toggle Bookmark");
//m_bookmarkAction->setIcon(QIcon(":/gdbdebugger/images/breakpoint.svg"));
connect(m_bookmarkMarginAction, SIGNAL(triggered()),
this, SLOT(bookmarkMarginActionTriggered()));
// EditorManager
QObject *editorManager = m_core->editorManager();
connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(editorAboutToClose(Core::IEditor*)));
connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(editorOpened(Core::IEditor*)));
return true; return true;
} }
@@ -169,7 +187,6 @@ BookmarksPlugin::~BookmarksPlugin()
void BookmarksPlugin::updateActions(int state) void BookmarksPlugin::updateActions(int state)
{ {
const bool hasbm = state >= BookmarkManager::HasBookMarks; const bool hasbm = state >= BookmarkManager::HasBookMarks;
const bool hasdocbm = state == BookmarkManager::HasBookmarksInDocument; const bool hasdocbm = state == BookmarkManager::HasBookmarksInDocument;
@@ -182,4 +199,32 @@ void BookmarksPlugin::updateActions(int state)
m_moveDownAction->setEnabled(hasbm); m_moveDownAction->setEnabled(hasbm);
} }
void BookmarksPlugin::editorOpened(Core::IEditor *editor)
{
connect(editor, SIGNAL(markContextMenuRequested(TextEditor::ITextEditor*,int,QMenu*)),
this, SLOT(requestContextMenu(TextEditor::ITextEditor*,int,QMenu*)));
}
void BookmarksPlugin::editorAboutToClose(Core::IEditor *editor)
{
disconnect(editor, SIGNAL(markContextMenuRequested(TextEditor::ITextEditor*,int,QMenu*)),
this, SLOT(requestContextMenu(TextEditor::ITextEditor*,int,QMenu*)));
}
void BookmarksPlugin::requestContextMenu(TextEditor::ITextEditor *editor,
int lineNumber, QMenu *menu)
{
m_bookmarkMarginActionLineNumber = lineNumber;
m_bookmarkMarginActionFileName = editor->file()->fileName();
menu->addAction(m_bookmarkMarginAction);
}
void BookmarksPlugin::bookmarkMarginActionTriggered()
{
m_bookmarkManager->toggleBookmark(
m_bookmarkMarginActionFileName,
m_bookmarkMarginActionLineNumber
);
}
Q_EXPORT_PLUGIN(BookmarksPlugin) Q_EXPORT_PLUGIN(BookmarksPlugin)

View File

@@ -31,18 +31,26 @@
** **
***************************************************************************/ ***************************************************************************/
#ifndef BOOKMARKS_H #ifndef BOOKMARKSPLUGIN_H
#define BOOKMARKS_H #define BOOKMARKSPLUGIN_H
#include <extensionsystem/iplugin.h>
#include <QtCore/QObject> #include <QtCore/QObject>
#include <QtCore/QMultiMap> #include <QtCore/QMultiMap>
#include <extensionsystem/iplugin.h> QT_BEGIN_NAMESPACE
class QAction;
QT_FORWARD_DECLARE_CLASS(QAction) class QMenu;
QT_END_NAMESPACE
namespace Core { namespace Core {
class ICore; class ICore;
class IEditor;
}
namespace TextEditor {
class ITextEditor;
} }
namespace Bookmarks { namespace Bookmarks {
@@ -67,6 +75,13 @@ public:
public slots: public slots:
void updateActions(int stateMask); void updateActions(int stateMask);
private slots:
void editorOpened(Core::IEditor *editor);
void editorAboutToClose(Core::IEditor *editor);
void requestContextMenu(TextEditor::ITextEditor *editor,
int lineNumber, QMenu *menu);
void bookmarkMarginActionTriggered();
private: private:
static BookmarksPlugin *m_instance; static BookmarksPlugin *m_instance;
BookmarkManager *m_bookmarkManager; BookmarkManager *m_bookmarkManager;
@@ -79,6 +94,10 @@ private:
QAction *m_docNextAction; QAction *m_docNextAction;
QAction *m_moveUpAction; QAction *m_moveUpAction;
QAction *m_moveDownAction; QAction *m_moveDownAction;
QAction *m_bookmarkMarginAction;
int m_bookmarkMarginActionLineNumber;
QString m_bookmarkMarginActionFileName;
}; };
} // namespace Internal } // namespace Internal

View File

@@ -32,13 +32,20 @@
***************************************************************************/ ***************************************************************************/
#include "cmakeproject.h" #include "cmakeproject.h"
#include "cmakeprojectconstants.h" #include "cmakeprojectconstants.h"
#include "cmakeprojectnodes.h" #include "cmakeprojectnodes.h"
#include "cmakerunconfiguration.h"
#include "cmakestep.h"
#include "makestep.h"
#include <extensionsystem/pluginmanager.h> #include <extensionsystem/pluginmanager.h>
#include <cpptools/cppmodelmanagerinterface.h> #include <cpptools/cppmodelmanagerinterface.h>
#include <utils/qtcassert.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QProcess>
using namespace CMakeProjectManager; using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal; using namespace CMakeProjectManager::Internal;
@@ -46,27 +53,40 @@ using namespace CMakeProjectManager::Internal;
CMakeProject::CMakeProject(CMakeManager *manager, const QString &fileName) CMakeProject::CMakeProject(CMakeManager *manager, const QString &fileName)
: m_manager(manager), m_fileName(fileName), m_rootNode(new CMakeProjectNode(m_fileName)) : m_manager(manager), m_fileName(fileName), m_rootNode(new CMakeProjectNode(m_fileName))
{ {
//TODO
m_file = new CMakeFile(this, fileName); m_file = new CMakeFile(this, fileName);
QDir dir = QFileInfo(m_fileName).absoluteDir(); QDir dir = QFileInfo(m_fileName).absoluteDir();
QString cbpFile = findCbpFile(dir); QString cbpFile = findCbpFile(dir);
if (cbpFile.isEmpty()) if (cbpFile.isEmpty())
cbpFile = createCbpFile(dir); cbpFile = createCbpFile(dir);
//TODO move this parsing to a seperate method, which is also called if the CMakeList.txt is updated
CMakeCbpParser cbpparser; CMakeCbpParser cbpparser;
if (cbpparser.parseCbpFile(cbpFile)) { if (cbpparser.parseCbpFile(cbpFile)) {
// TODO do a intelligent updating of the tree
buildTree(m_rootNode, cbpparser.fileList()); buildTree(m_rootNode, cbpparser.fileList());
foreach (ProjectExplorer::FileNode *fn, cbpparser.fileList()) foreach (ProjectExplorer::FileNode *fn, cbpparser.fileList())
m_files.append(fn->path()); m_files.append(fn->path());
m_files.sort(); m_files.sort();
m_targets = cbpparser.targets();
qDebug()<<"Printing targets";
foreach(CMakeTarget ct, m_targets) {
qDebug()<<ct.title<<" with executable:"<<ct.executable;
qDebug()<<"WD:"<<ct.workingDirectory;
qDebug()<<ct.makeCommand<<ct.makeCleanCommand;
qDebug()<<"";
}
CppTools::CppModelManagerInterface *modelmanager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>(); CppTools::CppModelManagerInterface *modelmanager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
if (modelmanager) { if (modelmanager) {
CppTools::CppModelManagerInterface::ProjectInfo *pinfo = modelmanager->projectInfo(this); CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
pinfo->includePaths = cbpparser.includeFiles(); pinfo.includePaths = cbpparser.includeFiles();
// TODO we only want C++ files, not all other stuff that might be in the project // TODO we only want C++ files, not all other stuff that might be in the project
pinfo->sourceFiles = m_files; pinfo.sourceFiles = m_files;
// TODO defines // TODO defines
// TODO gcc preprocessor files
modelmanager->updateProjectInfo(pinfo);
} }
} else { } else {
// TODO report error // TODO report error
@@ -84,25 +104,27 @@ QString CMakeProject::findCbpFile(const QDir &directory)
// TODO the cbp file is named like the project() command in the CMakeList.txt file // TODO the cbp file is named like the project() command in the CMakeList.txt file
// so this method below could find the wrong cbp file, if the user changes the project() // so this method below could find the wrong cbp file, if the user changes the project()
// name // name
foreach(const QString &cbpFile , directory.entryList()) foreach (const QString &cbpFile , directory.entryList()) {
{ if (cbpFile.endsWith(".cbp"))
if (cbpFile.endsWith(".cbp")) {
return directory.path() + "/" + cbpFile; return directory.path() + "/" + cbpFile;
} }
}
return QString::null; return QString::null;
} }
QString CMakeProject::createCbpFile(const QDir &directory)
QString CMakeProject::createCbpFile(const QDir &)
{ {
// TODO create a cbp file. // We create a cbp file, only if we didn't find a cbp file in the base directory
// Issue: Where to create it? We want to do that in the build directory // Yet that can still override cbp files in subdirectories
// but at this stage we don't know the build directory yet // And we are creating tons of files in the source directories
// So create it in a temp directory? // All of that is not really nice.
// Issue: We want to reuse whatever CMakeCache.txt that is alread there, which // The mid term plan is to move away from the CodeBlocks Generator and use our own
// would indicate, creating it in the build directory // QtCreator generator, which actually can be very similar to the CodeBlock Generator
// Or we could use a temp directory and use -C builddirectory
// TODO we need to pass on the same paremeters as the cmakestep
QProcess cmake;
cmake.setWorkingDirectory(directory.absolutePath());
cmake.start("cmake", QStringList() << "-GCodeBlocks - Unix Makefiles");
return QString::null; return QString::null;
} }
@@ -187,7 +209,7 @@ QString CMakeProject::buildDirectory(const QString &buildConfiguration) const
{ {
Q_UNUSED(buildConfiguration) Q_UNUSED(buildConfiguration)
//TODO //TODO
return ""; return QFileInfo(m_fileName).absolutePath();
} }
ProjectExplorer::BuildStepConfigWidget *CMakeProject::createConfigWidget() ProjectExplorer::BuildStepConfigWidget *CMakeProject::createConfigWidget()
@@ -224,13 +246,37 @@ QStringList CMakeProject::files(FilesMode fileMode) const
void CMakeProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer) void CMakeProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{ {
// TODO // TODO
Q_UNUSED(writer) Project::saveSettingsImpl(writer);
} }
void CMakeProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader) void CMakeProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader)
{ {
// TODO // TODO
Q_UNUSED(reader) Project::restoreSettingsImpl(reader);
if (buildConfigurations().isEmpty()) {
// No build configuration, adding those
CMakeStep *cmakeStep = new CMakeStep(this);
MakeStep *makeStep = new MakeStep(this);
insertBuildStep(0, cmakeStep);
insertBuildStep(1, makeStep);
// Create build configurations of m_targets
qDebug()<<"Create build configurations of m_targets";
foreach(const CMakeTarget &ct, m_targets) {
addBuildConfiguration(ct.title);
makeStep->setValue(ct.title, "makeCommand", ct.makeCommand);
makeStep->setValue(ct.title, "makeCleanCommand", ct.makeCleanCommand);
QSharedPointer<ProjectExplorer::RunConfiguration> rc(new CMakeRunConfiguration(this, ct.executable, ct.workingDirectory));
// TODO set build configuration to build before it can be run
addRunConfiguration(rc);
setActiveRunConfiguration(rc); // TODO what exactly shall be the active run configuration?
}
setActiveBuildConfiguration("all");
}
// Restoring is fine
} }
@@ -375,12 +421,86 @@ void CMakeCbpParser::parseBuild()
void CMakeCbpParser::parseTarget() void CMakeCbpParser::parseTarget()
{ {
m_targetType = false;
m_target.clear();
if (attributes().hasAttribute("title"))
m_target.title = attributes().value("title").toString();
while (!atEnd()) {
readNext();
if (isEndElement()) {
if (m_targetType || m_target.title == "all") {
m_targets.append(m_target);
}
return;
} else if (name() == "Compiler") {
parseCompiler();
} else if (name() == "Option") {
parseTargetOption();
} else if (isStartElement()) {
parseUnknownElement();
}
}
}
void CMakeCbpParser::parseTargetOption()
{
if (attributes().hasAttribute("output"))
m_target.executable = attributes().value("output").toString();
else if (attributes().hasAttribute("type") && attributes().value("type") == "1")
m_targetType = true;
else if (attributes().hasAttribute("working_dir"))
m_target.workingDirectory = attributes().value("working_dir").toString();
while (!atEnd()) {
readNext();
if (isEndElement()) {
return;
} else if (name() == "MakeCommand") {
parseMakeCommand();
} else if (isStartElement()) {
parseUnknownElement();
}
}
}
void CMakeCbpParser::parseMakeCommand()
{
while (!atEnd()) {
readNext();
if (isEndElement()) {
return;
} else if (name() == "Build") {
parseTargetBuild();
} else if (name() == "Clean") {
parseTargetClean();
} else if (isStartElement()) {
parseUnknownElement();
}
}
}
void CMakeCbpParser::parseTargetBuild()
{
if (attributes().hasAttribute("command"))
m_target.makeCommand = attributes().value("command").toString();
while (!atEnd()) {
readNext();
if (isEndElement()) {
return;
} else if (isStartElement()) {
parseUnknownElement();
}
}
}
void CMakeCbpParser::parseTargetClean()
{
if (attributes().hasAttribute("command"))
m_target.makeCleanCommand = attributes().value("command").toString();
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement()) {
return; return;
} else if (name() == "Compiler") {
parseCompiler();
} else if (isStartElement()) { } else if (isStartElement()) {
parseUnknownElement(); parseUnknownElement();
} }
@@ -432,7 +552,7 @@ void CMakeCbpParser::parseUnit()
void CMakeCbpParser::parseUnknownElement() void CMakeCbpParser::parseUnknownElement()
{ {
Q_ASSERT(isStartElement()); QTC_ASSERT(isStartElement(), /**/);
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
@@ -454,3 +574,18 @@ QStringList CMakeCbpParser::includeFiles()
{ {
return m_includeFiles; return m_includeFiles;
} }
QList<CMakeTarget> CMakeCbpParser::targets()
{
return m_targets;
}
void CMakeTarget::clear()
{
executable = QString::null;
makeCommand = QString::null;
makeCleanCommand = QString::null;
workingDirectory = QString::null;
title = QString::null;
}

View File

@@ -49,6 +49,16 @@ namespace Internal{
class CMakeFile; class CMakeFile;
struct CMakeTarget
{
QString title;
QString executable;
QString workingDirectory;
QString makeCommand;
QString makeCleanCommand;
void clear();
};
class CMakeProject : public ProjectExplorer::Project class CMakeProject : public ProjectExplorer::Project
{ {
Q_OBJECT Q_OBJECT
@@ -105,6 +115,7 @@ private:
// TODO probably need a CMake specific node structure // TODO probably need a CMake specific node structure
CMakeProjectNode* m_rootNode; CMakeProjectNode* m_rootNode;
QStringList m_files; QStringList m_files;
QList<CMakeTarget> m_targets;
protected: protected:
virtual void saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer); virtual void saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer);
@@ -118,11 +129,16 @@ public:
bool parseCbpFile(const QString &fileName); bool parseCbpFile(const QString &fileName);
QList<ProjectExplorer::FileNode *> fileList(); QList<ProjectExplorer::FileNode *> fileList();
QStringList includeFiles(); QStringList includeFiles();
QList<CMakeTarget> targets();
private: private:
void parseCodeBlocks_project_file(); void parseCodeBlocks_project_file();
void parseProject(); void parseProject();
void parseBuild(); void parseBuild();
void parseTarget(); void parseTarget();
void parseTargetOption();
void parseMakeCommand();
void parseTargetBuild();
void parseTargetClean();
void parseCompiler(); void parseCompiler();
void parseAdd(); void parseAdd();
void parseUnit(); void parseUnit();
@@ -130,6 +146,10 @@ private:
QList<ProjectExplorer::FileNode *> m_fileList; QList<ProjectExplorer::FileNode *> m_fileList;
QStringList m_includeFiles; QStringList m_includeFiles;
CMakeTarget m_target;
bool m_targetType;
QList<CMakeTarget> m_targets;
}; };
class CMakeFile : public Core::IFile class CMakeFile : public Core::IFile

View File

@@ -41,6 +41,7 @@ const char * const PROJECTCONTEXT = "CMakeProject.ProjectContext";
const char * const CMAKEMIMETYPE = "text/x-cmake"; // TOOD check that this is correct const char * const CMAKEMIMETYPE = "text/x-cmake"; // TOOD check that this is correct
const char * const CMAKESTEP = "CMakeProjectManager.CMakeStep"; const char * const CMAKESTEP = "CMakeProjectManager.CMakeStep";
const char * const MAKESTEP = "CMakeProjectManager.MakeStep"; const char * const MAKESTEP = "CMakeProjectManager.MakeStep";
const char * const CMAKERUNCONFIGURATION = "CMakeProjectManager.CMakeRunConfiguration";
} // namespace Constants } // namespace Constants

View File

@@ -8,11 +8,13 @@ HEADERS = cmakeproject.h \
cmakeprojectconstants.h \ cmakeprojectconstants.h \
cmakeprojectnodes.h \ cmakeprojectnodes.h \
cmakestep.h \ cmakestep.h \
makestep.h makestep.h \
cmakerunconfiguration.h
SOURCES = cmakeproject.cpp \ SOURCES = cmakeproject.cpp \
cmakeprojectplugin.cpp \ cmakeprojectplugin.cpp \
cmakeprojectmanager.cpp \ cmakeprojectmanager.cpp \
cmakeprojectnodes.cpp \ cmakeprojectnodes.cpp \
cmakestep.cpp \ cmakestep.cpp \
makestep.cpp makestep.cpp \
cmakerunconfiguration.cpp
RESOURCES += cmakeproject.qrc RESOURCES += cmakeproject.qrc

View File

@@ -33,6 +33,7 @@
#include "cmakeprojectplugin.h" #include "cmakeprojectplugin.h"
#include "cmakeprojectmanager.h" #include "cmakeprojectmanager.h"
#include "cmakerunconfiguration.h"
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h> #include <coreplugin/mimedatabase.h>
@@ -57,6 +58,7 @@ bool CMakeProjectPlugin::initialize(const QStringList & /*arguments*/, QString *
if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":cmakeproject/CMakeProject.mimetypes.xml"), errorMessage)) if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":cmakeproject/CMakeProject.mimetypes.xml"), errorMessage))
return false; return false;
addAutoReleasedObject(new CMakeManager()); addAutoReleasedObject(new CMakeManager());
addAutoReleasedObject(new CMakeRunConfigurationFactory());
return true; return true;
} }

View File

@@ -0,0 +1,157 @@
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "cmakerunconfiguration.h"
#include "cmakeproject.h"
#include "cmakeprojectconstants.h"
#include <projectexplorer/environment.h>
#include <utils/qtcassert.h>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
CMakeRunConfiguration::CMakeRunConfiguration(CMakeProject *pro, const QString &target, const QString &workingDirectory)
: ProjectExplorer::ApplicationRunConfiguration(pro), m_target(target), m_workingDirectory(workingDirectory)
{
setName(target);
}
CMakeRunConfiguration::~CMakeRunConfiguration()
{
}
QString CMakeRunConfiguration::type() const
{
return Constants::CMAKERUNCONFIGURATION;
}
QString CMakeRunConfiguration::executable() const
{
return m_target;
}
ProjectExplorer::ApplicationRunConfiguration::RunMode CMakeRunConfiguration::runMode() const
{
return ProjectExplorer::ApplicationRunConfiguration::Gui;
}
QString CMakeRunConfiguration::workingDirectory() const
{
return m_workingDirectory;
}
QStringList CMakeRunConfiguration::commandLineArguments() const
{
// TODO
return QStringList();
}
ProjectExplorer::Environment CMakeRunConfiguration::environment() const
{
// TODO
return ProjectExplorer::Environment::systemEnvironment();
}
void CMakeRunConfiguration::save(ProjectExplorer::PersistentSettingsWriter &writer) const
{
ProjectExplorer::ApplicationRunConfiguration::save(writer);
}
void CMakeRunConfiguration::restore(const ProjectExplorer::PersistentSettingsReader &reader)
{
ProjectExplorer::ApplicationRunConfiguration::restore(reader);
}
QWidget *CMakeRunConfiguration::configurationWidget()
{
//TODO
return new QWidget();
}
// Factory
CMakeRunConfigurationFactory::CMakeRunConfigurationFactory()
{
}
CMakeRunConfigurationFactory::~CMakeRunConfigurationFactory()
{
}
// used to recreate the runConfigurations when restoring settings
bool CMakeRunConfigurationFactory::canCreate(const QString &type) const
{
if (type.startsWith(Constants::CMAKERUNCONFIGURATION))
return true;
return false;
}
// used to show the list of possible additons to a project, returns a list of types
QStringList CMakeRunConfigurationFactory::canCreate(ProjectExplorer::Project *project) const
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
if (!pro)
return QStringList();
// TODO gather all targets and return them here
return QStringList();
}
// used to translate the types to names to display to the user
QString CMakeRunConfigurationFactory::nameForType(const QString &type) const
{
QTC_ASSERT(type.startsWith(Constants::CMAKERUNCONFIGURATION), /**/);
if (type == Constants::CMAKERUNCONFIGURATION)
return "CMake"; // Doesn't happen
else
return type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
}
QSharedPointer<ProjectExplorer::RunConfiguration> CMakeRunConfigurationFactory::create(ProjectExplorer::Project *project, const QString &type)
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
QTC_ASSERT(pro, /**/);
if (type == Constants::CMAKERUNCONFIGURATION) {
// Restoring, filename will be added by restoreSettings
QSharedPointer<ProjectExplorer::RunConfiguration> rc(new CMakeRunConfiguration(pro, QString::null, QString::null));
return rc;
} else {
// Adding new
QString file = type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
QSharedPointer<ProjectExplorer::RunConfiguration> rc(new CMakeRunConfiguration(pro, file, QString::null));
return rc;
}
}

View File

@@ -0,0 +1,93 @@
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#ifndef CMAKERUNCONFIGURATION_H
#define CMAKERUNCONFIGURATION_H
#include <projectexplorer/applicationrunconfiguration.h>
#include <projectexplorer/environment.h>
#include <projectexplorer/persistentsettings.h>
namespace CMakeProjectManager {
namespace Internal {
class CMakeProject;
class CMakeRunConfiguration : public ProjectExplorer::ApplicationRunConfiguration
{
public:
CMakeRunConfiguration(CMakeProject *pro, const QString &target, const QString &workingDirectory);
virtual ~CMakeRunConfiguration();
virtual QString type() const;
virtual QString executable() const;
virtual RunMode runMode() const;
virtual QString workingDirectory() const;
virtual QStringList commandLineArguments() const;
virtual ProjectExplorer::Environment environment() const;
virtual QWidget *configurationWidget();
virtual void save(ProjectExplorer::PersistentSettingsWriter &writer) const;
virtual void restore(const ProjectExplorer::PersistentSettingsReader &reader);
private:
QString m_target;
QString m_workingDirectory;
};
/* The run configuration factory is used for restoring run configurations from
* settings. And used to create new runconfigurations in the "Run Settings" Dialog.
* For the first case bool canCreate(const QString &type) and
* QSharedPointer<RunConfiguration> create(Project *project, QString type) are used.
* For the second type the functions QStringList canCreate(Project *pro) and
* QString nameForType(const QString&) are used to generate a list of creatable
* RunConfigurations, and create(..) is used to create it.
*/
class CMakeRunConfigurationFactory : public QObject
{
Q_OBJECT;
public:
CMakeRunConfigurationFactory();
virtual ~CMakeRunConfigurationFactory();
// used to recreate the runConfigurations when restoring settings
virtual bool canCreate(const QString &type) const;
// used to show the list of possible additons to a project, returns a list of types
virtual QStringList canCreate(ProjectExplorer::Project *pro) const;
// used to translate the types to names to display to the user
virtual QString nameForType(const QString &type) const;
virtual QSharedPointer<ProjectExplorer::RunConfiguration> create(ProjectExplorer::Project *project, const QString &type);
};
}
}
#endif // CMAKERUNCONFIGURATION_H

View File

@@ -32,8 +32,11 @@
***************************************************************************/ ***************************************************************************/
#include "cmakestep.h" #include "cmakestep.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h" #include "cmakeproject.h"
#include "cmakeprojectconstants.h"
#include <utils/qtcassert.h>
using namespace CMakeProjectManager; using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal; using namespace CMakeProjectManager::Internal;
@@ -41,12 +44,10 @@ using namespace CMakeProjectManager::Internal;
CMakeStep::CMakeStep(CMakeProject *pro) CMakeStep::CMakeStep(CMakeProject *pro)
: AbstractProcessStep(pro), m_pro(pro) : AbstractProcessStep(pro), m_pro(pro)
{ {
} }
CMakeStep::~CMakeStep() CMakeStep::~CMakeStep()
{ {
} }
bool CMakeStep::init(const QString &buildConfiguration) bool CMakeStep::init(const QString &buildConfiguration)
@@ -54,13 +55,18 @@ bool CMakeStep::init(const QString &buildConfiguration)
setEnabled(buildConfiguration, true); setEnabled(buildConfiguration, true);
setWorkingDirectory(buildConfiguration, m_pro->buildDirectory(buildConfiguration)); setWorkingDirectory(buildConfiguration, m_pro->buildDirectory(buildConfiguration));
setCommand(buildConfiguration, "cmake"); // TODO give full path here? setCommand(buildConfiguration, "cmake"); // TODO give full path here?
setArguments(buildConfiguration, QStringList()); // TODO setArguments(buildConfiguration, QStringList() << "-GUnix Makefiles"); // TODO
setEnvironment(buildConfiguration, m_pro->environment(buildConfiguration)); setEnvironment(buildConfiguration, m_pro->environment(buildConfiguration));
return AbstractProcessStep::init(buildConfiguration); return AbstractProcessStep::init(buildConfiguration);
} }
void CMakeStep::run(QFutureInterface<bool> &fi) void CMakeStep::run(QFutureInterface<bool> &fi)
{ {
// TODO we want to only run cmake if the command line arguments or
// the CmakeLists.txt has actually changed
// And we want all of them to share the SAME command line arguments
// Shadow building ruins this, hmm, hmm
//
AbstractProcessStep::run(fi); AbstractProcessStep::run(fi);
} }
@@ -109,9 +115,9 @@ bool CMakeBuildStepFactory::canCreate(const QString &name) const
ProjectExplorer::BuildStep *CMakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const ProjectExplorer::BuildStep *CMakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const
{ {
Q_ASSERT(name == Constants::CMAKESTEP); QTC_ASSERT(name == Constants::CMAKESTEP, /**/);
CMakeProject *pro = qobject_cast<CMakeProject *>(project); CMakeProject *pro = qobject_cast<CMakeProject *>(project);
Q_ASSERT(pro); QTC_ASSERT(pro, /**/);
return new CMakeStep(pro); return new CMakeStep(pro);
} }

View File

@@ -35,18 +35,18 @@
#include "cmakeprojectconstants.h" #include "cmakeprojectconstants.h"
#include "cmakeproject.h" #include "cmakeproject.h"
#include <utils/qtcassert.h>
using namespace CMakeProjectManager; using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal; using namespace CMakeProjectManager::Internal;
MakeStep::MakeStep(CMakeProject *pro) MakeStep::MakeStep(CMakeProject *pro)
: AbstractProcessStep(pro), m_pro(pro) : AbstractProcessStep(pro), m_pro(pro)
{ {
} }
MakeStep::~MakeStep() MakeStep::~MakeStep()
{ {
} }
bool MakeStep::init(const QString &buildConfiguration) bool MakeStep::init(const QString &buildConfiguration)
@@ -109,9 +109,9 @@ bool MakeBuildStepFactory::canCreate(const QString &name) const
ProjectExplorer::BuildStep *MakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const ProjectExplorer::BuildStep *MakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const
{ {
Q_ASSERT(name == Constants::MAKESTEP); QTC_ASSERT(name == Constants::MAKESTEP, return 0);
CMakeProject *pro = qobject_cast<CMakeProject *>(project); CMakeProject *pro = qobject_cast<CMakeProject *>(project);
Q_ASSERT(pro); QTC_ASSERT(pro, return 0);
return new MakeStep(pro); return new MakeStep(pro);
} }

View File

@@ -47,6 +47,7 @@ SettingsDialog::SettingsDialog(QWidget *parent, const QString &initialCategory,
setupUi(this); setupUi(this);
buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);
splitter->setCollapsible(1, false);
pageTree->header()->setVisible(false); pageTree->header()->setVisible(false);
connect(pageTree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), connect(pageTree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
@@ -59,7 +60,7 @@ SettingsDialog::SettingsDialog(QWidget *parent, const QString &initialCategory,
int index = 0; int index = 0;
foreach (IOptionsPage *page, pages) { foreach (IOptionsPage *page, pages) {
QTreeWidgetItem *item = new QTreeWidgetItem(); QTreeWidgetItem *item = new QTreeWidgetItem;
item->setText(0, page->name()); item->setText(0, page->name());
item->setData(0, Qt::UserRole, index); item->setData(0, Qt::UserRole, index);

View File

@@ -32,15 +32,18 @@
***************************************************************************/ ***************************************************************************/
#include "editorgroup.h" #include "editorgroup.h"
#include "editormanager.h" #include "editormanager.h"
#include <coreplugin/coreconstants.h> #include <coreplugin/coreconstants.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir> #include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtGui/QPainter> #include <QtGui/QPainter>
#include <QtGui/QStyle> #include <QtGui/QStyle>
#include <QtGui/QStyleOption> #include <QtGui/QStyleOption>
#include <QtCore/QtDebug>
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
#include <QtGui/QMacStyle> #include <QtGui/QMacStyle>
#endif #endif
@@ -107,7 +110,7 @@ QVariant EditorModel::data(const QModelIndex &index, int role) const
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
IEditor *editor = m_editors.at(index.row()); IEditor *editor = m_editors.at(index.row());
Q_ASSERT(editor); QTC_ASSERT(editor, return QVariant());
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
return editor->file()->isModified() return editor->file()->isModified()
@@ -145,6 +148,7 @@ EditorGroupContext::EditorGroupContext(EditorGroup *editorGroup)
m_editorGroup(editorGroup) m_editorGroup(editorGroup)
{ {
} }
QList<int> EditorGroupContext::context() const QList<int> EditorGroupContext::context() const
{ {
return m_context; return m_context;

View File

@@ -53,21 +53,23 @@
#include <coreplugin/baseview.h> #include <coreplugin/baseview.h>
#include <coreplugin/imode.h> #include <coreplugin/imode.h>
#include <QtCore/QFileInfo> #include <utils/qtcassert.h>
#include <QtCore/QSettings>
#include <QtCore/QMap>
#include <QtCore/QSet>
#include <QtCore/QProcess>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QMap>
#include <QtCore/QProcess>
#include <QtCore/QSet>
#include <QtCore/QSettings>
#include <QtGui/QAction> #include <QtGui/QAction>
#include <QtGui/QLayout>
#include <QtGui/QApplication> #include <QtGui/QApplication>
#include <QtGui/QSplitter>
#include <QtGui/QFileDialog> #include <QtGui/QFileDialog>
#include <QtGui/QLayout>
#include <QtGui/QMenu> #include <QtGui/QMenu>
#include <QtGui/QMessageBox> #include <QtGui/QMessageBox>
#include <QtGui/QPushButton> #include <QtGui/QPushButton>
#include <QtGui/QSplitter>
using namespace Core; using namespace Core;
using namespace Core::Internal; using namespace Core::Internal;
@@ -961,12 +963,11 @@ bool EditorManager::hasEditor(const QString &fileName) const
void EditorManager::restoreEditorState(IEditor *editor) void EditorManager::restoreEditorState(IEditor *editor)
{ {
Q_ASSERT(editor); QTC_ASSERT(editor, return);
QString fileName = editor->file()->fileName(); QString fileName = editor->file()->fileName();
if (m_d->m_editorStates.contains(fileName)) { if (m_d->m_editorStates.contains(fileName))
editor->restoreState(m_d->m_editorStates.value(fileName).toByteArray()); editor->restoreState(m_d->m_editorStates.value(fileName).toByteArray());
} }
}
bool EditorManager::saveEditor(IEditor *editor) bool EditorManager::saveEditor(IEditor *editor)
{ {

View File

@@ -32,16 +32,19 @@
***************************************************************************/ ***************************************************************************/
#include "editorsplitter.h" #include "editorsplitter.h"
#include "editormanager.h" #include "editormanager.h"
#include "minisplitter.h"
#include "openeditorswindow.h" #include "openeditorswindow.h"
#include "stackededitorgroup.h" #include "stackededitorgroup.h"
#include "minisplitter.h"
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h> #include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanagerinterface.h> #include <coreplugin/actionmanager/actionmanagerinterface.h>
#include <utils/qtcassert.h>
#include <QtGui/QHBoxLayout> #include <QtGui/QHBoxLayout>
#include <QtGui/QMenu> #include <QtGui/QMenu>
#include <QtGui/QApplication> #include <QtGui/QApplication>
@@ -160,7 +163,7 @@ void EditorSplitter::registerActions()
void EditorSplitter::updateActions() void EditorSplitter::updateActions()
{ {
const bool hasMultipleGroups = (qobject_cast<QSplitter*>(m_root) != 0); const bool hasMultipleGroups = (qobject_cast<QSplitter*>(m_root) != 0);
Q_ASSERT(currentGroup()); QTC_ASSERT(currentGroup(), return);
const bool hasEditors = (currentGroup()->editorCount() != 0); const bool hasEditors = (currentGroup()->editorCount() != 0);
m_unsplitAction->setEnabled(hasMultipleGroups); m_unsplitAction->setEnabled(hasMultipleGroups);
#if 0 #if 0
@@ -245,7 +248,7 @@ void EditorSplitter::collectGroups(QWidget *widget, QList<EditorGroup*> &groups)
return; return;
} }
QSplitter *splitter = qobject_cast<QSplitter*>(widget); QSplitter *splitter = qobject_cast<QSplitter*>(widget);
Q_ASSERT(splitter); QTC_ASSERT(splitter, return);
collectGroups(splitter->widget(LEFT), groups); collectGroups(splitter->widget(LEFT), groups);
collectGroups(splitter->widget(RIGHT), groups); collectGroups(splitter->widget(RIGHT), groups);
} }
@@ -330,7 +333,7 @@ void EditorSplitter::unsplit()
if (!curGroup) if (!curGroup)
return; return;
QWidget *curGroupWidget = curGroup->widget(); QWidget *curGroupWidget = curGroup->widget();
Q_ASSERT(curGroupWidget); QTC_ASSERT(curGroupWidget, return);
IEditor *selectedEditor = curGroup->currentEditor(); IEditor *selectedEditor = curGroup->currentEditor();
QSplitter *parentSplitter = qobject_cast<QSplitter*>(curGroupWidget->parentWidget()); QSplitter *parentSplitter = qobject_cast<QSplitter*>(curGroupWidget->parentWidget());
@@ -454,25 +457,25 @@ EditorGroup *EditorSplitter::groupFarthestOnSide(QWidget *node, Side side) const
void EditorSplitter::selectNextGroup() void EditorSplitter::selectNextGroup()
{ {
EditorGroup *curGroup = currentGroup(); EditorGroup *curGroup = currentGroup();
Q_ASSERT(curGroup); QTC_ASSERT(curGroup, return);
setCurrentGroup(nextGroup(curGroup, RIGHT)); setCurrentGroup(nextGroup(curGroup, RIGHT));
} }
void EditorSplitter::selectPreviousGroup() void EditorSplitter::selectPreviousGroup()
{ {
EditorGroup *curGroup = currentGroup(); EditorGroup *curGroup = currentGroup();
Q_ASSERT(curGroup); QTC_ASSERT(curGroup, return);
setCurrentGroup(nextGroup(curGroup, LEFT)); setCurrentGroup(nextGroup(curGroup, LEFT));
} }
EditorGroup *EditorSplitter::nextGroup(EditorGroup *curGroup, Side side) const EditorGroup *EditorSplitter::nextGroup(EditorGroup *curGroup, Side side) const
{ {
Q_ASSERT(curGroup); QTC_ASSERT(curGroup, return 0);
QWidget *curWidget = curGroup->widget(); QWidget *curWidget = curGroup->widget();
QWidget *parent = curWidget->parentWidget(); QWidget *parent = curWidget->parentWidget();
while (curWidget != m_root) { while (curWidget != m_root) {
QSplitter *splitter = qobject_cast<QSplitter *>(parent); QSplitter *splitter = qobject_cast<QSplitter *>(parent);
Q_ASSERT(splitter); QTC_ASSERT(splitter, return 0);
if (splitter->widget(side) != curWidget) { if (splitter->widget(side) != curWidget) {
curWidget = splitter->widget(side); curWidget = splitter->widget(side);
break; break;
@@ -486,7 +489,7 @@ EditorGroup *EditorSplitter::nextGroup(EditorGroup *curGroup, Side side) const
void EditorSplitter::moveDocToAdjacentGroup(Side side) void EditorSplitter::moveDocToAdjacentGroup(Side side)
{ {
EditorGroup *curGroup = currentGroup(); EditorGroup *curGroup = currentGroup();
Q_ASSERT(curGroup); QTC_ASSERT(curGroup, return);
IEditor *editor = curGroup->currentEditor(); IEditor *editor = curGroup->currentEditor();
if (!editor) if (!editor)
return; return;
@@ -510,7 +513,7 @@ QWidget *EditorSplitter::recreateGroupTree(QWidget *node)
QSplitter *splitter = qobject_cast<QSplitter *>(node); QSplitter *splitter = qobject_cast<QSplitter *>(node);
if (!splitter) { if (!splitter) {
EditorGroup *group = qobject_cast<EditorGroup *>(node); EditorGroup *group = qobject_cast<EditorGroup *>(node);
Q_ASSERT(group); QTC_ASSERT(group, return 0);
IEditor *currentEditor = group->currentEditor(); IEditor *currentEditor = group->currentEditor();
EditorGroup *newGroup = createGroup(); EditorGroup *newGroup = createGroup();
bool block = newGroup->widget()->blockSignals(true); bool block = newGroup->widget()->blockSignals(true);
@@ -588,7 +591,7 @@ void EditorSplitter::saveState(QWidget *current, QDataStream &stream) const
saveState(splitter->widget(1), stream); saveState(splitter->widget(1), stream);
} else { } else {
EditorGroup *group = qobject_cast<EditorGroup *>(current); EditorGroup *group = qobject_cast<EditorGroup *>(current);
Q_ASSERT(group); QTC_ASSERT(group, /**/);
if (group != currentGroup()) if (group != currentGroup())
type = 1; type = 1;
else else
@@ -639,7 +642,7 @@ void EditorSplitter::fillPathGroupMap(QWidget *current, QString currentPath,
map.insert(currentPath, group); map.insert(currentPath, group);
} else { } else {
QSplitter *splitter = qobject_cast<QSplitter *>(current); QSplitter *splitter = qobject_cast<QSplitter *>(current);
Q_ASSERT(splitter); QTC_ASSERT(splitter, return);
fillPathGroupMap(splitter->widget(0), currentPath+"0", map); fillPathGroupMap(splitter->widget(0), currentPath+"0", map);
fillPathGroupMap(splitter->widget(1), currentPath+"1", map); fillPathGroupMap(splitter->widget(1), currentPath+"1", map);
} }

View File

@@ -39,6 +39,7 @@
#include <coreplugin/coreconstants.h> #include <coreplugin/coreconstants.h>
#include <coreplugin/filemanager.h> #include <coreplugin/filemanager.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QTimer> #include <QtCore/QTimer>
#include <QtGui/QMenu> #include <QtGui/QMenu>
@@ -197,7 +198,7 @@ void OpenEditorsWidget::selectEditor(QTreeWidgetItem *item)
void OpenEditorsWidget::updateEditor() void OpenEditorsWidget::updateEditor()
{ {
IEditor *editor = qobject_cast<IEditor *>(sender()); IEditor *editor = qobject_cast<IEditor *>(sender());
Q_ASSERT(editor); QTC_ASSERT(editor, return);
int num = m_ui.editorList->topLevelItemCount(); int num = m_ui.editorList->topLevelItemCount();
for (int i = 0; i < num; ++i) { for (int i = 0; i < num; ++i) {
QTreeWidgetItem *item = m_ui.editorList->topLevelItem(i); QTreeWidgetItem *item = m_ui.editorList->topLevelItem(i);

View File

@@ -35,21 +35,24 @@
#include "editormanager.h" #include "editormanager.h"
#include "coreimpl.h" #include "coreimpl.h"
#include <QtCore/QFileInfo> #include <utils/qtcassert.h>
#include <QtCore/QDebug>
#include <QtCore/QDir> #include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QMimeData> #include <QtCore/QMimeData>
#include <QtGui/QApplication>
#include <QtGui/QComboBox> #include <QtGui/QComboBox>
#include <QtGui/QHBoxLayout> #include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter> #include <QtGui/QPainter>
#include <QtGui/QStackedWidget>
#include <QtGui/QStyle> #include <QtGui/QStyle>
#include <QtGui/QStyleOption> #include <QtGui/QStyleOption>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtGui/QToolBar> #include <QtGui/QToolBar>
#include <QtGui/QToolButton> #include <QtGui/QToolButton>
#include <QtGui/QLabel>
#include <QtGui/QStackedWidget>
#include <QtDebug>
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
#include <qmacstyle_mac.h> #include <qmacstyle_mac.h>
#endif #endif
@@ -240,7 +243,7 @@ void StackedEditorGroup::sendCloseRequest()
void StackedEditorGroup::removeEditor(IEditor *editor) void StackedEditorGroup::removeEditor(IEditor *editor)
{ {
Q_ASSERT(editor); QTC_ASSERT(editor, return);
EditorGroup::removeEditor(editor); EditorGroup::removeEditor(editor);
const int index = m_container->indexOf(editor->widget()); const int index = m_container->indexOf(editor->widget());
if (index != -1) { if (index != -1) {
@@ -280,7 +283,7 @@ void StackedEditorGroup::setCurrentEditor(IEditor *editor)
return; return;
m_toplevel->setVisible(true); m_toplevel->setVisible(true);
const int idx = m_container->indexOf(editor->widget()); const int idx = m_container->indexOf(editor->widget());
Q_ASSERT(idx >= 0); QTC_ASSERT(idx >= 0, return);
if (m_container->currentIndex() != idx) { if (m_container->currentIndex() != idx) {
m_container->setCurrentIndex(idx); m_container->setCurrentIndex(idx);
@@ -298,10 +301,11 @@ void StackedEditorGroup::setCurrentEditor(IEditor *editor)
} }
} }
void StackedEditorGroup::updateEditorStatus(IEditor *editor) { void StackedEditorGroup::updateEditorStatus(IEditor *editor)
{
if (!editor) if (!editor)
editor = qobject_cast<IEditor *>(sender()); editor = qobject_cast<IEditor *>(sender());
Q_ASSERT(editor); QTC_ASSERT(editor, return);
static const QIcon lockedIcon(QLatin1String(":/qworkbench/images/locked.png")); static const QIcon lockedIcon(QLatin1String(":/qworkbench/images/locked.png"));
static const QIcon unlockedIcon(QLatin1String(":/qworkbench/images/unlocked.png")); static const QIcon unlockedIcon(QLatin1String(":/qworkbench/images/unlocked.png"));
@@ -371,6 +375,6 @@ int StackedEditorGroup::indexOf(IEditor *editor)
if (editor == model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>()) if (editor == model->data(model->index(i, 0), Qt::UserRole).value<IEditor*>())
return i; return i;
} }
Q_ASSERT(false); QTC_ASSERT(false, /**/);
return 0; return 0;
} }

View File

@@ -32,6 +32,7 @@
***************************************************************************/ ***************************************************************************/
#include "filemanager.h" #include "filemanager.h"
#include "ifile.h" #include "ifile.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "saveitemsdialog.h" #include "saveitemsdialog.h"
@@ -40,6 +41,8 @@
#include "mimedatabase.h" #include "mimedatabase.h"
#include "iversioncontrol.h" #include "iversioncontrol.h"
#include <utils/qtcassert.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QSettings> #include <QtCore/QSettings>
#include <QtCore/QFileInfo> #include <QtCore/QFileInfo>
@@ -177,22 +180,20 @@ bool FileManager::removeFile(IFile *file)
void FileManager::addWatch(const QString &filename) void FileManager::addWatch(const QString &filename)
{ {
if (!filename.isEmpty() && managedFiles(filename).isEmpty()) { if (!filename.isEmpty() && managedFiles(filename).isEmpty())
m_fileWatcher->addPath(filename); m_fileWatcher->addPath(filename);
} }
}
void FileManager::removeWatch(const QString &filename) void FileManager::removeWatch(const QString &filename)
{ {
if (!filename.isEmpty() && managedFiles(filename).isEmpty()) { if (!filename.isEmpty() && managedFiles(filename).isEmpty())
m_fileWatcher->removePath(filename); m_fileWatcher->removePath(filename);
} }
}
void FileManager::checkForNewFileName() void FileManager::checkForNewFileName()
{ {
IFile *file = qobject_cast<IFile *>(sender()); IFile *file = qobject_cast<IFile *>(sender());
Q_ASSERT(file); QTC_ASSERT(file, return);
const QString newfilename = fixFileName(file->fileName()); const QString newfilename = fixFileName(file->fileName());
const QString oldfilename = m_managedFiles.value(file).fileName; const QString oldfilename = m_managedFiles.value(file).fileName;
if (!newfilename.isEmpty() && newfilename != oldfilename) { if (!newfilename.isEmpty() && newfilename != oldfilename) {

View File

@@ -957,7 +957,8 @@ void MainWindow::resetContext()
updateContextObject(0); updateContextObject(0);
} }
QMenu *MainWindow::createPopupMenu() { QMenu *MainWindow::createPopupMenu()
{
QMenu *menu = new QMenu(this); QMenu *menu = new QMenu(this);
QList<ActionContainer *> containers = m_actionManager->containers(); QList<ActionContainer *> containers = m_actionManager->containers();
foreach (ActionContainer *c, containers) { foreach (ActionContainer *c, containers) {

View File

@@ -33,30 +33,34 @@
#include "manhattanstyle.h" #include "manhattanstyle.h"
#include <QStyleOption>
#include <QPainter>
#include <QScrollArea>
#include <QMainWindow>
#include <QDockWidget>
#include <QPixmapCache>
#include <QDialogButtonBox>
#include <QPixmap>
#include <QToolBar>
#include <QDialog>
#include <QLineEdit>
#include <QComboBox>
#include <QLibrary>
#include <QStatusBar>
#include <QApplication>
#include <QStyleFactory>
#include <QToolButton>
#include <QLabel>
#include <QPushButton>
#include <QSplitter>
#include <QMenuBar>
#include "stylehelper.h" #include "stylehelper.h"
#include "styleanimator.h" #include "styleanimator.h"
#include <qdebug.h>
#include <QtCore/QDebug>
#include <QtCore/QLibrary>
#include <QtGui/QApplication>
#include <QtGui/QComboBox>
#include <QtGui/QDialog>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QDockWidget>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QMainWindow>
#include <QtGui/QMenuBar>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QPixmapCache>
#include <QtGui/QPushButton>
#include <QtGui/QScrollArea>
#include <QtGui/QSplitter>
#include <QtGui/QStatusBar>
#include <QtGui/QStyleFactory>
#include <QtGui/QStyleOption>
#include <QtGui/QToolBar>
#include <QtGui/QToolButton>
#include <utils/qtcassert.h>
// We define a currently unused state for indicating animations // We define a currently unused state for indicating animations
#define State_Animating 0x00000040 #define State_Animating 0x00000040
@@ -97,7 +101,7 @@ public:
ManhattanStylePrivate(const QString &baseStyleName) ManhattanStylePrivate(const QString &baseStyleName)
{ {
style = QStyleFactory::create(baseStyleName); style = QStyleFactory::create(baseStyleName);
Q_ASSERT(style); QTC_ASSERT(style, /**/);
buttonImage_pressed = QImage(":/qworkbench/images/pushbutton_pressed.png"); buttonImage_pressed = QImage(":/qworkbench/images/pushbutton_pressed.png");
buttonImage = QImage(":/qworkbench/images/pushbutton.png"); buttonImage = QImage(":/qworkbench/images/pushbutton.png");
@@ -105,12 +109,15 @@ public:
lineeditImage_disabled = QImage(":/qworkbench/images/inputfield_disabled.png"); lineeditImage_disabled = QImage(":/qworkbench/images/inputfield_disabled.png");
} }
~ManhattanStylePrivate() { ~ManhattanStylePrivate()
{
delete style; delete style;
style = 0; style = 0;
} }
void init(); void init();
public:
QStyle *style; QStyle *style;
QImage buttonImage; QImage buttonImage;
QImage buttonImage_pressed; QImage buttonImage_pressed;

View File

@@ -33,19 +33,22 @@
#include "mimedatabase.h" #include "mimedatabase.h"
#include <QtCore/QStringList> #include <utils/qtcassert.h>
#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile> #include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLocale>
#include <QtCore/QMap> #include <QtCore/QMap>
#include <QtCore/QMultiHash> #include <QtCore/QMultiHash>
#include <QtCore/QDebug>
#include <QtCore/QRegExp> #include <QtCore/QRegExp>
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtCore/QByteArray>
#include <QtCore/QSharedData> #include <QtCore/QSharedData>
#include <QtCore/QSharedPointer> #include <QtCore/QSharedPointer>
#include <QtCore/QStringList>
#include <QtCore/QTextStream> #include <QtCore/QTextStream>
#include <QtCore/QLocale>
#include <QtXml/QXmlStreamReader> #include <QtXml/QXmlStreamReader>
enum { debugMimeDB = 0 }; enum { debugMimeDB = 0 };
@@ -574,7 +577,7 @@ BaseMimeTypeParser:: BaseMimeTypeParser() :
// "*.log[1-9]" // "*.log[1-9]"
m_suffixPattern(QLatin1String("^\\*\\.[\\w]+$")) m_suffixPattern(QLatin1String("^\\*\\.[\\w]+$"))
{ {
Q_ASSERT(m_suffixPattern.isValid()); QTC_ASSERT(m_suffixPattern.isValid(), /**/);
} }
void BaseMimeTypeParser::addGlobPattern(const QString &pattern, MimeTypeData *d) const void BaseMimeTypeParser::addGlobPattern(const QString &pattern, MimeTypeData *d) const

View File

@@ -32,11 +32,13 @@
***************************************************************************/ ***************************************************************************/
#include "modemanager.h" #include "modemanager.h"
#include "fancytabwidget.h" #include "fancytabwidget.h"
#include "fancyactionbar.h" #include "fancyactionbar.h"
#include "mainwindow.h" #include "mainwindow.h"
#include <aggregation/aggregate.h> #include <aggregation/aggregate.h>
#include <coreplugin/actionmanager/actionmanagerinterface.h> #include <coreplugin/actionmanager/actionmanagerinterface.h>
#include <coreplugin/actionmanager/icommand.h> #include <coreplugin/actionmanager/icommand.h>
#include <coreplugin/coreconstants.h> #include <coreplugin/coreconstants.h>
@@ -44,9 +46,12 @@
#include <coreplugin/imode.h> #include <coreplugin/imode.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QObject> #include <QtCore/QObject>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QSignalMapper> #include <QtCore/QSignalMapper>
#include <QtGui/QAction> #include <QtGui/QAction>
#include <QtGui/QTabWidget> #include <QtGui/QTabWidget>
#include <QtGui/QVBoxLayout> #include <QtGui/QVBoxLayout>
@@ -225,7 +230,7 @@ void ModeManager::currentTabChanged(int index)
void ModeManager::setFocusToCurrentMode() void ModeManager::setFocusToCurrentMode()
{ {
IMode *mode = currentMode(); IMode *mode = currentMode();
Q_ASSERT(mode); QTC_ASSERT(mode, return);
QWidget *widget = mode->widget(); QWidget *widget = mode->widget();
if (widget) { if (widget) {
QWidget *focusWidget = widget->focusWidget(); QWidget *focusWidget = widget->focusWidget();

View File

@@ -40,11 +40,13 @@
#include "uniqueidmanager.h" #include "uniqueidmanager.h"
#include "viewmanagerinterface.h" #include "viewmanagerinterface.h"
#include <utils/qtcassert.h>
using namespace Core; using namespace Core;
using namespace Core::Internal; using namespace Core::Internal;
ProgressManager::ProgressManager(QObject *parent) : ProgressManager::ProgressManager(QObject *parent)
ProgressManagerInterface(parent) : ProgressManagerInterface(parent)
{ {
m_progressView = new ProgressView; m_progressView = new ProgressView;
ICore *core = CoreImpl::instance(); ICore *core = CoreImpl::instance();
@@ -103,7 +105,7 @@ QWidget *ProgressManager::progressView()
void ProgressManager::taskFinished() void ProgressManager::taskFinished()
{ {
QObject *taskObject = sender(); QObject *taskObject = sender();
Q_ASSERT(taskObject); QTC_ASSERT(taskObject, return);
QFutureWatcher<void> *task = static_cast<QFutureWatcher<void> *>(taskObject); QFutureWatcher<void> *task = static_cast<QFutureWatcher<void> *>(taskObject);
m_runningTasks.remove(task); m_runningTasks.remove(task);
delete task; delete task;

View File

@@ -34,6 +34,8 @@
#include "progressview.h" #include "progressview.h"
#include "futureprogress.h" #include "futureprogress.h"
#include <utils/qtcassert.h>
#include <QtGui/QHBoxLayout> #include <QtGui/QHBoxLayout>
using namespace Core; using namespace Core;
@@ -136,7 +138,7 @@ void ProgressView::removeTask(FutureProgress *task)
void ProgressView::slotFinished() void ProgressView::slotFinished()
{ {
FutureProgress *progress = qobject_cast<FutureProgress *>(sender()); FutureProgress *progress = qobject_cast<FutureProgress *>(sender());
Q_ASSERT(progress); QTC_ASSERT(progress, return);
if (m_keep.contains(progress) && !m_keep.value(progress) && !progress->hasError()) if (m_keep.contains(progress) && !m_keep.value(progress) && !progress->hasError())
removeTask(progress); removeTask(progress);
removeOldTasks(m_type.value(progress), true); removeOldTasks(m_type.value(progress), true);

View File

@@ -38,12 +38,15 @@
#include <coreplugin/messagemanager.h> #include <coreplugin/messagemanager.h>
#include <coreplugin/editormanager/editorgroup.h> #include <coreplugin/editormanager/editorgroup.h>
#include <utils/qtcassert.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtCore/QSettings> #include <QtCore/QSettings>
#include <QtGui/QMainWindow> #include <QtGui/QMainWindow>
#include <QtGui/QStatusBar> #include <QtGui/QStatusBar>
#include <QtGui/QToolBar> #include <QtGui/QToolBar>
#include <QtScript/QScriptEngine> #include <QtScript/QScriptEngine>
namespace { namespace {
@@ -107,7 +110,7 @@ QString CorePrototype::toString() const
CorePrototype::ICore *CorePrototype::callee() const CorePrototype::ICore *CorePrototype::callee() const
{ {
ICore *rc = qscriptvalue_cast<ICore *>(thisObject()); ICore *rc = qscriptvalue_cast<ICore *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }
@@ -121,14 +124,14 @@ MessageManagerPrototype::MessageManagerPrototype(QObject *parent) :
void MessageManagerPrototype::displayStatusBarMessage(const QString &text, int ms) void MessageManagerPrototype::displayStatusBarMessage(const QString &text, int ms)
{ {
MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject()); MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject());
Q_ASSERT(mm); QTC_ASSERT(mm, return);
mm->displayStatusBarMessage(text, ms); mm->displayStatusBarMessage(text, ms);
} }
void MessageManagerPrototype::printToOutputPane(const QString &text, bool bringToForeground) void MessageManagerPrototype::printToOutputPane(const QString &text, bool bringToForeground)
{ {
MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject()); MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject());
Q_ASSERT(mm); QTC_ASSERT(mm, return);
mm->printToOutputPane(text, bringToForeground); mm->printToOutputPane(text, bringToForeground);
} }
@@ -147,28 +150,66 @@ FileManagerPrototype::FileManagerPrototype(QObject *parent) :
FileManager *FileManagerPrototype::callee() const FileManager *FileManagerPrototype::callee() const
{ {
FileManager *rc = qscriptvalue_cast<FileManager *>(thisObject()); FileManager *rc = qscriptvalue_cast<FileManager *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }
bool FileManagerPrototype::addFiles(const QList<Core::IFile *> &files) { return callee()->addFiles(files); } bool FileManagerPrototype::addFiles(const QList<Core::IFile *> &files)
bool FileManagerPrototype::addFile(Core::IFile *file) { return callee()->addFile(file); } {
bool FileManagerPrototype::removeFile(Core::IFile *file) { return callee()->removeFile(file); } return callee()->addFiles(files);
}
bool FileManagerPrototype::addFile(Core::IFile *file)
{
return callee()->addFile(file);
}
bool FileManagerPrototype::removeFile(Core::IFile *file)
{
return callee()->removeFile(file);
}
QList<Core::IFile*> QList<Core::IFile*>
FileManagerPrototype::saveModifiedFilesSilently(const QList<Core::IFile*> &files) { return callee()->saveModifiedFilesSilently(files); } FileManagerPrototype::saveModifiedFilesSilently(const QList<Core::IFile*> &files)
{
return callee()->saveModifiedFilesSilently(files);
}
QString FileManagerPrototype::getSaveAsFileName(Core::IFile *file) { return callee()->getSaveAsFileName(file); } QString FileManagerPrototype::getSaveAsFileName(Core::IFile *file)
{
return callee()->getSaveAsFileName(file);
}
bool FileManagerPrototype::isFileManaged(const QString &fileName) const
{
return callee()->isFileManaged(fileName);
}
bool FileManagerPrototype::isFileManaged(const QString &fileName) const { return callee()->isFileManaged(fileName); }
QList<Core::IFile *> QList<Core::IFile *>
FileManagerPrototype::managedFiles(const QString &fileName) const { return callee()->managedFiles(fileName); } FileManagerPrototype::managedFiles(const QString &fileName) const
{
return callee()->managedFiles(fileName);
}
void FileManagerPrototype::blockFileChange(Core::IFile *file) { callee()->blockFileChange(file); } void FileManagerPrototype::blockFileChange(Core::IFile *file)
void FileManagerPrototype::unblockFileChange(Core::IFile *file) { return callee()->unblockFileChange(file); } {
callee()->blockFileChange(file);
}
void FileManagerPrototype::addToRecentFiles(const QString &fileName) { return callee()->addToRecentFiles(fileName); } void FileManagerPrototype::unblockFileChange(Core::IFile *file)
QStringList FileManagerPrototype::recentFiles() const { return callee()->recentFiles(); } {
return callee()->unblockFileChange(file);
}
void FileManagerPrototype::addToRecentFiles(const QString &fileName)
{
return callee()->addToRecentFiles(fileName);
}
QStringList FileManagerPrototype::recentFiles() const
{
return callee()->recentFiles();
}
QString FileManagerPrototype::toString() const QString FileManagerPrototype::toString() const
{ {
@@ -185,7 +226,7 @@ FilePrototype::FilePrototype(QObject *parent) :
IFile *FilePrototype::callee() const IFile *FilePrototype::callee() const
{ {
IFile *rc = qscriptvalue_cast<IFile *>(thisObject()); IFile *rc = qscriptvalue_cast<IFile *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }
@@ -270,39 +311,66 @@ QString EditorManagerPrototype::toString() const
EditorManagerPrototype::EditorManager *EditorManagerPrototype::callee() const EditorManagerPrototype::EditorManager *EditorManagerPrototype::callee() const
{ {
EditorManager *rc = qscriptvalue_cast<EditorManager *>(thisObject()); EditorManager *rc = qscriptvalue_cast<EditorManager *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }
// ------------- EditorPrototype // ------------- EditorPrototype
EditorPrototype::EditorPrototype(QObject *parent) : EditorPrototype::EditorPrototype(QObject *parent)
QObject(parent) : QObject(parent)
{ {
} }
QString EditorPrototype::displayName() const { return callee()->displayName(); } QString EditorPrototype::displayName() const
void EditorPrototype::setDisplayName(const QString &title) { callee()->setDisplayName(title); } {
return callee()->displayName();
}
QString EditorPrototype::kind() const { return QLatin1String(callee()->kind()); } void EditorPrototype::setDisplayName(const QString &title)
bool EditorPrototype::duplicateSupported() const { return callee()->duplicateSupported(); } {
callee()->setDisplayName(title);
}
bool EditorPrototype::createNew(const QString &contents) { return callee()->createNew(contents); } QString EditorPrototype::kind() const
bool EditorPrototype::open(const QString &fileName) { return callee()->open(fileName); } {
return QLatin1String(callee()->kind());
}
bool EditorPrototype::duplicateSupported() const
{
return callee()->duplicateSupported();
}
bool EditorPrototype::createNew(const QString &contents)
{
return callee()->createNew(contents);
}
bool EditorPrototype::open(const QString &fileName)
{
return callee()->open(fileName);
}
Core::IEditor *EditorPrototype::duplicate(QWidget *parent) Core::IEditor *EditorPrototype::duplicate(QWidget *parent)
{ {
return callee()->duplicate(parent); return callee()->duplicate(parent);
} }
Core::IFile *EditorPrototype::file() const { return callee()->file(); } Core::IFile *EditorPrototype::file() const
QToolBar* EditorPrototype::toolBar() const { return callee()->toolBar();} {
return callee()->file();
}
QToolBar* EditorPrototype::toolBar() const
{
return callee()->toolBar();
}
Core::IEditor *EditorPrototype::callee() const Core::IEditor *EditorPrototype::callee() const
{ {
IEditor *rc = qscriptvalue_cast<IEditor *>(thisObject()); IEditor *rc = qscriptvalue_cast<IEditor *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }
@@ -375,7 +443,7 @@ QString EditorGroupPrototype::toString() const
Core::EditorGroup *EditorGroupPrototype::callee() const Core::EditorGroup *EditorGroupPrototype::callee() const
{ {
EditorGroup *rc = qscriptvalue_cast<EditorGroup *>(thisObject()); EditorGroup *rc = qscriptvalue_cast<EditorGroup *>(thisObject());
Q_ASSERT(rc); QTC_ASSERT(rc, return 0);
return rc; return rc;
} }

View File

@@ -36,8 +36,10 @@
#include "metatypedeclarations.h" #include "metatypedeclarations.h"
#include <extensionsystem/ExtensionSystemInterfaces> #include <extensionsystem/ExtensionSystemInterfaces>
#include <utils/qtcassert.h>
#include <interface_wrap_helpers.h> #include <interface_wrap_helpers.h>
#include <wrap_helpers.h> #include <wrap_helpers.h>
#include <limits.h> #include <limits.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
@@ -170,7 +172,7 @@ template <int TAcceptMode, int TFileMode>
if (fileDialog.exec() == QDialog::Rejected) if (fileDialog.exec() == QDialog::Rejected)
return QScriptValue(engine, QScriptValue::NullValue); return QScriptValue(engine, QScriptValue::NullValue);
const QStringList rc = fileDialog.selectedFiles(); const QStringList rc = fileDialog.selectedFiles();
Q_ASSERT(!rc.empty()); QTC_ASSERT(!rc.empty(), /**/);
return TFileMode == QFileDialog::ExistingFiles ? return TFileMode == QFileDialog::ExistingFiles ?
engine->toScriptValue(rc) : engine->toScriptValue(rc.front()); engine->toScriptValue(rc) : engine->toScriptValue(rc.front());
} }
@@ -249,7 +251,7 @@ void ScriptManager::ensureEngineInitialized()
{ {
if (m_initialized) if (m_initialized)
return; return;
Q_ASSERT(m_core); QTC_ASSERT(m_core, return);
// register QObjects that occur as properties // register QObjects that occur as properties
SharedTools::registerQObject<QMainWindow>(m_engine); SharedTools::registerQObject<QMainWindow>(m_engine);
SharedTools::registerQObject<QStatusBar>(m_engine); SharedTools::registerQObject<QStatusBar>(m_engine);

View File

@@ -52,7 +52,8 @@ void Animation::paint(QPainter *painter, const QStyleOption *option)
Q_UNUSED(painter); Q_UNUSED(painter);
} }
void Animation::drawBlendedImage(QPainter *painter, QRect rect, float alpha) { void Animation::drawBlendedImage(QPainter *painter, QRect rect, float alpha)
{
if (_secondaryImage.isNull() || _primaryImage.isNull()) if (_secondaryImage.isNull() || _primaryImage.isNull())
return; return;

View File

@@ -32,21 +32,25 @@
***************************************************************************/ ***************************************************************************/
#include "versiondialog.h" #include "versiondialog.h"
#include "coreconstants.h" #include "coreconstants.h"
#include "coreimpl.h" #include "coreimpl.h"
#include <utils/qtcassert.h>
#include <QtCore/QDate>
#include <QtCore/QFile>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTextBrowser>
using namespace Core; using namespace Core;
using namespace Core::Internal; using namespace Core::Internal;
using namespace Core::Constants; using namespace Core::Constants;
#include <QtCore/QDate>
#include <QtCore/QFile>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QTextBrowser>
VersionDialog::VersionDialog(QWidget *parent) VersionDialog::VersionDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent)
{ {
@@ -90,7 +94,7 @@ VersionDialog::VersionDialog(QWidget *parent)
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close); QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close);
Q_ASSERT(closeButton); QTC_ASSERT(closeButton, /**/);
buttonBox->addButton(closeButton, QDialogButtonBox::ButtonRole(QDialogButtonBox::RejectRole | QDialogButtonBox::AcceptRole)); buttonBox->addButton(closeButton, QDialogButtonBox::ButtonRole(QDialogButtonBox::RejectRole | QDialogButtonBox::AcceptRole));
connect(buttonBox , SIGNAL(rejected()), this, SLOT(reject())); connect(buttonBox , SIGNAL(rejected()), this, SLOT(reject()));
@@ -118,7 +122,7 @@ void VersionDialog::popupLicense()
// Read file into string // Read file into string
ICore * core = CoreImpl::instance(); ICore * core = CoreImpl::instance();
Q_ASSERT(core != NULL); QTC_ASSERT(core, return);
QString fileName = core->resourcePath() + "/license.txt"; QString fileName = core->resourcePath() + "/license.txt";
QFile file(fileName); QFile file(fileName);

View File

@@ -1,4 +1,4 @@
<plugin name="CodePaster" version="0.1" compatVersion="0.1"> <plugin name="CodePaster" version="0.9.1" compatVersion="0.9.1">
<vendor>Nokia Corporation</vendor> <vendor>Nokia Corporation</vendor>
<copyright>(C) 2008 Nokia Corporation</copyright> <copyright>(C) 2008 Nokia Corporation</copyright>
<license>Nokia Technology Preview License Agreement</license> <license>Nokia Technology Preview License Agreement</license>

View File

@@ -36,12 +36,14 @@
#include <utils/codegeneration.h> #include <utils/codegeneration.h>
#include <utils/newclasswidget.h> #include <utils/newclasswidget.h>
#include <utils/qtcassert.h>
#include <QtCore/QTextStream>
#include <QtCore/QDir>
#include <QtCore/QDebug> #include <QtCore/QDebug>
#include <QtGui/QComboBox> #include <QtCore/QDir>
#include <QtCore/QTextStream>
#include <QtGui/QCheckBox> #include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QLabel> #include <QtGui/QLabel>
#include <QtGui/QVBoxLayout> #include <QtGui/QVBoxLayout>
#include <QtGui/QWizard> #include <QtGui/QWizard>
@@ -73,6 +75,7 @@ ClassNamePage::ClassNamePage(const QString &sourceSuffix,
m_newClassWidget->setBaseClassEditable(true); m_newClassWidget->setBaseClassEditable(true);
m_newClassWidget->setFormInputVisible(false); m_newClassWidget->setFormInputVisible(false);
m_newClassWidget->setNamespacesEnabled(true); m_newClassWidget->setNamespacesEnabled(true);
m_newClassWidget->setAllowDirectories(true);
connect(m_newClassWidget, SIGNAL(validChanged()), connect(m_newClassWidget, SIGNAL(validChanged()),
this, SLOT(slotValidChanged())); this, SLOT(slotValidChanged()));
@@ -195,7 +198,7 @@ bool CppClassWizard::generateHeaderAndSource(const CppClassWizardParameters &par
<< "\n#define " << guard << '\n' << '\n'; << "\n#define " << guard << '\n' << '\n';
const QRegExp qtClassExpr(QLatin1String("^Q[A-Z3].+")); const QRegExp qtClassExpr(QLatin1String("^Q[A-Z3].+"));
Q_ASSERT(qtClassExpr.isValid()); QTC_ASSERT(qtClassExpr.isValid(), /**/);
const bool superIsQtClass = qtClassExpr.exactMatch(params.baseClass); const bool superIsQtClass = qtClassExpr.exactMatch(params.baseClass);
if (superIsQtClass) { if (superIsQtClass) {
Core::Utils::writeIncludeFileDirective(params.baseClass, true, headerStr); Core::Utils::writeIncludeFileDirective(params.baseClass, true, headerStr);

View File

@@ -79,6 +79,7 @@
#include <QtGui/QComboBox> #include <QtGui/QComboBox>
#include <QtGui/QTreeView> #include <QtGui/QTreeView>
#include <QtGui/QHeaderView> #include <QtGui/QHeaderView>
#include <QtGui/QStringListModel>
using namespace CPlusPlus; using namespace CPlusPlus;
using namespace CppEditor::Internal; using namespace CppEditor::Internal;
@@ -344,11 +345,11 @@ void CPPEditor::updateMethodBoxIndex()
QModelIndex lastIndex; QModelIndex lastIndex;
const int rc = m_overviewModel->rowCount(QModelIndex()); const int rc = m_overviewModel->rowCount();
for (int row = 0; row < rc; ++row) { for (int row = 0; row < rc; ++row) {
const QModelIndex index = m_overviewModel->index(row, 0, QModelIndex()); const QModelIndex index = m_overviewModel->index(row, 0, QModelIndex());
Symbol *symbol = m_overviewModel->symbolFromIndex(index); Symbol *symbol = m_overviewModel->symbolFromIndex(index);
if (symbol->line() > unsigned(line)) if (symbol && symbol->line() > unsigned(line))
break; break;
lastIndex = index; lastIndex = index;
} }
@@ -519,6 +520,15 @@ void CPPEditor::jumpToDefinition()
#endif #endif
} }
} else { } else {
foreach (const Document::MacroUse use, doc->macroUses()) {
if (use.contains(endOfName - 1)) {
const Macro &macro = use.macro();
const QString fileName = QString::fromUtf8(macro.fileName);
if (TextEditor::BaseTextEditor::openEditorAt(fileName, macro.line, 0))
return; // done
}
}
qDebug() << "No results for expression:" << expression; qDebug() << "No results for expression:" << expression;
} }
} }

View File

@@ -42,6 +42,7 @@
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QAction; class QAction;
class QComboBox; class QComboBox;
class QStringListModel;
QT_END_NAMESPACE QT_END_NAMESPACE
namespace Core { namespace Core {

View File

@@ -42,6 +42,7 @@ CppClassesFilter::CppClassesFilter(CppModelManager *manager, Core::EditorManager
setIncludedByDefault(false); setIncludedByDefault(false);
search.setSymbolsToSearchFor(SearchSymbols::Classes); search.setSymbolsToSearchFor(SearchSymbols::Classes);
search.setSeparateScope(true);
} }
CppClassesFilter::~CppClassesFilter() CppClassesFilter::~CppClassesFilter()

View File

@@ -32,6 +32,7 @@
***************************************************************************/ ***************************************************************************/
#include "cppcodecompletion.h" #include "cppcodecompletion.h"
#include "cppmodelmanager.h" #include "cppmodelmanager.h"
#include <Control.h> #include <Control.h>
@@ -45,6 +46,7 @@
#include <SymbolVisitor.h> #include <SymbolVisitor.h>
#include <Scope.h> #include <Scope.h>
#include <TranslationUnit.h> #include <TranslationUnit.h>
#include <cplusplus/ResolveExpression.h> #include <cplusplus/ResolveExpression.h>
#include <cplusplus/LookupContext.h> #include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h> #include <cplusplus/Overview.h>
@@ -55,6 +57,7 @@
#include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/editormanager.h>
#include <texteditor/itexteditor.h> #include <texteditor/itexteditor.h>
#include <texteditor/itexteditable.h> #include <texteditor/itexteditable.h>
#include <utils/qtcassert.h>
#include <texteditor/basetexteditor.h> #include <texteditor/basetexteditor.h>
#include <QtCore/QDebug> #include <QtCore/QDebug>
@@ -540,7 +543,7 @@ bool CppCodeCompletion::completeMember(FullySpecifiedType,
const QList<TypeOfExpression::Result> &results, const QList<TypeOfExpression::Result> &results,
const LookupContext &context) const LookupContext &context)
{ {
Q_ASSERT(! results.isEmpty()); QTC_ASSERT(!results.isEmpty(), return false);
QList<Symbol *> classObjectCandidates; QList<Symbol *> classObjectCandidates;
@@ -699,7 +702,9 @@ void CppCodeCompletion::addMacros(const LookupContext &context)
continue; continue;
processed.insert(fn); processed.insert(fn);
if (Document::Ptr doc = context.document(fn)) { if (Document::Ptr doc = context.document(fn)) {
macroNames += doc->macroNames(); foreach (const Macro macro, doc->definedMacros()) {
macroNames.insert(macro.name);
}
todo += doc->includedFiles(); todo += doc->includedFiles();
} }
} }
@@ -936,7 +941,7 @@ void CppCodeCompletion::complete(const TextEditor::CompletionItem &item)
if (m_completionOperator == T_LPAREN) { if (m_completionOperator == T_LPAREN) {
if (symbol) { if (symbol) {
Function *function = symbol->type()->asFunction(); Function *function = symbol->type()->asFunction();
Q_ASSERT(function != 0); QTC_ASSERT(function, return);
m_functionArgumentWidget = new FunctionArgumentWidget(m_core); m_functionArgumentWidget = new FunctionArgumentWidget(m_core);
m_functionArgumentWidget->showFunctionHint(function); m_functionArgumentWidget->showFunctionHint(function);
@@ -1025,6 +1030,10 @@ bool CppCodeCompletion::partiallyComplete(const QList<TextEditor::CompletionItem
void CppCodeCompletion::cleanup() void CppCodeCompletion::cleanup()
{ {
m_completions.clear(); m_completions.clear();
// Set empty map in order to avoid referencing old versions of the documents
// until the next completion
typeOfExpression.setDocuments(QMap<QString, Document::Ptr>());
} }
int CppCodeCompletion::findStartOfName(const TextEditor::ITextEditor *editor) int CppCodeCompletion::findStartOfName(const TextEditor::ITextEditor *editor)

View File

@@ -0,0 +1,50 @@
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "cppfunctionsfilter.h"
using namespace CppTools::Internal;
CppFunctionsFilter::CppFunctionsFilter(CppModelManager *manager, Core::EditorManager *editorManager)
: CppQuickOpenFilter(manager, editorManager)
{
setShortcutString("m");
setIncludedByDefault(false);
search.setSymbolsToSearchFor(SearchSymbols::Functions);
search.setSeparateScope(true);
}
CppFunctionsFilter::~CppFunctionsFilter()
{
}

View File

@@ -0,0 +1,58 @@
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#ifndef CPPFUNCTIONSFILTER_H
#define CPPFUNCTIONSFILTER_H
#include <cppquickopenfilter.h>
namespace CppTools {
namespace Internal {
class CppFunctionsFilter : public CppQuickOpenFilter
{
Q_OBJECT
public:
CppFunctionsFilter(CppModelManager *manager, Core::EditorManager *editorManager);
~CppFunctionsFilter();
QString trName() const { return tr("Methods"); }
QString name() const { return QLatin1String("Methods"); }
Priority priority() const { return Medium; }
};
} // namespace Internal
} // namespace CppTools
#endif // CPPFUNCTIONSFILTER_H

View File

@@ -37,6 +37,7 @@
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <coreplugin/uniqueidmanager.h> #include <coreplugin/uniqueidmanager.h>
#include <texteditor/itexteditor.h> #include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <debugger/debuggerconstants.h> #include <debugger/debuggerconstants.h>
#include <CoreTypes.h> #include <CoreTypes.h>
@@ -51,13 +52,13 @@
#include <cplusplus/TypeOfExpression.h> #include <cplusplus/TypeOfExpression.h>
#include <QtGui/QToolTip> #include <QtGui/QToolTip>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QTextCursor> #include <QtGui/QTextCursor>
#include <QtGui/QTextBlock> #include <QtGui/QTextBlock>
#include <QtHelp/QHelpEngineCore> #include <QtHelp/QHelpEngineCore>
#include <QtCore/QtCore> #include <QtCore/QtCore>
using namespace CppTools::Internal; using namespace CppTools::Internal;
using namespace CPlusPlus;
CppHoverHandler::CppHoverHandler(CppModelManager *manager, QObject *parent) CppHoverHandler::CppHoverHandler(CppModelManager *manager, QObject *parent)
: QObject(parent), m_manager(manager), m_helpEngineNeedsSetup(false) : QObject(parent), m_manager(manager), m_helpEngineNeedsSetup(false)
@@ -104,11 +105,9 @@ void CppHoverHandler::showToolTip(TextEditor::ITextEditor *editor, const QPoint
} }
} }
static QString buildHelpId(const CPlusPlus::FullySpecifiedType &type, static QString buildHelpId(const FullySpecifiedType &type,
const CPlusPlus::Symbol *symbol) const Symbol *symbol)
{ {
using namespace CPlusPlus;
Name *name = 0; Name *name = 0;
Scope *scope = 0; Scope *scope = 0;
@@ -156,12 +155,10 @@ static QString buildHelpId(const CPlusPlus::FullySpecifiedType &type,
void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, int pos) void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, int pos)
{ {
using namespace CPlusPlus;
m_helpId.clear(); m_helpId.clear();
m_toolTip.clear(); m_toolTip.clear();
QPlainTextEdit *edit = qobject_cast<QPlainTextEdit *>(editor->widget()); TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
if (!edit) if (!edit)
return; return;
@@ -169,8 +166,7 @@ void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, in
tc.setPosition(pos); tc.setPosition(pos);
const int lineNumber = tc.block().blockNumber() + 1; const int lineNumber = tc.block().blockNumber() + 1;
const QString fileName = editor->file()->fileName();
QString fileName = editor->file()->fileName();
Document::Ptr doc = m_manager->document(fileName); Document::Ptr doc = m_manager->document(fileName);
if (doc) { if (doc) {
foreach (Document::DiagnosticMessage m, doc->diagnosticMessages()) { foreach (Document::DiagnosticMessage m, doc->diagnosticMessages()) {
@@ -235,6 +231,16 @@ void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, in
} }
} }
if (doc && m_toolTip.isEmpty()) {
foreach (const Document::MacroUse &use, doc->macroUses()) {
if (use.contains(pos)) {
m_toolTip = use.macro().toString();
m_helpId = use.macro().name;
break;
}
}
}
if (m_helpEngineNeedsSetup if (m_helpEngineNeedsSetup
&& m_helpEngine->registeredDocumentations().count() > 0) { && m_helpEngine->registeredDocumentations().count() > 0) {
m_helpEngine->setupData(); m_helpEngine->setupData();
@@ -243,7 +249,8 @@ void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, in
if (!m_helpId.isEmpty() && !m_helpEngine->linksForIdentifier(m_helpId).isEmpty()) { if (!m_helpId.isEmpty() && !m_helpEngine->linksForIdentifier(m_helpId).isEmpty()) {
m_toolTip = QString(QLatin1String("<table><tr><td valign=middle><nobr>%1</td>" m_toolTip = QString(QLatin1String("<table><tr><td valign=middle><nobr>%1</td>"
"<td><img src=\":/cpptools/images/f1.svg\"></td></tr></table>")).arg(Qt::escape(m_toolTip)); "<td><img src=\":/cpptools/images/f1.svg\"></td></tr></table>"))
.arg(Qt::escape(m_toolTip));
editor->setContextHelpId(m_helpId); editor->setContextHelpId(m_helpId);
} else if (!m_toolTip.isEmpty()) { } else if (!m_toolTip.isEmpty()) {
m_toolTip = QString(QLatin1String("<nobr>%1")).arg(Qt::escape(m_toolTip)); m_toolTip = QString(QLatin1String("<nobr>%1")).arg(Qt::escape(m_toolTip));

View File

@@ -31,8 +31,7 @@
** **
***************************************************************************/ ***************************************************************************/
#define _SCL_SECURE_NO_WARNINGS 1 #include <cplusplus/pp.h>
#include "pp.h"
#include "cppmodelmanager.h" #include "cppmodelmanager.h"
#include "cpphoverhandler.h" #include "cpphoverhandler.h"
@@ -53,6 +52,8 @@
#include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/progressmanager/progressmanager.h>
#include <utils/qtcassert.h>
#include <TranslationUnit.h> #include <TranslationUnit.h>
#include <Semantic.h> #include <Semantic.h>
#include <AST.h> #include <AST.h>
@@ -65,15 +66,16 @@
#include <Lexer.h> #include <Lexer.h>
#include <Token.h> #include <Token.h>
#include <QPlainTextEdit> #include <QtCore/QDebug>
#include <QTime> #include <QtCore/QMutexLocker>
#include <QDebug> #include <QtCore/QTime>
//#include <QtGui/QPlainTextEdit>
using namespace CppTools;
using namespace CppTools::Internal;
using namespace CPlusPlus; using namespace CPlusPlus;
namespace CppTools {
namespace Internal {
static const char pp_configuration_file[] = "<configuration>"; static const char pp_configuration_file[] = "<configuration>";
static const char pp_configuration[] = static const char pp_configuration[] =
@@ -105,38 +107,81 @@ static const char pp_configuration[] =
"#define __declspec(a)\n" "#define __declspec(a)\n"
"#define STDMETHOD(method) virtual HRESULT STDMETHODCALLTYPE method\n"; "#define STDMETHOD(method) virtual HRESULT STDMETHODCALLTYPE method\n";
class CppPreprocessor: public rpp::Client namespace CppTools {
namespace Internal {
class CppPreprocessor: public CPlusPlus::Client
{ {
public: public:
CppPreprocessor(QPointer<CppModelManager> modelManager) CppPreprocessor(QPointer<CppModelManager> modelManager);
void setWorkingCopy(const QMap<QString, QByteArray> &workingCopy);
void setIncludePaths(const QStringList &includePaths);
void setFrameworkPaths(const QStringList &frameworkPaths);
void setProjectFiles(const QStringList &files);
void run(QString &fileName);
void operator()(QString &fileName);
protected:
CPlusPlus::Document::Ptr switchDocument(CPlusPlus::Document::Ptr doc);
bool includeFile(const QString &absoluteFilePath, QByteArray *result);
QByteArray tryIncludeFile(QString &fileName, IncludeType type);
void mergeEnvironment(CPlusPlus::Document::Ptr doc);
void mergeEnvironment(CPlusPlus::Document::Ptr doc, QSet<QString> *processed);
virtual void macroAdded(const Macro &macro);
virtual void startExpandingMacro(unsigned offset,
const Macro &macro,
const QByteArray &originalText);
virtual void stopExpandingMacro(unsigned offset, const Macro &macro);
virtual void startSkippingBlocks(unsigned offset);
virtual void stopSkippingBlocks(unsigned offset);
virtual void sourceNeeded(QString &fileName, IncludeType type);
private:
QPointer<CppModelManager> m_modelManager;
CppModelManager::DocumentTable m_documents;
Environment env;
pp m_proc;
QStringList m_includePaths;
QStringList m_systemIncludePaths;
QMap<QString, QByteArray> m_workingCopy;
QStringList m_projectFiles;
QStringList m_frameworkPaths;
QSet<QString> m_included;
CPlusPlus::Document::Ptr m_currentDoc;
};
} // namespace Internal
} // namespace CppTools
CppPreprocessor::CppPreprocessor(QPointer<CppModelManager> modelManager)
: m_modelManager(modelManager), : m_modelManager(modelManager),
m_documents(modelManager->documents()), m_documents(modelManager->documents()),
m_proc(this, env) m_proc(this, env)
{ } { }
void setWorkingCopy(const QMap<QString, QByteArray> &workingCopy) void CppPreprocessor::setWorkingCopy(const QMap<QString, QByteArray> &workingCopy)
{ m_workingCopy = workingCopy; } { m_workingCopy = workingCopy; }
void setIncludePaths(const QStringList &includePaths) void CppPreprocessor::setIncludePaths(const QStringList &includePaths)
{ m_includePaths = includePaths; } { m_includePaths = includePaths; }
void setFrameworkPaths(const QStringList &frameworkPaths) void CppPreprocessor::setFrameworkPaths(const QStringList &frameworkPaths)
{ m_frameworkPaths = frameworkPaths; } { m_frameworkPaths = frameworkPaths; }
void addIncludePath(const QString &path) void CppPreprocessor::setProjectFiles(const QStringList &files)
{ m_includePaths.append(path); }
void setProjectFiles(const QStringList &files)
{ m_projectFiles = files; } { m_projectFiles = files; }
void run(QString &fileName) void CppPreprocessor::run(QString &fileName)
{ sourceNeeded(fileName, IncludeGlobal); } { sourceNeeded(fileName, IncludeGlobal); }
void operator()(QString &fileName) void CppPreprocessor::operator()(QString &fileName)
{ run(fileName); } { run(fileName); }
protected: bool CppPreprocessor::includeFile(const QString &absoluteFilePath, QByteArray *result)
bool includeFile(const QString &absoluteFilePath, QByteArray *result)
{ {
if (absoluteFilePath.isEmpty() || m_included.contains(absoluteFilePath)) { if (absoluteFilePath.isEmpty() || m_included.contains(absoluteFilePath)) {
return true; return true;
@@ -165,7 +210,7 @@ protected:
return false; return false;
} }
QByteArray tryIncludeFile(QString &fileName, IncludeType type) QByteArray CppPreprocessor::tryIncludeFile(QString &fileName, IncludeType type)
{ {
QFileInfo fileInfo(fileName); QFileInfo fileInfo(fileName);
if (fileName == QLatin1String(pp_configuration_file) || fileInfo.isAbsolute()) { if (fileName == QLatin1String(pp_configuration_file) || fileInfo.isAbsolute()) {
@@ -248,26 +293,26 @@ protected:
return QByteArray(); return QByteArray();
} }
virtual void macroAdded(const QByteArray &macroName, const QByteArray &macroText) void CppPreprocessor::macroAdded(const Macro &macro)
{ {
if (! m_currentDoc) if (! m_currentDoc)
return; return;
m_currentDoc->appendMacro(macroName, macroText); m_currentDoc->appendMacro(macro);
} }
virtual void startExpandingMacro(unsigned offset, void CppPreprocessor::startExpandingMacro(unsigned offset,
const rpp::Macro &, const Macro &macro,
const QByteArray &originalText) const QByteArray &originalText)
{ {
if (! m_currentDoc) if (! m_currentDoc)
return; return;
//qDebug() << "start expanding:" << macro.name << "text:" << originalText; //qDebug() << "start expanding:" << macro.name << "text:" << originalText;
m_currentDoc->addMacroUse(offset, originalText.length()); m_currentDoc->addMacroUse(macro, offset, originalText.length());
} }
virtual void stopExpandingMacro(unsigned, const rpp::Macro &) void CppPreprocessor::stopExpandingMacro(unsigned, const Macro &)
{ {
if (! m_currentDoc) if (! m_currentDoc)
return; return;
@@ -275,13 +320,13 @@ protected:
//qDebug() << "stop expanding:" << macro.name; //qDebug() << "stop expanding:" << macro.name;
} }
void mergeEnvironment(Document::Ptr doc) void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
{ {
QSet<QString> processed; QSet<QString> processed;
mergeEnvironment(doc, &processed); mergeEnvironment(doc, &processed);
} }
void mergeEnvironment(Document::Ptr doc, QSet<QString> *processed) void CppPreprocessor::mergeEnvironment(Document::Ptr doc, QSet<QString> *processed)
{ {
if (! doc) if (! doc)
return; return;
@@ -293,31 +338,30 @@ protected:
processed->insert(fn); processed->insert(fn);
foreach (QString includedFile, doc->includedFiles()) foreach (QString includedFile, doc->includedFiles()) {
mergeEnvironment(m_documents.value(includedFile), processed); mergeEnvironment(m_documents.value(includedFile), processed);
const QByteArray macros = doc->definedMacros();
QByteArray localFileName = doc->fileName().toUtf8();
QByteArray dummy;
m_proc(localFileName, macros, &dummy);
} }
virtual void startSkippingBlocks(unsigned offset) foreach (const Macro macro, doc->definedMacros()) {
env.bind(macro);
}
}
void CppPreprocessor::startSkippingBlocks(unsigned offset)
{ {
//qDebug() << "start skipping blocks:" << offset; //qDebug() << "start skipping blocks:" << offset;
if (m_currentDoc) if (m_currentDoc)
m_currentDoc->startSkippingBlocks(offset); m_currentDoc->startSkippingBlocks(offset);
} }
virtual void stopSkippingBlocks(unsigned offset) void CppPreprocessor::stopSkippingBlocks(unsigned offset)
{ {
//qDebug() << "stop skipping blocks:" << offset; //qDebug() << "stop skipping blocks:" << offset;
if (m_currentDoc) if (m_currentDoc)
m_currentDoc->stopSkippingBlocks(offset); m_currentDoc->stopSkippingBlocks(offset);
} }
virtual void sourceNeeded(QString &fileName, IncludeType type) void CppPreprocessor::sourceNeeded(QString &fileName, IncludeType type)
{ {
if (fileName.isEmpty()) if (fileName.isEmpty())
return; return;
@@ -346,17 +390,17 @@ protected:
} else { } else {
Document::Ptr previousDoc = switchDocument(Document::create(fileName)); Document::Ptr previousDoc = switchDocument(Document::create(fileName));
const QByteArray previousFile = env.current_file; const QByteArray previousFile = env.currentFile;
const unsigned previousLine = env.currentLine; const unsigned previousLine = env.currentLine;
env.current_file = QByteArray(m_currentDoc->translationUnit()->fileName(), env.currentFile = QByteArray(m_currentDoc->translationUnit()->fileName(),
m_currentDoc->translationUnit()->fileNameLength()); m_currentDoc->translationUnit()->fileNameLength());
QByteArray preprocessedCode; QByteArray preprocessedCode;
m_proc(contents, &preprocessedCode); m_proc(contents, &preprocessedCode);
//qDebug() << preprocessedCode; //qDebug() << preprocessedCode;
env.current_file = previousFile; env.currentFile = previousFile;
env.currentLine = previousLine; env.currentLine = previousLine;
m_currentDoc->setSource(preprocessedCode); m_currentDoc->setSource(preprocessedCode);
@@ -371,33 +415,14 @@ protected:
} }
} }
Document::Ptr switchDocument(Document::Ptr doc) Document::Ptr CppPreprocessor::switchDocument(Document::Ptr doc)
{ {
Document::Ptr previousDoc = m_currentDoc; Document::Ptr previousDoc = m_currentDoc;
m_currentDoc = doc; m_currentDoc = doc;
return previousDoc; return previousDoc;
} }
private:
QPointer<CppModelManager> m_modelManager;
CppModelManager::DocumentTable m_documents;
rpp::Environment env;
rpp::pp m_proc;
QStringList m_includePaths;
QStringList m_systemIncludePaths;
QMap<QString, QByteArray> m_workingCopy;
QStringList m_projectFiles;
QStringList m_frameworkPaths;
QSet<QString> m_included;
Document::Ptr m_currentDoc;
};
} // namespace Internal
} // namespace CppTools
using namespace CppTools;
using namespace CppTools::Internal;
/*! /*!
\class CppTools::CppModelManager \class CppTools::CppModelManager
@@ -417,10 +442,10 @@ CppModelManager::CppModelManager(QObject *parent) :
m_projectExplorer = ExtensionSystem::PluginManager::instance() m_projectExplorer = ExtensionSystem::PluginManager::instance()
->getObject<ProjectExplorer::ProjectExplorerPlugin>(); ->getObject<ProjectExplorer::ProjectExplorerPlugin>();
Q_ASSERT(m_projectExplorer); QTC_ASSERT(m_projectExplorer, return);
ProjectExplorer::SessionManager *session = m_projectExplorer->session(); ProjectExplorer::SessionManager *session = m_projectExplorer->session();
Q_ASSERT(session != 0); QTC_ASSERT(session, return);
connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)), connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(onProjectAdded(ProjectExplorer::Project*))); this, SLOT(onProjectAdded(ProjectExplorer::Project*)));
@@ -450,13 +475,26 @@ CppModelManager::CppModelManager(QObject *parent) :
CppModelManager::~CppModelManager() CppModelManager::~CppModelManager()
{ } { }
Document::Ptr CppModelManager::document(const QString &fileName) Document::Ptr CppModelManager::document(const QString &fileName) const
{ return m_documents.value(fileName); } { return m_documents.value(fileName); }
CppModelManager::DocumentTable CppModelManager::documents() CppModelManager::DocumentTable CppModelManager::documents() const
{ return m_documents; } { return m_documents; }
QStringList CppModelManager::updateProjectFiles() const void CppModelManager::ensureUpdated()
{
QMutexLocker locker(&mutex);
if (! m_dirty)
return;
m_projectFiles = internalProjectFiles();
m_includePaths = internalIncludePaths();
m_frameworkPaths = internalFrameworkPaths();
m_definedMacros = internalDefinedMacros();
m_dirty = false;
}
QStringList CppModelManager::internalProjectFiles() const
{ {
QStringList files; QStringList files;
QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects); QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
@@ -465,10 +503,11 @@ QStringList CppModelManager::updateProjectFiles() const
ProjectInfo pinfo = it.value(); ProjectInfo pinfo = it.value();
files += pinfo.sourceFiles; files += pinfo.sourceFiles;
} }
files.removeDuplicates();
return files; return files;
} }
QStringList CppModelManager::updateIncludePaths() const QStringList CppModelManager::internalIncludePaths() const
{ {
QStringList includePaths; QStringList includePaths;
QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects); QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
@@ -477,10 +516,11 @@ QStringList CppModelManager::updateIncludePaths() const
ProjectInfo pinfo = it.value(); ProjectInfo pinfo = it.value();
includePaths += pinfo.includePaths; includePaths += pinfo.includePaths;
} }
includePaths.removeDuplicates();
return includePaths; return includePaths;
} }
QStringList CppModelManager::updateFrameworkPaths() const QStringList CppModelManager::internalFrameworkPaths() const
{ {
QStringList frameworkPaths; QStringList frameworkPaths;
QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects); QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
@@ -489,10 +529,11 @@ QStringList CppModelManager::updateFrameworkPaths() const
ProjectInfo pinfo = it.value(); ProjectInfo pinfo = it.value();
frameworkPaths += pinfo.frameworkPaths; frameworkPaths += pinfo.frameworkPaths;
} }
frameworkPaths.removeDuplicates();
return frameworkPaths; return frameworkPaths;
} }
QByteArray CppModelManager::updateDefinedMacros() const QByteArray CppModelManager::internalDefinedMacros() const
{ {
QByteArray macros; QByteArray macros;
QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects); QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
@@ -527,8 +568,30 @@ QMap<QString, QByteArray> CppModelManager::buildWorkingCopyList()
void CppModelManager::updateSourceFiles(const QStringList &sourceFiles) void CppModelManager::updateSourceFiles(const QStringList &sourceFiles)
{ (void) refreshSourceFiles(sourceFiles); } { (void) refreshSourceFiles(sourceFiles); }
CppModelManager::ProjectInfo *CppModelManager::projectInfo(ProjectExplorer::Project *project) QList<CppModelManager::ProjectInfo> CppModelManager::projectInfos() const
{ return &m_projects[project]; } {
QMutexLocker locker(&mutex);
return m_projects.values();
}
CppModelManager::ProjectInfo CppModelManager::projectInfo(ProjectExplorer::Project *project) const
{
QMutexLocker locker(&mutex);
return m_projects.value(project, ProjectInfo(project));
}
void CppModelManager::updateProjectInfo(const ProjectInfo &pinfo)
{
QMutexLocker locker(&mutex);
if (! pinfo.isValid())
return;
m_projects.insert(pinfo.project, pinfo);
m_dirty = true;
}
QFuture<void> CppModelManager::refreshSourceFiles(const QStringList &sourceFiles) QFuture<void> CppModelManager::refreshSourceFiles(const QStringList &sourceFiles)
{ {
@@ -566,7 +629,7 @@ void CppModelManager::editorOpened(Core::IEditor *editor)
{ {
if (isCppEditor(editor)) { if (isCppEditor(editor)) {
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor); TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
Q_ASSERT(textEditor != 0); QTC_ASSERT(textEditor, return);
CppEditorSupport *editorSupport = new CppEditorSupport(this); CppEditorSupport *editorSupport = new CppEditorSupport(this);
editorSupport->setTextEditor(textEditor); editorSupport->setTextEditor(textEditor);
@@ -586,7 +649,7 @@ void CppModelManager::editorAboutToClose(Core::IEditor *editor)
{ {
if (isCppEditor(editor)) { if (isCppEditor(editor)) {
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor); TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
Q_ASSERT(textEditor != 0); QTC_ASSERT(textEditor, return);
CppEditorSupport *editorSupport = m_editorSupport.value(textEditor); CppEditorSupport *editorSupport = m_editorSupport.value(textEditor);
m_editorSupport.remove(textEditor); m_editorSupport.remove(textEditor);
@@ -683,7 +746,7 @@ void CppModelManager::onDocumentUpdated(Document::Ptr doc)
sel.cursor = c; sel.cursor = c;
selections.append(sel); selections.append(sel);
} }
ed->setExtraExtraSelections(selections); ed->setExtraSelections(TextEditor::BaseTextEditor::CodeWarningsSelection, selections);
break; break;
} }
} }
@@ -691,13 +754,18 @@ void CppModelManager::onDocumentUpdated(Document::Ptr doc)
void CppModelManager::onProjectAdded(ProjectExplorer::Project *) void CppModelManager::onProjectAdded(ProjectExplorer::Project *)
{ {
QMutexLocker locker(&mutex);
m_dirty = true; m_dirty = true;
} }
void CppModelManager::onAboutToRemoveProject(ProjectExplorer::Project *project) void CppModelManager::onAboutToRemoveProject(ProjectExplorer::Project *project)
{ {
do {
QMutexLocker locker(&mutex);
m_dirty = true; m_dirty = true;
m_projects.remove(project); m_projects.remove(project);
} while (0);
GC(); GC();
} }
@@ -705,15 +773,22 @@ void CppModelManager::onSessionUnloaded()
{ {
if (m_core->progressManager()) { if (m_core->progressManager()) {
m_core->progressManager()->cancelTasks(CppTools::Constants::TASK_INDEX); m_core->progressManager()->cancelTasks(CppTools::Constants::TASK_INDEX);
m_dirty = true;
} }
do {
QMutexLocker locker(&mutex);
m_projects.clear();
m_dirty = true;
} while (0);
GC();
} }
void CppModelManager::parse(QFutureInterface<void> &future, void CppModelManager::parse(QFutureInterface<void> &future,
CppPreprocessor *preproc, CppPreprocessor *preproc,
QStringList files) QStringList files)
{ {
Q_ASSERT(! files.isEmpty()); QTC_ASSERT(!files.isEmpty(), return);
// Change the priority of the background parser thread to idle. // Change the priority of the background parser thread to idle.
QThread::currentThread()->setPriority(QThread::IdlePriority); QThread::currentThread()->setPriority(QThread::IdlePriority);

View File

@@ -40,6 +40,7 @@
#include <QMap> #include <QMap>
#include <QFutureInterface> #include <QFutureInterface>
#include <QMutex>
namespace Core { namespace Core {
class ICore; class ICore;
@@ -70,9 +71,13 @@ public:
virtual ~CppModelManager(); virtual ~CppModelManager();
virtual void updateSourceFiles(const QStringList &sourceFiles); virtual void updateSourceFiles(const QStringList &sourceFiles);
virtual ProjectInfo *projectInfo(ProjectExplorer::Project *project);
virtual CPlusPlus::Document::Ptr document(const QString &fileName); virtual QList<ProjectInfo> projectInfos() const;
virtual DocumentTable documents(); virtual ProjectInfo projectInfo(ProjectExplorer::Project *project) const;
virtual void updateProjectInfo(const ProjectInfo &pinfo);
virtual CPlusPlus::Document::Ptr document(const QString &fileName) const;
virtual DocumentTable documents() const;
virtual void GC(); virtual void GC();
QFuture<void> refreshSourceFiles(const QStringList &sourceFiles); QFuture<void> refreshSourceFiles(const QStringList &sourceFiles);
@@ -127,21 +132,11 @@ private:
return m_definedMacros; return m_definedMacros;
} }
QStringList updateProjectFiles() const; void ensureUpdated();
QStringList updateIncludePaths() const; QStringList internalProjectFiles() const;
QStringList updateFrameworkPaths() const; QStringList internalIncludePaths() const;
QByteArray updateDefinedMacros() const; QStringList internalFrameworkPaths() const;
QByteArray internalDefinedMacros() const;
void ensureUpdated() {
if (! m_dirty)
return;
m_projectFiles = updateProjectFiles();
m_includePaths = updateIncludePaths();
m_frameworkPaths = updateFrameworkPaths();
m_definedMacros = updateDefinedMacros();
m_dirty = false;
}
static void parse(QFutureInterface<void> &future, static void parse(QFutureInterface<void> &future,
CppPreprocessor *preproc, CppPreprocessor *preproc,
@@ -166,6 +161,8 @@ private:
// project integration // project integration
QMap<ProjectExplorer::Project *, ProjectInfo> m_projects; QMap<ProjectExplorer::Project *, ProjectInfo> m_projects;
mutable QMutex mutex;
enum { enum {
MAX_SELECTION_COUNT = 5 MAX_SELECTION_COUNT = 5
}; };

View File

@@ -38,6 +38,7 @@
#include <cplusplus/CppDocument.h> #include <cplusplus/CppDocument.h>
#include <QtCore/QObject> #include <QtCore/QObject>
#include <QtCore/QMap> #include <QtCore/QMap>
#include <QtCore/QPointer>
namespace ProjectExplorer { namespace ProjectExplorer {
class Project; class Project;
@@ -51,10 +52,29 @@ class CPPTOOLS_EXPORT CppModelManagerInterface
Q_OBJECT Q_OBJECT
public: public:
typedef QMap<QString, CPlusPlus::Document::Ptr> DocumentTable; typedef QMap<QString, CPlusPlus::Document::Ptr> DocumentTable; // ### remove me
struct ProjectInfo class ProjectInfo
{ {
public:
ProjectInfo()
{ }
ProjectInfo(QPointer<ProjectExplorer::Project> project)
: project(project)
{ }
operator bool() const
{ return ! project.isNull(); }
bool isValid() const
{ return ! project.isNull(); }
bool isNull() const
{ return project.isNull(); }
public: // attributes
QPointer<ProjectExplorer::Project> project;
QString projectPath; QString projectPath;
QByteArray defines; QByteArray defines;
QStringList sourceFiles; QStringList sourceFiles;
@@ -69,10 +89,12 @@ public:
virtual void GC() = 0; virtual void GC() = 0;
virtual void updateSourceFiles(const QStringList &sourceFiles) = 0; virtual void updateSourceFiles(const QStringList &sourceFiles) = 0;
virtual CPlusPlus::Document::Ptr document(const QString &fileName) = 0; virtual CPlusPlus::Document::Ptr document(const QString &fileName) const = 0;
virtual DocumentTable documents() = 0; virtual DocumentTable documents() const = 0;
virtual ProjectInfo *projectInfo(ProjectExplorer::Project *project) = 0; virtual QList<ProjectInfo> projectInfos() const = 0;
virtual ProjectInfo projectInfo(ProjectExplorer::Project *project) const = 0;
virtual void updateProjectInfo(const ProjectInfo &pinfo) = 0;
}; };
} // namespace CppTools } // namespace CppTools

View File

@@ -75,6 +75,12 @@ void CppQuickOpenFilter::refresh(QFutureInterface<void> &future)
Q_UNUSED(future); Q_UNUSED(future);
} }
static bool compareLexigraphically(const QuickOpen::FilterEntry &a,
const QuickOpen::FilterEntry &b)
{
return a.displayName < b.displayName;
}
QList<QuickOpen::FilterEntry> CppQuickOpenFilter::matchesFor(const QString &origEntry) QList<QuickOpen::FilterEntry> CppQuickOpenFilter::matchesFor(const QString &origEntry)
{ {
QString entry = trimWildcards(origEntry); QString entry = trimWildcards(origEntry);
@@ -109,6 +115,9 @@ QList<QuickOpen::FilterEntry> CppQuickOpenFilter::matchesFor(const QString &orig
} }
} }
if (entries.size() < 1000)
qSort(entries.begin(), entries.end(), compareLexigraphically);
return entries; return entries;
} }

View File

@@ -34,6 +34,7 @@
#include "cpptools.h" #include "cpptools.h"
#include "cppclassesfilter.h" #include "cppclassesfilter.h"
#include "cppcodecompletion.h" #include "cppcodecompletion.h"
#include "cppfunctionsfilter.h"
#include "cpphoverhandler.h" #include "cpphoverhandler.h"
#include "cppmodelmanager.h" #include "cppmodelmanager.h"
#include "cpptoolsconstants.h" #include "cpptoolsconstants.h"
@@ -89,6 +90,7 @@ bool CppToolsPlugin::initialize(const QStringList & /*arguments*/, QString *)
m_core->editorManager()); m_core->editorManager());
addAutoReleasedObject(quickOpenFilter); addAutoReleasedObject(quickOpenFilter);
addAutoReleasedObject(new CppClassesFilter(m_modelManager, m_core->editorManager())); addAutoReleasedObject(new CppClassesFilter(m_modelManager, m_core->editorManager()));
addAutoReleasedObject(new CppFunctionsFilter(m_modelManager, m_core->editorManager()));
// Menus // Menus
Core::IActionContainer *mtools = am->actionContainer(Core::Constants::M_TOOLS); Core::IActionContainer *mtools = am->actionContainer(Core::Constants::M_TOOLS);

View File

@@ -10,15 +10,16 @@ unix:QMAKE_CXXFLAGS_DEBUG += -O3
INCLUDEPATH += . INCLUDEPATH += .
DEFINES += CPPTOOLS_LIBRARY DEFINES += CPPTOOLS_LIBRARY
CONFIG += help CONFIG += help
include(rpp/rpp.pri)|error("Can't find RPP")
HEADERS += cpptools_global.h \ HEADERS += cpptools_global.h \
cppquickopenfilter.h \ cppquickopenfilter.h \
cppclassesfilter.h \ cppclassesfilter.h \
searchsymbols.h searchsymbols.h \
cppfunctionsfilter.h
SOURCES += cppquickopenfilter.cpp \ SOURCES += cppquickopenfilter.cpp \
cpptoolseditorsupport.cpp \ cpptoolseditorsupport.cpp \
cppclassesfilter.cpp \ cppclassesfilter.cpp \
searchsymbols.cpp searchsymbols.cpp \
cppfunctionsfilter.cpp
# Input # Input
SOURCES += cpptools.cpp \ SOURCES += cpptools.cpp \

Some files were not shown because too many files have changed in this diff Show More