externaltool.cpp 32.7 KB
Newer Older
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
7
8
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
con's avatar
con committed
9
** No Commercial Usage
10
**
con's avatar
con committed
11
12
13
14
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
15
16
17
18
19
20
21
22
23
24
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
con's avatar
con committed
25
26
27
28
29
30
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
31
32
33
34
**
**************************************************************************/

#include "externaltool.h"
con's avatar
con committed
35
#include "actionmanager/actionmanager.h"
36
#include "coreconstants.h"
con's avatar
con committed
37
38
39
40
#include "variablemanager.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
41
42
43
#include <coreplugin/filemanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
con's avatar
con committed
44
45
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
46
#include <utils/environment.h>
47
48

#include <QtCore/QXmlStreamReader>
49
#include <QtCore/QXmlStreamWriter>
50
51
#include <QtCore/QDir>
#include <QtCore/QFile>
52
#include <QtCore/QDateTime>
53
54
#include <QtGui/QMenu>
#include <QtGui/QAction>
55
56
57

#include <QtDebug>

58
using namespace Core;
59
60
61
62
using namespace Core::Internal;

namespace {
    const char * const kExternalTool = "externaltool";
63
    const char * const kId = "id";
64
65
66
67
68
69
70
    const char * const kDescription = "description";
    const char * const kDisplayName = "displayname";
    const char * const kCategory = "category";
    const char * const kOrder = "order";
    const char * const kExecutable = "executable";
    const char * const kPath = "path";
    const char * const kArguments = "arguments";
71
    const char * const kInput = "input";
72
73
74
75
    const char * const kWorkingDirectory = "workingdirectory";

    const char * const kXmlLang = "xml:lang";
    const char * const kOutput = "output";
con's avatar
con committed
76
    const char * const kError = "error";
77
78
    const char * const kOutputShowInPane = "showinpane";
    const char * const kOutputReplaceSelection = "replaceselection";
con's avatar
con committed
79
    const char * const kOutputIgnore = "ignore";
80
81
82
83
84
    const char * const kModifiesDocument = "modifiesdocument";
    const char * const kYes = "yes";
    const char * const kNo = "no";
    const char * const kTrue= "true";
    const char * const kFalse = "false";
85
86

    const char * const kSpecialUncategorizedSetting = "SpecialEmptyCategoryForUncategorizedTools";
87
88
}

89
90
// #pragma mark -- ExternalTool

91
ExternalTool::ExternalTool() :
92
    m_displayCategory(QLatin1String("")), // difference between isNull and isEmpty
93
    m_order(-1),
con's avatar
con committed
94
    m_outputHandling(ShowInPane),
95
    m_errorHandling(ShowInPane),
96
    m_modifiesCurrentDocument(false)
97
98
99
{
}

100
101
102
103
104
105
106
107
108
109
110
ExternalTool::ExternalTool(const ExternalTool *other)
    : m_id(other->m_id),
      m_description(other->m_description),
      m_displayName(other->m_displayName),
      m_displayCategory(other->m_displayCategory),
      m_order(other->m_order),
      m_executables(other->m_executables),
      m_arguments(other->m_arguments),
      m_input(other->m_input),
      m_workingDirectory(other->m_workingDirectory),
      m_outputHandling(other->m_outputHandling),
111
      m_errorHandling(other->m_errorHandling),
112
      m_modifiesCurrentDocument(other->m_modifiesCurrentDocument),
113
      m_fileName(other->m_fileName),
114
      m_presetTool(other->m_presetTool)
115
116
117
{
}

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
ExternalTool &ExternalTool::operator=(const ExternalTool &other)
{
    m_id = other.m_id;
    m_description = other.m_description;
    m_displayName = other.m_displayName;
    m_displayCategory = other.m_displayCategory;
    m_order = other.m_order;
    m_executables = other.m_executables;
    m_arguments = other.m_arguments;
    m_input = other.m_input;
    m_workingDirectory = other.m_workingDirectory;
    m_outputHandling = other.m_outputHandling;
    m_errorHandling = other.m_errorHandling;
    m_modifiesCurrentDocument = other.m_modifiesCurrentDocument;
    m_fileName = other.m_fileName;
    m_presetTool = other.m_presetTool;
134
    return *this;
135
136
}

con's avatar
con committed
137
138
139
140
ExternalTool::~ExternalTool()
{
}

