summaryrefslogtreecommitdiff
path: root/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
blob: d92c43ed7f2fe6a630a26ffd6a632be6faf76738 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
283
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "vcsbasesubmiteditor.h"

#include "commonvcssettings.h"
#include "nicknamedialog.h"
#include "submiteditorfile.h"
#include "submiteditorwidget.h"
#include "submitfieldwidget.h"
#include "submitfilemodel.h"
#include "vcsbaseoutputwindow.h"
#include "vcsplugin.h"

#include <aggregation/aggregate.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <utils/checkablemessagebox.h>
#include <utils/synchronousprocess.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <coreplugin/find/basetextfind.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>

#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>

#include <QDebug>
#include <QDir>
#include <QProcess>
#include <QFileInfo>
#include <QPointer>
#include <QStringListModel>
#include <QStyle>
#include <QToolBar>
#include <QAction>
#include <QApplication>
#include <QMessageBox>
#include <QCompleter>

#include <cstring>

enum { debug = 0 };
enum { wantToolBar = 0 };

// Return true if word is meaningful and can be added to a completion model
static bool acceptsWordForCompletion(const char *word)
{
    if (word == 0)
        return false;
    static const std::size_t minWordLength = 7;
    return std::strlen(word) >= minWordLength;
}

// Return the class name which function belongs to
static const char *belongingClassName(const CPlusPlus::Function *function)
{
    if (function == 0)
        return 0;

    const CPlusPlus::Name *funcName = function->name();
    if (funcName != 0 && funcName->asQualifiedNameId() != 0) {
        const CPlusPlus::Name *funcBaseName = funcName->asQualifiedNameId()->base();
        if (funcBaseName != 0 && funcBaseName->identifier() != 0)
            return funcBaseName->identifier()->chars();
    }

    return 0;
}

/*!
    \class VcsBase::VcsBaseSubmitEditorParameters

    \brief The VcsBaseSubmitEditorParameters class is a utility class
    to parametrize a VcsBaseSubmitEditor.
*/

/*!
    \class  VcsBase::VcsBaseSubmitEditor

    \brief The VcsBaseSubmitEditor class is the base class for a submit editor
    based on the SubmitEditorWidget.

    Presents the commit message in a text editor and an
    checkable list of modified files in a list window. The user can delete
    files from the list by pressing unchecking them or diff the selection
    by doubleclicking.

    The action matching the ids (unless 0) of the parameter struct will be
    registered with the EditorWidget and submit/diff actions will be added to
    a toolbar.

    For the given context, there must be only one instance of the editor
    active.
    To start a submit, set the submit template on the editor and the output
    of the VCS status command listing the modified files as fileList and open
    it.

    The submit process is started by listening on the editor close
    signal and then asking the IDocument interface of the editor to save the file
    within a DocumentManager::blockFileChange() section
    and to launch the submit process. In addition, the action registered
    for submit should be connected to a slot triggering the close of the
    current editor in the editor manager.
*/

namespace VcsBase {

using namespace Internal;
using namespace Utils;

static inline QString submitMessageCheckScript()
{
    return VcsPlugin::instance()->settings().submitMessageCheckScript;
}

struct VcsBaseSubmitEditorPrivate
{
    VcsBaseSubmitEditorPrivate(const VcsBaseSubmitEditorParameters *parameters,
                               SubmitEditorWidget *editorWidget,
                               VcsBaseSubmitEditor *q);

    SubmitEditorWidget *m_widget;
    QToolBar *m_toolWidget;
    const VcsBaseSubmitEditorParameters *m_parameters;
    QString m_displayName;
    QString m_checkScriptWorkingDirectory;
    SubmitEditorFile *m_file;

    QPointer<QAction> m_diffAction;
    QPointer<QAction> m_submitAction;