141
142
143
144
145
QString ExternalTool::id() const
{
    return m_id;
}

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
QString ExternalTool::description() const
{
    return m_description;
}

QString ExternalTool::displayName() const
{
    return m_displayName;
}

QString ExternalTool::displayCategory() const
{
    return m_displayCategory;
}

int ExternalTool::order() const
{
    return m_order;
}

QStringList ExternalTool::executables() const
{
    return m_executables;
}

QString ExternalTool::arguments() const
{
    return m_arguments;
}

176
177
178
179
180
QString ExternalTool::input() const
{
    return m_input;
}

181
182
183
184
185
186
187
188
189
190
QString ExternalTool::workingDirectory() const
{
    return m_workingDirectory;
}

ExternalTool::OutputHandling ExternalTool::outputHandling() const
{
    return m_outputHandling;
}

con's avatar
con committed
191
192
193
194
195
ExternalTool::OutputHandling ExternalTool::errorHandling() const
{
    return m_errorHandling;
}

196
197
198
199
200
bool ExternalTool::modifiesCurrentDocument() const
{
    return m_modifiesCurrentDocument;
}

201
202
203
204
205
void ExternalTool::setFileName(const QString &fileName)
{
    m_fileName = fileName;
}

206
void ExternalTool::setPreset(QSharedPointer<ExternalTool> preset)
207
{
208
    m_presetTool = preset;
209
210
211
212
213
214
215
}

QString ExternalTool::fileName() const
{
    return m_fileName;
}

216
QSharedPointer<ExternalTool> ExternalTool::preset() const
217
{
218
    return m_presetTool;
219
220
}

con's avatar
con committed
221
222
223
224
225
void ExternalTool::setId(const QString &id)
{
    m_id = id;
}

226
void ExternalTool::setDisplayCategory(const QString &category)
con's avatar
con committed
227
228
229
230
{
    m_displayCategory = category;
}

231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
void ExternalTool::setDisplayName(const QString &name)
{
    m_displayName = name;
}

void ExternalTool::setDescription(const QString &description)
{
    m_description = description;
}


void ExternalTool::setOutputHandling(OutputHandling handling)
{
    m_outputHandling = handling;
}


void ExternalTool::setErrorHandling(OutputHandling handling)
{
    m_errorHandling = handling;
}


void ExternalTool::setModifiesCurrentDocument(bool modifies)
{
    m_modifiesCurrentDocument = modifies;
}


void ExternalTool::setExecutables(const QStringList &executables)
{
    m_executables = executables;
}


void ExternalTool::setArguments(const QString &arguments)
{
    m_arguments = arguments;
}


void ExternalTool::setInput(const QString &input)
{
    m_input = input;
}


void ExternalTool::setWorkingDirectory(const QString &workingDirectory)
{
    m_workingDirectory = workingDirectory;
}

283
static QStringList splitLocale(const QString &locale)
284
{
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    QString value = locale;
    QStringList values;
    if (!value.isEmpty())
        values << value;
    int index = value.indexOf(QLatin1Char('.'));
    if (index >= 0) {
        value = value.left(index);
        if (!value.isEmpty())
            values << value;
    }
    index = value.indexOf(QLatin1Char('_'));
    if (index >= 0) {
        value = value.left(index);
        if (!value.isEmpty())
            values << value;
    }
    return values;
}

static void localizedText(const QStringList &locales, QXmlStreamReader *reader, int *currentLocale, QString *currentText)
{
    Q_ASSERT(reader);
    Q_ASSERT(currentLocale);
    Q_ASSERT(currentText);
    if (reader->attributes().hasAttribute(QLatin1String(kXmlLang))) {
        int index = locales.indexOf(reader->attributes().value(QLatin1String(kXmlLang)).toString());
        if (index >= 0 && (index < *currentLocale || *currentLocale < 0)) {
            *currentText = reader->readElementText();
            *currentLocale = index;
        } else {
            reader->skipCurrentElement();
        }
    } else {
        if (*currentLocale < 0 && currentText->isEmpty()) {
            *currentText = reader->readElementText();
        } else {
            reader->skipCurrentElement();
        }
    }
324
325
    if (currentText->isNull()) // prefer isEmpty over isNull
        *currentText = QLatin1String("");
326
327
}

con's avatar
con committed
328
329
330
331
332
333
334
335
336
337
static bool parseOutputAttribute(const QString &attribute, QXmlStreamReader *reader, ExternalTool::OutputHandling *value)
{
    const QString output = reader->attributes().value(attribute).toString();
    if (output == QLatin1String(kOutputShowInPane)) {
        *value = ExternalTool::ShowInPane;
    } else if (output == QLatin1String(kOutputReplaceSelection)) {
        *value = ExternalTool::ReplaceSelection;
    } else if (output == QLatin1String(kOutputIgnore)) {
        *value = ExternalTool::Ignore;
    } else {
338
        reader->raiseError(QLatin1String("Allowed values for output attribute are 'showinpane','replaceselection','ignore'"));
con's avatar
con committed
339
340
341
342
343
        return false;
    }
    return true;
}

344
ExternalTool * ExternalTool::createFromXml(const QByteArray &xml, QString *errorMessage, const QString &locale)
345
346
347
348
349
{
    int descriptionLocale = -1;
    int nameLocale = -1;
    int categoryLocale = -1;
    const QStringList &locales = splitLocale(locale);
350
351
    ExternalTool *tool = new ExternalTool;
    QXmlStreamReader reader(xml);
352

353
354
    if (!reader.readNextStartElement() || reader.name() != QLatin1String(kExternalTool))
        reader.raiseError(QLatin1String("Missing start element <externaltool>"));
355
    tool->m_id = reader.attributes().value(QLatin1String(kId)).toString();
356
357
    if (tool->m_id.isEmpty())
        reader.raiseError(QLatin1String("Missing or empty id attribute for <externaltool>"));
358
359
    while (reader.readNextStartElement()) {
        if (reader.name() == QLatin1String(kDescription)) {
360
            localizedText(locales, &reader, &descriptionLocale, &tool->m_description);
361
        } else if (reader.name() == QLatin1String(kDisplayName)) {
362
            localizedText(locales, &reader, &nameLocale, &tool->m_displayName);
363
        } else if (reader.name() == QLatin1String(kCategory)) {
364
            localizedText(locales, &reader, &categoryLocale, &tool->m_displayCategory);
365
366
367
368
369
370
371
372
373
374
375
        } else if (reader.name() == QLatin1String(kOrder)) {
            if (tool->m_order >= 0) {
                reader.raiseError(QLatin1String("only one <order> element allowed"));
                break;
            }
            bool ok;
            tool->m_order = reader.readElementText().toInt(&ok);
            if (!ok || tool->m_order < 0)
                reader.raiseError(QLatin1String("<order> element requires non-negative integer value"));
        } else if (reader.name() == QLatin1String(kExecutable)) {
            if (reader.attributes().hasAttribute(QLatin1String(kOutput))) {
con's avatar
con committed
376
377
378
379
380
                if (!parseOutputAttribute(QLatin1String(kOutput), &reader, &tool->m_outputHandling))
                    break;
            }
            if (reader.attributes().hasAttribute(QLatin1String(kError))) {
                if (!parseOutputAttribute(QLatin1String(kError), &reader, &tool->m_errorHandling))
381
382
                    break;
            }
383
384
385
386
387
388
389
390
391
392
393
            if (reader.attributes().hasAttribute(QLatin1String(kModifiesDocument))) {
                const QString &value = reader.attributes().value(QLatin1String(kModifiesDocument)).toString();
                if (value == QLatin1String(kYes) || value == QLatin1String(kTrue)) {
                    tool->m_modifiesCurrentDocument = true;
                } else if (value == QLatin1String(kNo) || value == QLatin1String(kFalse)) {
                    tool->m_modifiesCurrentDocument = false;
                } else {
                    reader.raiseError(QLatin1String("Allowed values for modifiesdocument attribute are 'yes','true','no','false'"));
                    break;
                }
            }
394
395
396
397
398
399
400
401
402
            while (reader.readNextStartElement()) {
                if (reader.name() == QLatin1String(kPath)) {
                    tool->m_executables.append(reader.readElementText());
                } else if (reader.name() == QLatin1String(kArguments)) {
                    if (!tool->m_arguments.isEmpty()) {
                        reader.raiseError(QLatin1String("only one <arguments> element allowed"));
                        break;
                    }
                    tool->m_arguments = reader.readElementText();
403
404
405
406
407
408
                } else if (reader.name() == QLatin1String(kInput)) {
                    if (!tool->m_input.isEmpty()) {
                        reader.raiseError(QLatin1String("only one <input> element allowed"));
                        break;
                    }
                    tool->m_input = reader.readElementText();
409
410
411
412
413
414
                } else if (reader.name() == QLatin1String(kWorkingDirectory)) {
                    if (!tool->m_workingDirectory.isEmpty()) {
                        reader.raiseError(QLatin1String("only one <workingdirectory> element allowed"));
                        break;
                    }
                    tool->m_workingDirectory = reader.readElementText();
con's avatar
con committed
415
416
417
418
                } else {
                    reader.raiseError(QString::fromLatin1("Unknown element <%1> as subelement of <%2>").arg(
                                          reader.qualifiedName().toString(), QLatin1String(kExecutable)));
                    break;
419
420
421
422
423
424
425
426
427
428
429
430
431
432
                }
            }
        } else {
            reader.raiseError(QString::fromLatin1("Unknown element <%1>").arg(reader.qualifiedName().toString()));
        }
    }
    if (reader.hasError()) {
        if (errorMessage)
            *errorMessage = reader.errorString();
        delete tool;
        return 0;
    }
    return tool;
}
433