    NickNameDialog *m_nickNameDialog;
};

VcsBaseSubmitEditorPrivate::VcsBaseSubmitEditorPrivate(const VcsBaseSubmitEditorParameters *parameters,
                                                       SubmitEditorWidget *editorWidget,
                                                       VcsBaseSubmitEditor *q) :
    m_widget(editorWidget),
    m_toolWidget(0),
    m_parameters(parameters),
    m_file(new SubmitEditorFile(parameters, q)),
    m_nickNameDialog(0)
{
    QCompleter *completer = new QCompleter(q);
    completer->setCaseSensitivity(Qt::CaseSensitive);
    completer->setModelSorting(QCompleter::CaseSensitivelySortedModel);
    m_widget->descriptionEdit()->setCompleter(completer);
    m_widget->descriptionEdit()->setCompletionLengthThreshold(4);
}

VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *parameters,
                                         SubmitEditorWidget *editorWidget) :
    d(new VcsBaseSubmitEditorPrivate(parameters, editorWidget, this))
{
    setContext(Core::Context(parameters->context));
    setWidget(d->m_widget);
    document()->setDisplayName(QCoreApplication::translate("VCS", d->m_parameters->displayName));

    // Message font according to settings
    Utils::CompletingTextEdit *descriptionEdit = editorWidget->descriptionEdit();
    const TextEditor::FontSettings fs = TextEditor::TextEditorSettings::fontSettings();
    const QTextCharFormat tf = fs.toTextCharFormat(TextEditor::C_TEXT);
    descriptionEdit->setFont(tf.font());
    const QTextCharFormat selectionFormat = fs.toTextCharFormat(TextEditor::C_SELECTION);
    QPalette pal;
    pal.setColor(QPalette::Base, tf.background().color());
    pal.setColor(QPalette::Text, tf.foreground().color());
    pal.setColor(QPalette::Foreground, tf.foreground().color());
    if (selectionFormat.background().style() != Qt::NoBrush)
        pal.setColor(QPalette::Highlight, selectionFormat.background().color());
    pal.setBrush(QPalette::HighlightedText, selectionFormat.foreground());
    descriptionEdit->setPalette(pal);

    d->m_file->setModified(false);
    // We are always clean to prevent the editor manager from asking to save.

    connect(d->m_widget, SIGNAL(diffSelected(QList<int>)), this, SLOT(slotDiffSelectedVcsFiles(QList<int>)));
    connect(descriptionEdit, SIGNAL(textChanged()), this, SLOT(slotDescriptionChanged()));

    const CommonVcsSettings settings = VcsPlugin::instance()->settings();
    // Add additional context menu settings
    if (!settings.submitMessageCheckScript.isEmpty() || !settings.nickNameMailMap.isEmpty()) {
        QAction *sep = new QAction(this);
        sep->setSeparator(true);
        d->m_widget->addDescriptionEditContextMenuAction(sep);
        // Run check action
        if (!settings.submitMessageCheckScript.isEmpty()) {
            QAction *checkAction = new QAction(tr("Check Message"), this);
            connect(checkAction, SIGNAL(triggered()), this, SLOT(slotCheckSubmitMessage()));
            d->m_widget->addDescriptionEditContextMenuAction(checkAction);
        }
        // Insert nick
        if (!settings.nickNameMailMap.isEmpty()) {
            QAction *insertAction = new QAction(tr("Insert Name..."), this);
            connect(insertAction, SIGNAL(triggered()), this, SLOT(slotInsertNickName()));
            d->m_widget->addDescriptionEditContextMenuAction(insertAction);
        }
    }
    // Do we have user fields?
    if (!settings.nickNameFieldListFile.isEmpty())
        createUserFields(settings.nickNameFieldListFile);

    // wrapping. etc
    slotUpdateEditorSettings(settings);
    connect(VcsPlugin::instance(),
            SIGNAL(settingsChanged(VcsBase::Internal::CommonVcsSettings)),
            this, SLOT(slotUpdateEditorSettings(VcsBase::Internal::CommonVcsSettings)));
    // Commit data refresh might lead to closing the editor, so use a queued connection
    connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(slotRefreshCommitData()), Qt::QueuedConnection);
    connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()),
            this, SLOT(slotRefreshCommitData()), Qt::QueuedConnection);

    Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
    aggregate->add(new Core::BaseTextFind(descriptionEdit));
    aggregate->add(this);
}