434
ExternalTool * ExternalTool::createFromFile(const QString &fileName, QString *errorMessage, const QString &locale)
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
{
    QFileInfo info(fileName);
    QFile file(info.absoluteFilePath());
    if (!file.open(QIODevice::ReadOnly)) {
        if (errorMessage)
            *errorMessage = tr("Could not open tool specification %1 for reading").arg(fileName);
        return 0;
    }
    const QByteArray &bytes = file.readAll();
    file.close();
    ExternalTool *tool = ExternalTool::createFromXml(bytes, errorMessage, locale);
    if (!tool) {
        return 0;
    }
    tool->m_fileName = file.fileName();
    return tool;
}

static QLatin1String stringForOutputHandling(ExternalTool::OutputHandling handling)
{
    switch (handling) {
    case Core::Internal::ExternalTool::Ignore:
        return QLatin1String(kOutputIgnore);
    case Core::Internal::ExternalTool::ShowInPane:
        return QLatin1String(kOutputShowInPane);
    case Core::Internal::ExternalTool::ReplaceSelection:
        return QLatin1String(kOutputReplaceSelection);
    }
    return QLatin1String("");
}

bool ExternalTool::save(QString *errorMessage) const
{
    if (m_fileName.isEmpty())
        return false;
    QFile file(m_fileName);
    if (!file.open(QIODevice::WriteOnly)) {
        if (errorMessage)
            *errorMessage = tr("Could not write tool specification %1").arg(m_fileName);
        return false;
    }
    QXmlStreamWriter out(&file);
    out.setAutoFormatting(true);
    out.writeStartDocument(QLatin1String("1.0"));
    out.writeComment(QString::fromLatin1("Written on %1 by Qt Creator %2")
                     .arg(QDateTime::currentDateTime().toString(), QLatin1String(Constants::IDE_VERSION_LONG)));
    out.writeStartElement(QLatin1String(kExternalTool));
    out.writeAttribute(QLatin1String(kId), m_id);
    out.writeTextElement(QLatin1String(kDescription), m_description);
    out.writeTextElement(QLatin1String(kDisplayName), m_displayName);
    out.writeTextElement(QLatin1String(kCategory), m_displayCategory);
    if (m_order != -1)
        out.writeTextElement(QLatin1String(kOrder), QString::number(m_order));

    out.writeStartElement(QLatin1String(kExecutable));
    out.writeAttribute(QLatin1String(kOutput), stringForOutputHandling(m_outputHandling));
    out.writeAttribute(QLatin1String(kError), stringForOutputHandling(m_errorHandling));
    out.writeAttribute(QLatin1String(kModifiesDocument), m_modifiesCurrentDocument ? QLatin1String(kYes) : QLatin1String(kNo));
    foreach (const QString &executable, m_executables)
        out.writeTextElement(QLatin1String(kPath), executable);
    if (!m_arguments.isEmpty())
        out.writeTextElement(QLatin1String(kArguments), m_arguments);
    if (!m_input.isEmpty())
        out.writeTextElement(QLatin1String(kInput), m_input);
    if (!m_workingDirectory.isEmpty())
        out.writeTextElement(QLatin1String(kWorkingDirectory), m_workingDirectory);
    out.writeEndElement();

    out.writeEndDocument();
    file.close();
505
    return true;
506
507
}

508
bool ExternalTool::operator==(const ExternalTool &other) const
509
510
511
512
513
514
515
516
517
518
519
{
    return m_id == other.m_id
            && m_description == other.m_description
            && m_displayName == other.m_displayName
            && m_displayCategory == other.m_displayCategory
            && m_order == other.m_order
            && m_executables == other.m_executables
            && m_arguments == other.m_arguments
            && m_input == other.m_input
            && m_workingDirectory == other.m_workingDirectory
            && m_outputHandling == other.m_outputHandling
520
            && m_modifiesCurrentDocument == other.m_modifiesCurrentDocument
521
522
            && m_errorHandling == other.m_errorHandling
            && m_fileName == other.m_fileName;
523
524
}

con's avatar
con committed
525
526
527
// #pragma mark -- ExternalToolRunner

ExternalToolRunner::ExternalToolRunner(const ExternalTool *tool)
528
    : m_tool(new ExternalTool(tool)),
con's avatar
con committed
529
530
531
532
533
534
      m_process(0),
      m_outputCodec(QTextCodec::codecForLocale())
{
    run();
}

535
536
537
538
539
540
ExternalToolRunner::~ExternalToolRunner()
{
    if (m_tool)
        delete m_tool;
}

con's avatar
con committed
541
542
543
544
bool ExternalToolRunner::resolve()
{
    if (!m_tool)
        return false;
545
546
547
    m_resolvedExecutable.clear();
    m_resolvedArguments.clear();
    m_resolvedWorkingDirectory.clear();
con's avatar
con committed
548
549
550
551
    { // executable
        foreach (const QString &executable, m_tool->executables()) {
            QString resolved = Utils::expandMacros(executable,
                                                   Core::VariableManager::instance()->macroExpander());
552
553
            m_resolvedExecutable =
                    Utils::Environment::systemEnvironment().searchInPath(resolved);
con's avatar
con committed
554
        }
555
        if (m_resolvedExecutable.isEmpty())
con's avatar
con committed
556
557
558
            return false;
    }
    { // arguments
559
        m_resolvedArguments = Utils::expandMacros(m_tool->arguments(),
con's avatar
con committed
560
561
                                               Core::VariableManager::instance()->macroExpander());
    }
562
563
564
565
    { // input
        m_resolvedInput = Utils::expandMacros(m_tool->input(),
                                              Core::VariableManager::instance()->macroExpander());
    }
con's avatar
con committed
566
567
568
569
570
571
572
573
574
575
576
577
578
    { // working directory
        m_resolvedWorkingDirectory = Utils::expandMacros(m_tool->workingDirectory(),
                                               Core::VariableManager::instance()->macroExpander());
    }
    return true;
}

void ExternalToolRunner::run()
{
    if (!resolve()) {
        deleteLater();
        return;
    }
579
    if (m_tool->modifiesCurrentDocument()) {
580
581
        if (IEditor *editor = EditorManager::instance()->currentEditor()) {
            m_expectedFileName = editor->file()->fileName();
582
583
584
585
586
587
            bool cancelled = false;
            FileManager::instance()->saveModifiedFiles(QList<IFile *>() << editor->file(), &cancelled);
            if (cancelled) {
                deleteLater();
                return;
            }
588
589
            FileManager::instance()->expectFileChange(m_expectedFileName);
        }
590
    }
591
    m_process = new Utils::QtcProcess(this);
592
    connect(m_process, SIGNAL(started()), this, SLOT(started()));
593
    connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus)));
con's avatar
con committed
594
595
596
597
598
    connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
    connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
    connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));
    if (!m_resolvedWorkingDirectory.isEmpty())
        m_process->setWorkingDirectory(m_resolvedWorkingDirectory);
599
    m_process->setCommand(m_resolvedExecutable, m_resolvedArguments);
600
601
    ICore::instance()->messageManager()->printToOutputPane(
                tr("Starting external tool '%1'").arg(m_resolvedExecutable), false);
602
603
604
605
606
    if (!m_resolvedArguments.isEmpty()) {
        ICore::instance()->messageManager()->printToOutputPane(
                tr("with arguments '%1'").arg(m_resolvedArguments), false);
    }
    m_process->start();
607
608
609
610
611
612
613
614
}

void ExternalToolRunner::started()
{
    if (!m_resolvedInput.isEmpty()) {
        m_process->write(m_resolvedInput.toLocal8Bit());
    }
    m_process->closeWriteChannel();
con's avatar
con committed
615
616
}