VcsBaseSubmitEditor::~VcsBaseSubmitEditor()
{
    delete d->m_toolWidget;
    delete d->m_widget;
    delete d;
}

void VcsBaseSubmitEditor::slotUpdateEditorSettings(const CommonVcsSettings &s)
{
    setLineWrapWidth(s.lineWrapWidth);
    setLineWrap(s.lineWrap);
}

void VcsBaseSubmitEditor::slotRefreshCommitData()
{
    if (Core::EditorManager::currentEditor() == this)
        updateFileModel();
}

// Return a trimmed list of non-empty field texts
static inline QStringList fieldTexts(const QString &fileContents)
{
    QStringList rc;
    const QStringList rawFields = fileContents.trimmed().split(QLatin1Char('\n'));
    foreach (const QString &field, rawFields) {
        const QString trimmedField = field.trimmed();
        if (!trimmedField.isEmpty())
            rc.push_back(trimmedField);
    }
    return rc;
}

void VcsBaseSubmitEditor::createUserFields(const QString &fieldConfigFile)
{
    Utils::FileReader reader;
    if (!reader.fetch(fieldConfigFile, QIODevice::Text, Core::ICore::mainWindow()))
        return;
    // Parse into fields
    const QStringList fields = fieldTexts(QString::fromUtf8(reader.data()));
    if (fields.empty())
        return;
    // Create a completer on user names
    const QStandardItemModel *nickNameModel = VcsPlugin::instance()->nickNameModel();
    QCompleter *completer = new QCompleter(NickNameDialog::nickNameList(nickNameModel), this);

    SubmitFieldWidget *fieldWidget = new SubmitFieldWidget;
    connect(fieldWidget, SIGNAL(browseButtonClicked(int,QString)),
            this, SLOT(slotSetFieldNickName(int)));
    fieldWidget->setCompleter(completer);
    fieldWidget->setAllowDuplicateFields(true);
    fieldWidget->setHasBrowseButton(true);
    fieldWidget->setFields(fields);
    d->m_widget->addSubmitFieldWidget(fieldWidget);
}

void VcsBaseSubmitEditor::registerActions(QAction *editorUndoAction, QAction *editorRedoAction,
                                          QAction *submitAction, QAction *diffAction)
{
    d->m_widget->registerActions(editorUndoAction, editorRedoAction, submitAction, diffAction);
    d->m_diffAction = diffAction;
    d->m_submitAction = submitAction;
}

void VcsBaseSubmitEditor::unregisterActions(QAction *editorUndoAction,  QAction *editorRedoAction,
                           QAction *submitAction, QAction *diffAction)
{
    d->m_widget->unregisterActions(editorUndoAction, editorRedoAction, submitAction, diffAction);
    d->m_diffAction = d->m_submitAction = 0;
}

QAbstractItemView::SelectionMode VcsBaseSubmitEditor::fileListSelectionMode() const
{
    return d->m_widget->fileListSelectionMode();
}

void VcsBaseSubmitEditor::setFileListSelectionMode(QAbstractItemView::SelectionMode sm)
{
    d->m_widget->setFileListSelectionMode(sm);
}

bool VcsBaseSubmitEditor::isEmptyFileListEnabled() const
{
    return d->m_widget->isEmptyFileListEnabled();
}

void VcsBaseSubmitEditor::setEmptyFileListEnabled(bool e)
{
    d->m_widget->setEmptyFileListEnabled(e);
}

bool VcsBaseSubmitEditor::lineWrap() const
{
    return d->m_widget->lineWrap();
}

void VcsBaseSubmitEditor::setLineWrap(bool w)
{
    d->m_widget->setLineWrap(w);
}

int VcsBaseSubmitEditor::lineWrapWidth() const
{
    return d->m_widget->lineWrapWidth();
}

void VcsBaseSubmitEditor::setLineWrapWidth(int w)
{
    d->m_widget->setLineWrapWidth(w);
}

void VcsBaseSubmitEditor::slotDescriptionChanged()
{
}

bool VcsBaseSubmitEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
    if (fileName.isEmpty())
        return false;

    Utils::FileReader reader;
    if (!reader.fetch(realFileName, QIODevice::Text, errorString))
        return false;

    const QString text = QString::fromLocal8Bit(reader.data());
    if (!setFileContents(text.toUtf8()))
        return false;

    d->m_file->setFilePath(QFileInfo(fileName).absoluteFilePath());
    d->m_file->setModified(fileName != realFileName);
    return true;
}

Core::IDocument *VcsBaseSubmitEditor::document()
{
    return d->m_file;
}

QString VcsBaseSubmitEditor::checkScriptWorkingDirectory() const
{
    return d->m_checkScriptWorkingDirectory;
}

void VcsBaseSubmitEditor::setCheckScriptWorkingDirectory(const QString &s)
{
    d->m_checkScriptWorkingDirectory = s;
}

static QToolBar *createToolBar(const QWidget *someWidget, QAction *submitAction, QAction *diffAction)
{
    // Create
    QToolBar *toolBar = new QToolBar;
    toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    const int size = someWidget->style()->pixelMetric(QStyle::PM_SmallIconSize);
    toolBar->setIconSize(QSize(size, size));
    toolBar->addSeparator();

    if (submitAction)
        toolBar->addAction(submitAction);
    if (diffAction)
        toolBar->addAction(diffAction);
    return toolBar;
}

QWidget *VcsBaseSubmitEditor::toolBar()
{
    if (!wantToolBar)
        return 0;

    if (d->m_toolWidget)
        return d->m_toolWidget;

    if (!d->m_diffAction && !d->m_submitAction)
        return 0;

    // Create
    d->m_toolWidget = createToolBar(d->m_widget, d->m_submitAction, d->m_diffAction);
    return d->m_toolWidget;
}

QStringList VcsBaseSubmitEditor::checkedFiles() const
{
    return d->m_widget->checkedFiles();
}

void VcsBaseSubmitEditor::setFileModel(SubmitFileModel *model, const QString &repositoryDirectory)
{
    QTC_ASSERT(model, return);
    if (SubmitFileModel *oldModel = d->m_widget->fileModel()) {
        model->updateSelections(oldModel);
        delete oldModel;
    }
    d->m_widget->setFileModel(model);

    QSet<QString> uniqueSymbols;
    const CPlusPlus::Snapshot cppSnapShot = CppTools::CppModelManagerInterface::instance()->snapshot();

    // Iterate over the files and get interesting symbols
    for (int row = 0; row < model->rowCount(); ++row) {
        const QFileInfo fileInfo(repositoryDirectory, model->file(row));

        // Add file name
        uniqueSymbols.insert(fileInfo.fileName());

        const QString filePath = fileInfo.absoluteFilePath();
        // Add symbols from the C++ code model
        const CPlusPlus::Document::Ptr doc = cppSnapShot.document(filePath);
        if (!doc.isNull() && doc->control() != 0) {
            const CPlusPlus::Control *ctrl = doc->control();
            CPlusPlus::Symbol **symPtr = ctrl->firstSymbol(); // Read-only
            while (symPtr != ctrl->lastSymbol()) {
                const CPlusPlus::Symbol *sym = *symPtr;

                const CPlusPlus::Identifier *symId = sym->identifier();
                // Add any class, function or namespace identifiers
                if ((sym->isClass() || sym->isFunction() || sym->isNamespace())
                        && (symId != 0 && acceptsWordForCompletion(symId->chars())))
                {
                    uniqueSymbols.insert(QString::fromUtf8(symId->chars()));
                }

                // Handle specific case : get "Foo" in "void Foo::function() {}"
                if (sym->isFunction() && !sym->asFunction()->isDeclaration()) {
                    const char *className = belongingClassName(sym->asFunction());
                    if (acceptsWordForCompletion(className))
                        uniqueSymbols.insert(QString::fromUtf8(className));
                }

                ++symPtr;
            }
        }
    }

    // Populate completer with symbols
    if (!uniqueSymbols.isEmpty()) {
        QCompleter *completer = d->m_widget->descriptionEdit()->completer();
        QStringList symbolsList = uniqueSymbols.toList();
        symbolsList.sort();
        completer->setModel(new QStringListModel(symbolsList, completer));
    }
}