617
void ExternalToolRunner::finished(int exitCode, QProcess::ExitStatus status)
con's avatar
con committed
618
{
619
620
621
622
    if (status == QProcess::NormalExit && exitCode == 0) {
        if (m_tool->outputHandling() == ExternalTool::ReplaceSelection
                || m_tool->errorHandling() == ExternalTool::ReplaceSelection) {
            emit ExternalToolManager::instance()->replaceSelectionRequested(m_processOutput);
623
624
        }
        if (m_tool->modifiesCurrentDocument()) {
625
626
            FileManager::instance()->unexpectFileChange(m_expectedFileName);
        }
627
    }
628
629
    ICore::instance()->messageManager()->printToOutputPane(
                tr("'%1' finished").arg(m_resolvedExecutable), false);
con's avatar
con committed
630
631
632
633
634
    deleteLater();
}

void ExternalToolRunner::error(QProcess::ProcessError error)
{
635
    if (m_tool->modifiesCurrentDocument()) {
636
637
        FileManager::instance()->unexpectFileChange(m_expectedFileName);
    }
con's avatar
con committed
638
639
640
641
642
643
    // TODO inform about errors
    deleteLater();
}

void ExternalToolRunner::readStandardOutput()
{
con's avatar
con committed
644
645
    if (m_tool->outputHandling() == ExternalTool::Ignore)
        return;
con's avatar
con committed
646
647
648
649
    QByteArray data = m_process->readAllStandardOutput();
    QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_outputCodecState);
    if (m_tool->outputHandling() == ExternalTool::ShowInPane) {
        ICore::instance()->messageManager()->printToOutputPane(output, true);
650
651
    } else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection) {
        m_processOutput.append(output);
con's avatar
con committed
652
653
654
655
656
    }
}

void ExternalToolRunner::readStandardError()
{
con's avatar
con committed
657
658
    if (m_tool->errorHandling() == ExternalTool::Ignore)
        return;
con's avatar
con committed
659
660
    QByteArray data = m_process->readAllStandardError();
    QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_errorCodecState);
con's avatar
con committed
661
    if (m_tool->errorHandling() == ExternalTool::ShowInPane) {
con's avatar
con committed
662
        ICore::instance()->messageManager()->printToOutputPane(output, true);
663
664
    } else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection) {
        m_processOutput.append(output);
con's avatar
con committed
665
666
667
    }
}

668
669
// #pragma mark -- ExternalToolManager

670
671
ExternalToolManager *ExternalToolManager::m_instance = 0;

672
673
674
ExternalToolManager::ExternalToolManager(Core::ICore *core)
    : QObject(core), m_core(core)
{
675
    m_instance = this;
676
677
678
679
680
    initialize();
}

ExternalToolManager::~ExternalToolManager()
{
681
    writeSettings();
con's avatar
con committed
682
    // TODO kill running tools
683
684
685
686
687
    qDeleteAll(m_tools);
}

void ExternalToolManager::initialize()
{
688
689
690
691
692
    m_configureSeparator = new QAction(this);
    m_configureSeparator->setSeparator(true);
    m_configureAction = new QAction(tr("Configure..."), this);
    connect(m_configureAction, SIGNAL(triggered()), this, SLOT(openPreferences()));

693
    // add the external tools menu
694
695
696
697
698
699
    ActionManager *am = m_core->actionManager();
    ActionContainer *mexternaltools = am->createMenu(Id(Constants::M_TOOLS_EXTERNAL));
    mexternaltools->menu()->setTitle(tr("External"));
    ActionContainer *mtools = am->actionContainer(Constants::M_TOOLS);
    mtools->addMenu(mexternaltools, Constants::G_DEFAULT_THREE);

700
701
    QMap<QString, QMultiMap<int, ExternalTool*> > categoryPriorityMap;
    QMap<QString, ExternalTool *> tools;
702
    parseDirectory(m_core->userResourcePath() + QLatin1String("/externaltools"),
703
704
                   &categoryPriorityMap,
                   &tools);
705
    parseDirectory(m_core->resourcePath() + QLatin1String("/externaltools"),
706
707
708
                   &categoryPriorityMap,
                   &tools,
                   true);
709

710
711
    QMap<QString, QList<Internal::ExternalTool *> > categoryMap;
    QMapIterator<QString, QMultiMap<int, ExternalTool*> > it(categoryPriorityMap);
712
713
    while (it.hasNext()) {
        it.next();
714
        categoryMap.insert(it.key(), it.value().values());
715
    }
716

con's avatar
con committed
717
718
    // read renamed categories and custom order
    readSettings(tools, &categoryMap);
719
    setToolsByCategory(categoryMap);
720
721
}