SubmitFileModel *VcsBaseSubmitEditor::fileModel() const
{
    return d->m_widget->fileModel();
}

QStringList VcsBaseSubmitEditor::rowsToFiles(const QList<int> &rows) const
{
    if (rows.empty())
        return QStringList();

    QStringList rc;
    const SubmitFileModel *model = fileModel();
    const int count = rows.size();
    for (int i = 0; i < count; i++)
        rc.push_back(model->file(rows.at(i)));
    return rc;
}

void VcsBaseSubmitEditor::slotDiffSelectedVcsFiles(const QList<int> &rawList)
{
    if (d->m_parameters->diffType == VcsBaseSubmitEditorParameters::DiffRows)
        emit diffSelectedFiles(rawList);
    else
        emit diffSelectedFiles(rowsToFiles(rawList));
}

QByteArray VcsBaseSubmitEditor::fileContents() const
{
    return d->m_widget->descriptionText().toLocal8Bit();
}

bool VcsBaseSubmitEditor::setFileContents(const QByteArray &contents)
{
    d->m_widget->setDescriptionText(QString::fromUtf8(contents));
    return true;
}

bool VcsBaseSubmitEditor::isDescriptionMandatory() const
{
    return d->m_widget->isDescriptionMandatory();
}

void VcsBaseSubmitEditor::setDescriptionMandatory(bool v)
{
    d->m_widget->setDescriptionMandatory(v);
}

enum { checkDialogMinimumWidth = 500 };

VcsBaseSubmitEditor::PromptSubmitResult
        VcsBaseSubmitEditor::promptSubmit(const QString &title,
                                          const QString &question,
                                          const QString &checkFailureQuestion,
                                          bool *promptSetting,
                                          bool forcePrompt,
                                          bool canCommitOnFailure)
{
    SubmitEditorWidget *submitWidget = static_cast<SubmitEditorWidget *>(this->widget());

    Core::EditorManager::activateEditor(this, Core::EditorManager::IgnoreNavigationHistory);

    if (!submitWidget->isEnabled())
        return SubmitDiscarded;

    QString errorMessage;
    QMessageBox::StandardButton answer = QMessageBox::Yes;

    const bool prompt = forcePrompt || *promptSetting;

    QWidget *parent = Core::ICore::mainWindow();
    // Pop up a message depending on whether the check succeeded and the
    // user wants to be prompted
    bool canCommit = checkSubmitMessage(&errorMessage) && submitWidget->canSubmit();
    if (canCommit) {
        // Check ok, do prompt?
        if (prompt) {
            // Provide check box to turn off prompt ONLY if it was not forced
            if (*promptSetting && !forcePrompt) {
                const QDialogButtonBox::StandardButton danswer =
                        Utils::CheckableMessageBox::question(parent, title, question,
                                                                   tr("Prompt to submit"), promptSetting,
                                                                   QDialogButtonBox::Yes|QDialogButtonBox::No|
                                                                   QDialogButtonBox::Cancel,
                                                                   QDialogButtonBox::Yes);
                answer = Utils::CheckableMessageBox::dialogButtonBoxToMessageBoxButton(danswer);
            } else {
                answer = QMessageBox::question(parent, title, question,
                                               QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel,
                                               QMessageBox::Yes);
            }
        }
    } else {
        // Check failed.
        QMessageBox msgBox(QMessageBox::Question, title, checkFailureQuestion,
                           QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel, parent);
        msgBox.setDefaultButton(QMessageBox::Cancel);
        msgBox.setInformativeText(errorMessage);
        msgBox.setMinimumWidth(checkDialogMinimumWidth);
        answer = static_cast<QMessageBox::StandardButton>(msgBox.exec());
    }
    if (!canCommit && !canCommitOnFailure) {
        switch (answer) {
        case QMessageBox::No:
            return SubmitDiscarded;
        case QMessageBox::Yes:
            return SubmitCanceled;
        default:
            break;
        }
    } else {
        switch (answer) {
        case QMessageBox::No:
            return SubmitDiscarded;
        case QMessageBox::Yes:
            return SubmitConfirmed;
        default:
            break;
        }
    }

    return SubmitCanceled;
}