722
723
724
void ExternalToolManager::parseDirectory(const QString &directory,
                                         QMap<QString, QMultiMap<int, Internal::ExternalTool*> > *categoryMenus,
                                         QMap<QString, ExternalTool *> *tools,
725
                                         bool isPreset)
726
727
{
    QTC_ASSERT(categoryMenus, return);
728
    QTC_ASSERT(tools, return);
729
    QDir dir(directory, QLatin1String("*.xml"), QDir::Unsorted, QDir::Files | QDir::Readable);
730
    foreach (const QFileInfo &info, dir.entryInfoList()) {
731
732
        const QString &fileName = info.absoluteFilePath();
        QString error;
733
        ExternalTool *tool = ExternalTool::createFromFile(fileName, &error, m_core->userInterfaceLanguage());
734
735
736
737
738
739
        if (!tool) {
            qWarning() << tr("Error while parsing external tool %1: %2").arg(fileName, error);
            continue;
        }
        if (tools->contains(tool->id())) {
            if (isPreset) {
740
                // preset that was changed
741
                ExternalTool *other = tools->value(tool->id());
742
                other->setPreset(QSharedPointer<ExternalTool>(tool));
743
744
            } else {
                qWarning() << tr("Error: External tool in %1 has duplicate id").arg(fileName);
745
                delete tool;
746
            }
747
            continue;
con's avatar
con committed
748
        }
749
750
751
752
        if (isPreset) {
            // preset that wasn't changed --> save original values
            tool->setPreset(QSharedPointer<ExternalTool>(new ExternalTool(tool)));
        }
753
754
        tools->insert(tool->id(), tool);
        (*categoryMenus)[tool->displayCategory()].insert(tool->order(), tool);
con's avatar
con committed
755
    }
756
757
758
759
}

void ExternalToolManager::menuActivated()
{
con's avatar
con committed
760
761
762
763
764
    QAction *action = qobject_cast<QAction *>(sender());
    QTC_ASSERT(action, return);
    ExternalTool *tool = m_tools.value(action->data().toString());
    QTC_ASSERT(tool, return);
    new ExternalToolRunner(tool);
765
}
766

767
QMap<QString, QList<Internal::ExternalTool *> > ExternalToolManager::toolsByCategory() const
768
769
770
771
{
    return m_categoryMap;
}

772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
QMap<QString, ExternalTool *> ExternalToolManager::toolsById() const
{
    return m_tools;
}

void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal::ExternalTool *> > &tools)
{
    // clear menu
    ActionManager *am = m_core->actionManager();
    ActionContainer *mexternaltools = am->actionContainer(Id(Constants::M_TOOLS_EXTERNAL));
    mexternaltools->clear();

    // delete old tools and create list of new ones
    QMap<QString, ExternalTool *> newTools;
    QMap<QString, QAction *> newActions;
    QMapIterator<QString, QList<ExternalTool *> > it(tools);
    while (it.hasNext()) {
        it.next();
        foreach (ExternalTool *tool, it.value()) {
            const QString &id = tool->id();
            if (m_tools.value(id) == tool) {
                newActions.insert(id, m_actions.value(id));
                // remove from list to prevent deletion
                m_tools.remove(id);
                m_actions.remove(id);
            }
            newTools.insert(id, tool);
        }
    }
    qDeleteAll(m_tools);
    QMapIterator<QString, QAction *> remainingActions(m_actions);
    while (remainingActions.hasNext()) {
        remainingActions.next();
        am->unregisterAction(remainingActions.value(), Id("Tools.External." + remainingActions.key()));
        delete remainingActions.value();
    }
    m_actions.clear();
    // assign the new stuff
    m_tools = newTools;
    m_actions = newActions;
    m_categoryMap = tools;
    // create menu structure and remove no-longer used containers
    // add all the category menus, QMap is nicely sorted
    QMap<QString, ActionContainer *> newContainers;
    it.toFront();
    while (it.hasNext()) {
        it.next();
        ActionContainer *container = 0;
        const QString &containerName = it.key();
821
        if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
            container = mexternaltools;
        } else {
            if (m_containers.contains(containerName)) {
                container = m_containers.take(containerName); // remove to avoid deletion below
            } else {
                container = am->createMenu(Id("Tools.External.Category." + containerName));
            }
            newContainers.insert(containerName, container);
            mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE);
            container->menu()->setTitle(containerName);
        }
        foreach (ExternalTool *tool, it.value()) {
            const QString &toolId = tool->id();
            // tool action and command
            QAction *action = 0;
            Command *command = 0;
            if (m_actions.contains(toolId)) {
                action = m_actions.value(toolId);
                command = am->command(Id("Tools.External." + toolId));
            } else {
                action = new QAction(tool->displayName(), this);
                action->setData(toolId);
                m_actions.insert(toolId, action);
                connect(action, SIGNAL(triggered()), this, SLOT(menuActivated()));
                command = am->registerAction(action, Id("Tools.External." + toolId), Context(Constants::C_GLOBAL));
                command->setAttribute(Command::CA_UpdateText);
            }
            action->setText(tool->displayName());
            action->setToolTip(tool->description());
            action->setWhatsThis(tool->description());
            container->addAction(command, Constants::G_DEFAULT_TWO);
        }
    }

    // delete the unused containers
    qDeleteAll(m_containers);
    // remember the new containers
    m_containers = newContainers;
860
861
862
863

    // (re)add the configure menu item
    mexternaltools->menu()->addAction(m_configureSeparator);
    mexternaltools->menu()->addAction(m_configureAction);
864
865
866
}

void ExternalToolManager::readSettings(const QMap<QString, ExternalTool *> &tools,
con's avatar
con committed
867
                                       QMap<QString, QList<ExternalTool *> > *categoryMap)
868
869
870
871
{
    QSettings *settings = m_core->settings();
    settings->beginGroup(QLatin1String("ExternalTools"));

con's avatar
con committed
872
    if (categoryMap) {
873
        settings->beginGroup(QLatin1String("OverrideCategories"));
874
875
876
877
878
        foreach (const QString &settingsCategory, settings->childGroups()) {
            QString displayCategory = settingsCategory;
            if (displayCategory == QLatin1String(kSpecialUncategorizedSetting))
                displayCategory = QLatin1String("");
            int count = settings->beginReadArray(settingsCategory);
con's avatar
con committed
879
880
881
882
883
884
885
886
887
888
            for (int i = 0; i < count; ++i) {
                settings->setArrayIndex(i);
                const QString &toolId = settings->value(QLatin1String("Tool")).toString();
                if (tools.contains(toolId)) {
                    ExternalTool *tool = tools.value(toolId);
                    // remove from old category
                    (*categoryMap)[tool->displayCategory()].removeAll(tool);
                    if (categoryMap->value(tool->displayCategory()).isEmpty())
                        categoryMap->remove(tool->displayCategory());
                    // add to new category
889
                    (*categoryMap)[displayCategory].append(tool);
890
891
                }
            }
con's avatar
con committed
892
            settings->endArray();
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
        }
        settings->endGroup();
    }

    settings->endGroup();
}

void ExternalToolManager::writeSettings()
{
    QSettings *settings = m_core->settings();
    settings->beginGroup(QLatin1String("ExternalTools"));
    settings->remove(QLatin1String(""));

    settings->beginGroup(QLatin1String("OverrideCategories"));
    QMapIterator<QString, QList<ExternalTool *> > it(m_categoryMap);
    while (it.hasNext()) {
        it.next();
910
911
912
        QString category = it.key();
        if (category.isEmpty())
            category = QLatin1String(kSpecialUncategorizedSetting);
con's avatar
con committed
913
914
        settings->beginWriteArray(category, it.value().count());
        int i = 0;
915
        foreach (ExternalTool *tool, it.value()) {
con's avatar
con committed
916
917
918
            settings->setArrayIndex(i);
            settings->setValue(QLatin1String("Tool"), tool->id());
            ++i;
919
        }
con's avatar
con committed
920
        settings->endArray();
921
922
923
924
925
    }
    settings->endGroup();

    settings->endGroup();
}
926
927
928
929
930
931

void ExternalToolManager::openPreferences()
{
    ICore::instance()->showOptionsDialog(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE),
                                         QLatin1String(Core::Constants::SETTINGS_ID_TOOLS));
}