QString VcsBaseSubmitEditor::promptForNickName()
{
    if (!d->m_nickNameDialog)
        d->m_nickNameDialog = new NickNameDialog(VcsPlugin::instance()->nickNameModel(), d->m_widget);
    if (d->m_nickNameDialog->exec() == QDialog::Accepted)
       return d->m_nickNameDialog->nickName();
    return QString();
}

void VcsBaseSubmitEditor::slotInsertNickName()
{
    const QString nick = promptForNickName();
    if (!nick.isEmpty())
        d->m_widget->descriptionEdit()->textCursor().insertText(nick);
}

void VcsBaseSubmitEditor::slotSetFieldNickName(int i)
{
    if (SubmitFieldWidget *sfw = d->m_widget->submitFieldWidgets().front()) {
        const QString nick = promptForNickName();
        if (!nick.isEmpty())
            sfw->setFieldValue(i, nick);
    }
}

void VcsBaseSubmitEditor::slotCheckSubmitMessage()
{
    QString errorMessage;
    if (!checkSubmitMessage(&errorMessage)) {
        QMessageBox msgBox(QMessageBox::Warning, tr("Submit Message Check Failed"),
                           errorMessage, QMessageBox::Ok, d->m_widget);
        msgBox.setMinimumWidth(checkDialogMinimumWidth);
        msgBox.exec();
    }
}

bool VcsBaseSubmitEditor::checkSubmitMessage(QString *errorMessage) const
{
    const QString checkScript = submitMessageCheckScript();
    if (checkScript.isEmpty())
        return true;
    QApplication::setOverrideCursor(Qt::WaitCursor);
    const bool rc = runSubmitMessageCheckScript(checkScript, errorMessage);
    QApplication::restoreOverrideCursor();
    return rc;
}

static inline QString msgCheckScript(const QString &workingDir, const QString &cmd)
{
    const QString nativeCmd = QDir::toNativeSeparators(cmd);
    return workingDir.isEmpty() ?
           VcsBaseSubmitEditor::tr("Executing %1").arg(nativeCmd) :
           VcsBaseSubmitEditor::tr("Executing [%1] %2").
           arg(QDir::toNativeSeparators(workingDir), nativeCmd);
}

bool VcsBaseSubmitEditor::runSubmitMessageCheckScript(const QString &checkScript, QString *errorMessage) const
{
    // Write out message
    QString tempFilePattern = QDir::tempPath();
    if (!tempFilePattern.endsWith(QDir::separator()))
        tempFilePattern += QDir::separator();
    tempFilePattern += QLatin1String("msgXXXXXX.txt");
    TempFileSaver saver(tempFilePattern);
    saver.write(fileContents());
    if (!saver.finalize(errorMessage))
        return false;
    // Run check process
    VcsBaseOutputWindow *outputWindow = VcsBaseOutputWindow::instance();
    outputWindow->appendCommand(msgCheckScript(d->m_checkScriptWorkingDirectory, checkScript));
    QProcess checkProcess;
    if (!d->m_checkScriptWorkingDirectory.isEmpty())
        checkProcess.setWorkingDirectory(d->m_checkScriptWorkingDirectory);
    checkProcess.start(checkScript, QStringList(saver.fileName()));
    checkProcess.closeWriteChannel();
    if (!checkProcess.waitForStarted()) {
        *errorMessage = tr("The check script \"%1\" could not be started: %2").arg(checkScript, checkProcess.errorString());
        return false;
    }
    QByteArray stdOutData;
    QByteArray stdErrData;
    if (!SynchronousProcess::readDataFromProcess(checkProcess, 30000, &stdOutData, &stdErrData, false)) {
        SynchronousProcess::stopProcess(checkProcess);
        *errorMessage = tr("The check script \"%1\" timed out.").
                        arg(QDir::toNativeSeparators(checkScript));
        return false;
    }
    if (checkProcess.exitStatus() != QProcess::NormalExit) {
        *errorMessage = tr("The check script \"%1\" crashed.").
                        arg(QDir::toNativeSeparators(checkScript));
        return false;
    }
    if (!stdOutData.isEmpty())
        outputWindow->appendSilently(QString::fromLocal8Bit(stdOutData));
    const QString stdErr = QString::fromLocal8Bit(stdErrData);
    if (!stdErr.isEmpty())
        outputWindow->appendSilently(stdErr);
    const int exitCode = checkProcess.exitCode();
    if (exitCode != 0) {
        const QString exMessage = tr("The check script returned exit code %1.").
                                  arg(exitCode);
        outputWindow->appendError(exMessage);
        *errorMessage = stdErr;
        if (errorMessage->isEmpty())
            *errorMessage = exMessage;
        return false;
    }
    return true;
}

QIcon VcsBaseSubmitEditor::diffIcon()
{
    return QIcon(QLatin1String(":/vcsbase/images/diff.png"));
}

QIcon VcsBaseSubmitEditor::submitIcon()
{
    return QIcon(QLatin1String(":/vcsbase/images/submit.png"));
}

// Compile a list if files in the current projects. TODO: Recurse down qrc files?
QStringList VcsBaseSubmitEditor::currentProjectFiles(bool nativeSeparators, QString *name)
{
    if (name)
        name->clear();

    if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject()) {
        QStringList files = currentProject->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
        if (name)
            *name = currentProject->displayName();
        if (nativeSeparators && !files.empty()) {
            const QStringList::iterator end = files.end();
            for (QStringList::iterator it = files.begin(); it != end; ++it)
                *it = QDir::toNativeSeparators(*it);
        }
        return files;
    }
    return QStringList();
}

// Reduce a list of untracked files reported by a VCS down to the files
// that are actually part of the current project(s).
void VcsBaseSubmitEditor::filterUntrackedFilesOfProject(const QString &repositoryDirectory, QStringList *untrackedFiles)
{
    if (untrackedFiles->empty())
        return;
    const QStringList nativeProjectFiles = VcsBaseSubmitEditor::currentProjectFiles(true);
    if (nativeProjectFiles.empty())
        return;
    const QDir repoDir(repositoryDirectory);
    for (QStringList::iterator it = untrackedFiles->begin(); it != untrackedFiles->end(); ) {
        const QString path = QDir::toNativeSeparators(repoDir.absoluteFilePath(*it));
        if (nativeProjectFiles.contains(path))
            ++it;
        else
            it = untrackedFiles->erase(it);
    }
}

} // namespace VcsBase