vcsbaseeditor.cpp 51.7 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31 32
#include "vcsbaseeditor.h"
#include "diffhighlighter.h"
#include "baseannotationhighlighter.h"
33
#include "vcsbaseplugin.h"
Orgad Shaneh's avatar
Orgad Shaneh committed
34
#include "vcsbaseeditorparameterwidget.h"
35
#include "command.h"
con's avatar
con committed
36

Tobias Hunger's avatar
Tobias Hunger committed
37 38
#include <coreplugin/icore.h>
#include <coreplugin/vcsmanager.h>
jkobus's avatar
jkobus committed
39
#include <coreplugin/patchtool.h>
40 41
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/editorconfiguration.h>
con's avatar
con committed
42
#include <projectexplorer/projectexplorer.h>
43
#include <projectexplorer/project.h>
con's avatar
con committed
44
#include <projectexplorer/session.h>
45
#include <texteditor/basetextdocument.h>
46
#include <texteditor/basetextdocumentlayout.h>
47
#include <utils/qtcassert.h>
con's avatar
con committed
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#include <QDebug>
#include <QFileInfo>
#include <QFile>
#include <QRegExp>
#include <QSet>
#include <QTextCodec>
#include <QUrl>
#include <QTextBlock>
#include <QDesktopServices>
#include <QAction>
#include <QKeyEvent>
#include <QMenu>
#include <QTextCursor>
#include <QTextEdit>
#include <QComboBox>
#include <QClipboard>
#include <QApplication>
#include <QMessageBox>
con's avatar
con committed
67

68
/*!
hjk's avatar
hjk committed
69
    \enum VcsBase::EditorContentType
70

Leena Miettinen's avatar
Leena Miettinen committed
71
    This enum describes the contents of a VcsBaseEditor and its interaction.
72 73

    \value RegularCommandOutput  No special handling.
Leena Miettinen's avatar
Leena Miettinen committed
74 75 76 77 78 79 80 81
    \value LogOutput  Log of a file under revision control. Provide a
           description of the change that users can click to view detailed
           information about the change and \e Annotate for the log of a
           single file.
    \value AnnotateOutput  Color contents per change number and provide a
           clickable change description.
           Context menu offers annotate previous version functionality.
           Expected format:
82 83 84
           \code
           <change description>: file line
           \endcode
Leena Miettinen's avatar
Leena Miettinen committed
85 86 87
    \value DiffOutput  Diff output. Might include describe output, which consists of a
           header and diffs. Double-clicking the chunk opens the file. The context
           menu offers the functionality to revert the chunk.
88

hjk's avatar
hjk committed
89
    \sa VcsBase::VcsBaseEditorWidget
90 91
*/

92 93
using namespace TextEditor;

hjk's avatar
hjk committed
94
namespace VcsBase {
con's avatar
con committed
95

96
/*!
hjk's avatar
hjk committed
97
    \class VcsBase::DiffChunk
98

99 100
    \brief The DiffChunk class provides a diff chunk consisting of file name
    and chunk data.
101 102
*/

103 104 105 106 107
bool DiffChunk::isValid() const
{
    return !fileName.isEmpty() && !chunk.isEmpty();
}

108
QByteArray DiffChunk::asPatch(const QString &workingDirectory) const
109
{
110 111 112
    QString relativeFile = workingDirectory.isEmpty() ?
                fileName : QDir(workingDirectory).relativeFilePath(fileName);
    const QByteArray fileNameBA = QFile::encodeName(relativeFile);
113 114 115 116 117 118 119 120 121
    QByteArray rc = "--- ";
    rc += fileNameBA;
    rc += "\n+++ ";
    rc += fileNameBA;
    rc += '\n';
    rc += chunk;
    return rc;
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135
namespace Internal {

// Data to be passed to apply/revert diff chunk actions.
class DiffChunkAction
{
public:
    DiffChunkAction(const DiffChunk &dc = DiffChunk(), bool revertIn = false) :
        chunk(dc), revert(revertIn) {}

    DiffChunk chunk;
    bool revert;
};

} // namespace Internal
hjk's avatar
hjk committed
136
} // namespace VcsBase
137

hjk's avatar
hjk committed
138
Q_DECLARE_METATYPE(VcsBase::Internal::DiffChunkAction)
139

hjk's avatar
hjk committed
140
namespace VcsBase {
141

142
/*!
hjk's avatar
hjk committed
143
    \class VcsBase::VcsBaseEditor
144

145 146
    \brief The VcsBaseEditor class implements an editor with no support for
    duplicates.
147 148

    Creates a browse combo in the toolbar for diff output.
hjk's avatar
hjk committed
149
    It also mirrors the signals of the VcsBaseEditor since the editor
150 151 152
    manager passes the editor around.
*/

153
VcsBaseEditor::VcsBaseEditor(const VcsBaseEditorParameters *type)
con's avatar
con committed
154
{
155
    setContext(Core::Context(type->context, TextEditor::Constants::C_TEXTEDITOR));
con's avatar
con committed
156 157
}

hjk's avatar
hjk committed
158
// ----------- VcsBaseEditorPrivate
con's avatar
con committed
159

160 161
namespace Internal {

162
/*! \class AbstractTextCursorHandler
163 164
 *  \brief The AbstractTextCursorHandler class provides an interface to handle
 *  the contents under a text cursor inside an editor.
165 166 167 168 169 170
 */
class AbstractTextCursorHandler : public QObject
{
public:
    AbstractTextCursorHandler(VcsBaseEditorWidget *editorWidget = 0);

Leena Miettinen's avatar
Leena Miettinen committed
171
    /*! Tries to find some matching contents under \a cursor.
172
     *
Leena Miettinen's avatar
Leena Miettinen committed
173 174 175 176
     *  It is the first function to be called because it changes the internal
     *  state of the handler. Other functions (such as
     *  highlightCurrentContents() and handleCurrentContents()) use the result
     *  of the matching.
177
     *
Leena Miettinen's avatar
Leena Miettinen committed
178
     *  Returns \c true if contents could be found.
179 180 181 182 183 184 185 186 187 188 189 190
     */
    virtual bool findContentsUnderCursor(const QTextCursor &cursor);

    //! Highlight (eg underline) the contents matched with findContentsUnderCursor()
    virtual void highlightCurrentContents() = 0;

    //! React to user-interaction with the contents matched with findContentsUnderCursor()
    virtual void handleCurrentContents() = 0;

    //! Contents matched with the last call to findContentsUnderCursor()
    virtual QString currentContents() const = 0;

Leena Miettinen's avatar
Leena Miettinen committed
191 192
    /*! Fills \a menu with contextual actions applying to the contents matched
     *  with findContentsUnderCursor().
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
     */
    virtual void fillContextMenu(QMenu *menu, EditorContentType type) const = 0;

    //! Editor passed on construction of this handler
    VcsBaseEditorWidget *editorWidget() const;

    //! Text cursor used to match contents with findContentsUnderCursor()
    QTextCursor currentCursor() const;

private:
    VcsBaseEditorWidget *m_editorWidget;
    QTextCursor m_currentCursor;
};

AbstractTextCursorHandler::AbstractTextCursorHandler(VcsBaseEditorWidget *editorWidget)
    : QObject(editorWidget),
      m_editorWidget(editorWidget)
{
}

bool AbstractTextCursorHandler::findContentsUnderCursor(const QTextCursor &cursor)
{
    m_currentCursor = cursor;
    return false;
}

VcsBaseEditorWidget *AbstractTextCursorHandler::editorWidget() const
{
    return m_editorWidget;
}

QTextCursor AbstractTextCursorHandler::currentCursor() const
{
    return m_currentCursor;
}

/*! \class ChangeTextCursorHandler
230 231
 *  \brief The ChangeTextCursorHandler class provides a handler for VCS change
 *  identifiers.
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
 */
class ChangeTextCursorHandler : public AbstractTextCursorHandler
{
    Q_OBJECT

public:
    ChangeTextCursorHandler(VcsBaseEditorWidget *editorWidget = 0);

    bool findContentsUnderCursor(const QTextCursor &cursor);
    void highlightCurrentContents();
    void handleCurrentContents();
    QString currentContents() const;
    void fillContextMenu(QMenu *menu, EditorContentType type) const;

private slots:
    void slotDescribe();
    void slotCopyRevision();

private:
    QAction *createDescribeAction(const QString &change) const;
    QAction *createAnnotateAction(const QString &change, bool previous) const;
    QAction *createCopyRevisionAction(const QString &change) const;

    QString m_currentChange;
};

ChangeTextCursorHandler::ChangeTextCursorHandler(VcsBaseEditorWidget *editorWidget)
    : AbstractTextCursorHandler(editorWidget)
{
}

bool ChangeTextCursorHandler::findContentsUnderCursor(const QTextCursor &cursor)
{
    AbstractTextCursorHandler::findContentsUnderCursor(cursor);
    m_currentChange = editorWidget()->changeUnderCursor(cursor);
    return !m_currentChange.isEmpty();
}

void ChangeTextCursorHandler::highlightCurrentContents()
{
    QTextEdit::ExtraSelection sel;
    sel.cursor = currentCursor();
    sel.cursor.select(QTextCursor::WordUnderCursor);
    sel.format.setFontUnderline(true);
    sel.format.setProperty(QTextFormat::UserProperty, m_currentChange);
    editorWidget()->setExtraSelections(VcsBaseEditorWidget::OtherSelection,
                                       QList<QTextEdit::ExtraSelection>() << sel);
}

void ChangeTextCursorHandler::handleCurrentContents()
{
    slotDescribe();
}

void ChangeTextCursorHandler::fillContextMenu(QMenu *menu, EditorContentType type) const
{
288
    VcsBaseEditorWidget *widget = editorWidget();
289 290
    switch (type) {
    case AnnotateOutput: { // Describe current / annotate previous
291
        bool currentValid = widget->isValidRevision(m_currentChange);
292 293
        menu->addSeparator();
        menu->addAction(createCopyRevisionAction(m_currentChange));
294 295
        if (currentValid)
            menu->addAction(createDescribeAction(m_currentChange));
296
        menu->addSeparator();
297 298 299
        if (currentValid)
            menu->addAction(createAnnotateAction(widget->decorateVersion(m_currentChange), false));
        const QStringList previousVersions = widget->annotationPreviousVersions(m_currentChange);
300 301
        if (!previousVersions.isEmpty()) {
            foreach (const QString &pv, previousVersions)
302
                menu->addAction(createAnnotateAction(widget->decorateVersion(pv), true));
303 304 305
        }
        break;
    }
306 307 308 309 310 311
    default: // Describe current / Annotate file of current
        menu->addSeparator();
        menu->addAction(createCopyRevisionAction(m_currentChange));
        menu->addAction(createDescribeAction(m_currentChange));
        if (widget->isFileLogAnnotateEnabled())
            menu->addAction(createAnnotateAction(m_currentChange, false));
312 313
        break;
    }
314
    widget->addChangeActions(menu, m_currentChange);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
}

QString ChangeTextCursorHandler::currentContents() const
{
    return m_currentChange;
}

void ChangeTextCursorHandler::slotDescribe()
{
    emit editorWidget()->describeRequested(editorWidget()->source(), m_currentChange);
}

void ChangeTextCursorHandler::slotCopyRevision()
{
    QApplication::clipboard()->setText(m_currentChange);
}

QAction *ChangeTextCursorHandler::createDescribeAction(const QString &change) const
{
334
    QAction *a = new QAction(VcsBaseEditorWidget::tr("Describe Change %1").arg(change), 0);
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
    connect(a, SIGNAL(triggered()), this, SLOT(slotDescribe()));
    return a;
}

QAction *ChangeTextCursorHandler::createAnnotateAction(const QString &change, bool previous) const
{
    // Use 'previous' format if desired and available, else default to standard.
    const QString &format =
            previous && !editorWidget()->annotatePreviousRevisionTextFormat().isEmpty() ?
                editorWidget()->annotatePreviousRevisionTextFormat() :
                editorWidget()->annotateRevisionTextFormat();
    QAction *a = new QAction(format.arg(change), 0);
    a->setData(change);
    connect(a, SIGNAL(triggered()), editorWidget(), SLOT(slotAnnotateRevision()));
    return a;
}

QAction *ChangeTextCursorHandler::createCopyRevisionAction(const QString &change) const
{
    QAction *a = new QAction(editorWidget()->copyRevisionTextFormat().arg(change), 0);
    a->setData(change);
    connect(a, SIGNAL(triggered()), this, SLOT(slotCopyRevision()));
    return a;
}

/*! \class UrlTextCursorHandler
361 362
 *  \brief The UrlTextCursorHandler class provides a handler for URLs, such as
 *  http://qt-project.org/.
363 364
 *
 *  The URL pattern can be redefined in sub-classes with setUrlPattern(), by default the pattern
Leena Miettinen's avatar
Leena Miettinen committed
365
 *  works for hyper-text URLs.
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
 */
class UrlTextCursorHandler : public AbstractTextCursorHandler
{
    Q_OBJECT

public:
    UrlTextCursorHandler(VcsBaseEditorWidget *editorWidget = 0);

    bool findContentsUnderCursor(const QTextCursor &cursor);
    void highlightCurrentContents();
    void handleCurrentContents();
    void fillContextMenu(QMenu *menu, EditorContentType type) const;
    QString currentContents() const;

protected slots:
    virtual void slotCopyUrl();
    virtual void slotOpenUrl();

protected:
    void setUrlPattern(const QString &pattern);
    QAction *createOpenUrlAction(const QString &text) const;
    QAction *createCopyUrlAction(const QString &text) const;

private:
    class UrlData
    {
    public:
        int startColumn;
        QString url;
    };

    UrlData m_urlData;
398
    QRegExp m_pattern;
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
};

UrlTextCursorHandler::UrlTextCursorHandler(VcsBaseEditorWidget *editorWidget)
    : AbstractTextCursorHandler(editorWidget)
{
    setUrlPattern(QLatin1String("https?\\://[^\\s]+"));
}

bool UrlTextCursorHandler::findContentsUnderCursor(const QTextCursor &cursor)
{
    AbstractTextCursorHandler::findContentsUnderCursor(cursor);

    m_urlData.url.clear();
    m_urlData.startColumn = -1;

    QTextCursor cursorForUrl = cursor;
    cursorForUrl.select(QTextCursor::LineUnderCursor);
    if (cursorForUrl.hasSelection()) {
        const QString line = cursorForUrl.selectedText();
        const int cursorCol = cursor.columnNumber();
        int urlMatchIndex = -1;
        do {
421
            urlMatchIndex = m_pattern.indexIn(line, urlMatchIndex + 1);
422
            if (urlMatchIndex != -1) {
423
                const QString url = m_pattern.cap(0);
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
                if (urlMatchIndex <= cursorCol && cursorCol <= urlMatchIndex + url.length()) {
                    m_urlData.startColumn = urlMatchIndex;
                    m_urlData.url = url;
                }
            }
        } while (urlMatchIndex != -1 && m_urlData.startColumn == -1);
    }

    return m_urlData.startColumn != -1;
}

void UrlTextCursorHandler::highlightCurrentContents()
{
    QTextEdit::ExtraSelection sel;
    sel.cursor = currentCursor();
    sel.cursor.setPosition(currentCursor().position()
                           - (currentCursor().columnNumber() - m_urlData.startColumn));
    sel.cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, m_urlData.url.length());
    sel.format.setFontUnderline(true);
    sel.format.setForeground(Qt::blue);
    sel.format.setUnderlineColor(Qt::blue);
    sel.format.setProperty(QTextFormat::UserProperty, m_urlData.url);
    editorWidget()->setExtraSelections(VcsBaseEditorWidget::OtherSelection,
                                       QList<QTextEdit::ExtraSelection>() << sel);
}

void UrlTextCursorHandler::handleCurrentContents()
{
    slotOpenUrl();
}

void UrlTextCursorHandler::fillContextMenu(QMenu *menu, EditorContentType type) const
{
    Q_UNUSED(type);
    menu->addSeparator();
Leena Miettinen's avatar
Leena Miettinen committed
459 460
    menu->addAction(createOpenUrlAction(tr("Open URL in Browser...")));
    menu->addAction(createCopyUrlAction(tr("Copy URL Location")));
461 462 463 464 465 466 467 468 469
}

QString UrlTextCursorHandler::currentContents() const
{
    return  m_urlData.url;
}

void UrlTextCursorHandler::setUrlPattern(const QString &pattern)
{
470 471
    m_pattern = QRegExp(pattern);
    QTC_ASSERT(m_pattern.isValid(), return);
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
}

void UrlTextCursorHandler::slotCopyUrl()
{
    QApplication::clipboard()->setText(m_urlData.url);
}

void UrlTextCursorHandler::slotOpenUrl()
{
    QDesktopServices::openUrl(QUrl(m_urlData.url));
}

QAction *UrlTextCursorHandler::createOpenUrlAction(const QString &text) const
{
    QAction *a = new QAction(text, 0);
    a->setData(m_urlData.url);
    connect(a, SIGNAL(triggered()), this, SLOT(slotOpenUrl()));
    return a;
}

QAction *UrlTextCursorHandler::createCopyUrlAction(const QString &text) const
{
    QAction *a = new QAction(text, 0);
    a->setData(m_urlData.url);
    connect(a, SIGNAL(triggered()), this, SLOT(slotCopyUrl()));
    return a;
}

/*! \class EmailTextCursorHandler
501 502
 *  \brief The EmailTextCursorHandler class provides a handler for email
 *  addresses.
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
 */
class EmailTextCursorHandler : public UrlTextCursorHandler
{
    Q_OBJECT

public:
    EmailTextCursorHandler(VcsBaseEditorWidget *editorWidget = 0);
    void fillContextMenu(QMenu *menu, EditorContentType type) const;

protected slots:
    void slotOpenUrl();
};

EmailTextCursorHandler::EmailTextCursorHandler(VcsBaseEditorWidget *editorWidget)
    : UrlTextCursorHandler(editorWidget)
{
519
    setUrlPattern(QLatin1String("[a-zA-Z0-9_\\.-]+@[^@ ]+\\.[a-zA-Z]+"));
520 521 522 523 524 525
}

void EmailTextCursorHandler::fillContextMenu(QMenu *menu, EditorContentType type) const
{
    Q_UNUSED(type);
    menu->addSeparator();
Leena Miettinen's avatar
Leena Miettinen committed
526 527
    menu->addAction(createOpenUrlAction(tr("Send Email To...")));
    menu->addAction(createCopyUrlAction(tr("Copy Email Address")));
528 529 530 531 532 533 534
}

void EmailTextCursorHandler::slotOpenUrl()
{
    QDesktopServices::openUrl(QUrl(QLatin1String("mailto:") + currentContents()));
}

hjk's avatar
hjk committed
535
class VcsBaseEditorWidgetPrivate
536
{
537
public:
538
    VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget *editorWidget);
539 540

    AbstractTextCursorHandler *findTextCursorHandler(const QTextCursor &cursor);
541 542 543
    // creates a browse combo in the toolbar for quick access to entries.
    // Can be used for diff and log. Combo created on first call.
    QComboBox *entriesComboBox();
con's avatar
con committed
544

545
    TextEditor::BaseTextEditorWidget *q;
hjk's avatar
hjk committed
546
    const VcsBaseEditorParameters *m_parameters;
547

548
    QString m_workingDirectory;
549 550

    QRegExp m_diffFilePattern;
551
    QRegExp m_logEntryPattern;
Orgad Shaneh's avatar
Orgad Shaneh committed
552
    QList<int> m_entrySections; // line number where this section starts
553
    int m_cursorLine;
554
    QString m_annotateRevisionTextFormat;
555
    QString m_annotatePreviousRevisionTextFormat;
556
    QString m_copyRevisionTextFormat;
557
    bool m_fileLogAnnotateEnabled;
Orgad Shaneh's avatar
Orgad Shaneh committed
558
    VcsBaseEditorParameterWidget *m_configurationWidget;
559
    bool m_mouseDragging;
560
    QList<AbstractTextCursorHandler *> m_textCursorHandlers;
561
    QPointer<Command> m_command;
562

563 564
private:
    QComboBox *m_entriesComboBox;
con's avatar
con committed
565 566
};

567 568 569
VcsBaseEditorWidgetPrivate::VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget *editorWidget)  :
    q(editorWidget),
    m_parameters(0),
570
    m_cursorLine(-1),
hjk's avatar
hjk committed
571 572
    m_annotateRevisionTextFormat(VcsBaseEditorWidget::tr("Annotate \"%1\"")),
    m_copyRevisionTextFormat(VcsBaseEditorWidget::tr("Copy \"%1\"")),
573
    m_fileLogAnnotateEnabled(false),
574
    m_configurationWidget(0),
575 576
    m_mouseDragging(false),
    m_entriesComboBox(0)
con's avatar
con committed
577
{
578 579 580 581 582 583 584 585 586 587 588 589
    m_textCursorHandlers.append(new ChangeTextCursorHandler(editorWidget));
    m_textCursorHandlers.append(new UrlTextCursorHandler(editorWidget));
    m_textCursorHandlers.append(new EmailTextCursorHandler(editorWidget));
}

AbstractTextCursorHandler *VcsBaseEditorWidgetPrivate::findTextCursorHandler(const QTextCursor &cursor)
{
    foreach (AbstractTextCursorHandler *handler, m_textCursorHandlers) {
        if (handler->findContentsUnderCursor(cursor))
            return handler;
    }
    return 0;
con's avatar
con committed
590 591
}

592 593 594 595 596 597 598 599 600 601 602
QComboBox *VcsBaseEditorWidgetPrivate::entriesComboBox()
{
    if (m_entriesComboBox)
        return m_entriesComboBox;
    m_entriesComboBox = new QComboBox;
    m_entriesComboBox->setMinimumContentsLength(20);
    // Make the combo box prefer to expand
    QSizePolicy policy = m_entriesComboBox->sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_entriesComboBox->setSizePolicy(policy);

603
    q->insertExtraToolBarWidget(TextEditor::BaseTextEditorWidget::Left, m_entriesComboBox);
604 605 606
    return m_entriesComboBox;
}

607 608
} // namespace Internal

609
/*!
610
    \class VcsBase::VcsBaseEditorParameters
611

612 613 614 615 616
    \brief The VcsBaseEditorParameters class is a helper class used to
    parametrize an editor with MIME type, context
    and id.

    The extension is currently only a suggestion when running
617 618
    VCS commands with redirection.

hjk's avatar
hjk committed
619
    \sa VcsBase::VcsBaseEditorWidget, VcsBase::BaseVcsEditorFactory, VcsBase::EditorContentType
620 621 622
*/

/*!
hjk's avatar
hjk committed
623
    \class VcsBase::VcsBaseEditorWidget
624

625 626
    \brief The VcsBaseEditorWidget class is the base class for editors showing
    version control system output
627 628 629 630 631 632
    of the type enumerated by EditorContentType.

    The source property should contain the file or directory the log
    refers to and will be emitted with describeRequested().
    This is for VCS that need a current directory.

hjk's avatar
hjk committed
633
    \sa VcsBase::BaseVcsEditorFactory, VcsBase::VcsBaseEditorParameters, VcsBase::EditorContentType
634 635
*/

636 637
VcsBaseEditorWidget::VcsBaseEditorWidget()
  : d(new Internal::VcsBaseEditorWidgetPrivate(this))
con's avatar
con committed
638
{
639
    viewport()->setMouseTracking(true);
640 641
    BaseTextDocumentPtr doc(new BaseTextDocument);
    setTextDocument(doc);
642 643 644 645 646 647 648 649
}

void VcsBaseEditorWidget::setParameters(const VcsBaseEditorParameters *parameters)
{
    QTC_CHECK(d->m_parameters == 0);
    d->m_parameters = parameters;
    textDocument()->setId(d->m_parameters->id);
    textDocument()->setMimeType(QLatin1String(d->m_parameters->mimeType));
con's avatar
con committed
650 651
}

652 653 654 655 656 657
void VcsBaseEditorWidget::setDiffFilePattern(const QRegExp &pattern)
{
    QTC_ASSERT(pattern.isValid() && pattern.captureCount() >= 1, return);
    d->m_diffFilePattern = pattern;
}

658 659 660 661 662 663
void VcsBaseEditorWidget::setLogEntryPattern(const QRegExp &pattern)
{
    QTC_ASSERT(pattern.isValid() && pattern.captureCount() >= 1, return);
    d->m_logEntryPattern = pattern;
}

664 665 666 667 668 669 670 671 672 673 674
bool VcsBaseEditorWidget::supportChangeLinks() const
{
    switch (d->m_parameters->type) {
    case LogOutput:
    case AnnotateOutput:
        return true;
    default:
        return false;
    }
}

675 676 677 678 679 680
QString VcsBaseEditorWidget::fileNameForLine(int line) const
{
    Q_UNUSED(line);
    return source();
}

hjk's avatar
hjk committed
681
void VcsBaseEditorWidget::init()
con's avatar
con committed
682
{
683
    switch (d->m_parameters->type) {
684 685
    case OtherContent:
        break;
con's avatar
con committed
686
    case LogOutput:
687 688 689
        connect(d->entriesComboBox(), SIGNAL(activated(int)), this, SLOT(slotJumpToEntry(int)));
        connect(this, SIGNAL(textChanged()), this, SLOT(slotPopulateLogBrowser()));
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
690
        break;
con's avatar
con committed
691 692 693 694
    case AnnotateOutput:
        // Annotation highlighting depends on contents, which is set later on
        connect(this, SIGNAL(textChanged()), this, SLOT(slotActivateAnnotation()));
        break;
Orgad Shaneh's avatar
Orgad Shaneh committed
695
    case DiffOutput:
696 697
        // Diff: set up diff file browsing
        connect(d->entriesComboBox(), SIGNAL(activated(int)), this, SLOT(slotJumpToEntry(int)));
698
        connect(this, SIGNAL(textChanged()), this, SLOT(slotPopulateDiffBrowser()));
699
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
con's avatar
con committed
700 701
        break;
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
702 703 704
    if (hasDiff()) {
        DiffHighlighter *dh = new DiffHighlighter(d->m_diffFilePattern);
        setCodeFoldingSupported(true);
705
        textDocument()->setSyntaxHighlighter(dh);
Orgad Shaneh's avatar
Orgad Shaneh committed
706
    }
707 708
    // override revisions display (green or red bar on the left, marking changes):
    setRevisionsVisible(false);
con's avatar
con committed
709 710
}

hjk's avatar
hjk committed
711
VcsBaseEditorWidget::~VcsBaseEditorWidget()
con's avatar
con committed
712
{
713
    setCommand(0); // abort all running commands
714
    delete d;
con's avatar
con committed
715 716
}

hjk's avatar
hjk committed
717
void VcsBaseEditorWidget::setForceReadOnly(bool b)
718
{
hjk's avatar
hjk committed
719
    VcsBaseEditor *eda = qobject_cast<VcsBaseEditor *>(editor());
720
    QTC_ASSERT(eda != 0, return);
721
    setReadOnly(b);
722
    eda->document()->setTemporary(b);
723 724
}

hjk's avatar
hjk committed
725
QString VcsBaseEditorWidget::source() const
con's avatar
con committed
726
{
727
    return VcsBasePlugin::source(textDocument());
con's avatar
con committed
728 729
}

hjk's avatar
hjk committed
730
void VcsBaseEditorWidget::setSource(const  QString &source)
con's avatar
con committed
731
{
732
    VcsBasePlugin::setSource(textDocument(), source);
con's avatar
con committed
733 734
}

hjk's avatar
hjk committed
735
QString VcsBaseEditorWidget::annotateRevisionTextFormat() const
736 737 738 739
{
    return d->m_annotateRevisionTextFormat;
}

hjk's avatar
hjk committed
740
void VcsBaseEditorWidget::setAnnotateRevisionTextFormat(const QString &f)
741 742 743 744
{
    d->m_annotateRevisionTextFormat = f;
}

hjk's avatar
hjk committed
745
QString VcsBaseEditorWidget::annotatePreviousRevisionTextFormat() const
746 747 748 749
{
    return d->m_annotatePreviousRevisionTextFormat;
}

hjk's avatar
hjk committed
750
void VcsBaseEditorWidget::setAnnotatePreviousRevisionTextFormat(const QString &f)
751 752 753 754
{
    d->m_annotatePreviousRevisionTextFormat = f;
}

hjk's avatar
hjk committed
755
QString VcsBaseEditorWidget::copyRevisionTextFormat() const
756 757 758 759
{
    return d->m_copyRevisionTextFormat;
}

hjk's avatar
hjk committed
760
void VcsBaseEditorWidget::setCopyRevisionTextFormat(const QString &f)
761 762 763 764
{
    d->m_copyRevisionTextFormat = f;
}

hjk's avatar
hjk committed
765
bool VcsBaseEditorWidget::isFileLogAnnotateEnabled() const
766 767 768 769
{
    return d->m_fileLogAnnotateEnabled;
}

hjk's avatar
hjk committed
770
void VcsBaseEditorWidget::setFileLogAnnotateEnabled(bool e)
771 772 773 774
{
    d->m_fileLogAnnotateEnabled = e;
}

775
QString VcsBaseEditorWidget::workingDirectory() const
776
{
777
    return d->m_workingDirectory;
778 779
}

780
void VcsBaseEditorWidget::setWorkingDirectory(const QString &wd)
781
{
782
    d->m_workingDirectory = wd;
783 784
}

hjk's avatar
hjk committed
785
QTextCodec *VcsBaseEditorWidget::codec() const
con's avatar
con committed
786
{
787
    return const_cast<QTextCodec *>(textDocument()->codec());
con's avatar
con committed
788 789
}

hjk's avatar
hjk committed
790
void VcsBaseEditorWidget::setCodec(QTextCodec *c)
con's avatar
con committed
791
{
792
    if (c)
793
        textDocument()->setCodec(c);
794
    else
con's avatar
con committed
795 796 797
        qWarning("%s: Attempt to set 0 codec.", Q_FUNC_INFO);
}

hjk's avatar
hjk committed
798
EditorContentType VcsBaseEditorWidget::contentType() const
con's avatar
con committed
799
{
800
    return d->m_parameters->type;
con's avatar
con committed
801 802
}

hjk's avatar
hjk committed
803
bool VcsBaseEditorWidget::isModified() const
con's avatar
con committed
804 805 806 807
{
    return false;
}

hjk's avatar
hjk committed
808
TextEditor::BaseTextEditor *VcsBaseEditorWidget::createEditor()
con's avatar
con committed
809
{
810
    QTC_ASSERT("should not happen anymore" && false, return 0);
811 812
}

hjk's avatar
hjk committed
813
void VcsBaseEditorWidget::slotPopulateDiffBrowser()
814
{
815 816
    QComboBox *entriesComboBox = d->entriesComboBox();
    entriesComboBox->clear();
Orgad Shaneh's avatar
Orgad Shaneh committed
817
    d->m_entrySections.clear();
818 819 820 821 822 823 824 825
    // Create a list of section line numbers (diffed files)
    // and populate combo with filenames.
    const QTextBlock cend = document()->end();
    int lineNumber = 0;
    QString lastFileName;
    for (QTextBlock it = document()->begin(); it != cend; it = it.next(), lineNumber++) {
        const QString text = it.text();
        // Check for a new diff section (not repeating the last filename)
826
        if (d->m_diffFilePattern.indexIn(text) == 0) {
827 828 829 830
            const QString file = fileNameFromDiffSpecification(it);
            if (!file.isEmpty() && lastFileName != file) {
                lastFileName = file;
                // ignore any headers
Orgad Shaneh's avatar
Orgad Shaneh committed
831
                d->m_entrySections.push_back(d->m_entrySections.empty() ? 0 : lineNumber);
832
                entriesComboBox->addItem(QFileInfo(file).fileName());
833 834 835 836 837
            }
        }
    }
}

838 839 840 841 842 843 844 845 846 847 848 849 850 851
void VcsBaseEditorWidget::slotPopulateLogBrowser()
{
    QComboBox *entriesComboBox = d->entriesComboBox();
    entriesComboBox->clear();
    d->m_entrySections.clear();
    // Create a list of section line numbers (log entries)
    // and populate combo with subjects (if any).
    const QTextBlock cend = document()->end();
    int lineNumber = 0;
    for (QTextBlock it = document()->begin(); it != cend; it = it.next(), lineNumber++) {
        const QString text = it.text();
        // Check for a new log section (not repeating the last filename)
        if (d->m_logEntryPattern.indexIn(text) != -1) {
            d->m_entrySections.push_back(d->m_entrySections.empty() ? 0 : lineNumber);
852 853 854 855 856 857 858 859 860 861
            QString entry = d->m_logEntryPattern.cap(1);
            QString subject = revisionSubject(it);
            if (!subject.isEmpty()) {
                if (subject.length() > 100) {
                    subject.truncate(97);
                    subject.append(QLatin1String("..."));
                }
                entry.append(QLatin1String(" - ")).append(subject);
            }
            entriesComboBox->addItem(entry);
862 863 864 865
        }
    }
}

866
void VcsBaseEditorWidget::slotJumpToEntry(int index)
867
{
868
    // goto diff/log entry as indicated by index/line number
Orgad Shaneh's avatar
Orgad Shaneh committed
869
    if (index < 0 || index >= d->m_entrySections.size())
870
        return;
Orgad Shaneh's avatar
Orgad Shaneh committed
871
    const int lineNumber = d->m_entrySections.at(index) + 1; // TextEdit uses 1..n convention
872 873 874 875
    // check if we need to do something, especially to avoid messing up navigation history
    int currentLine, currentColumn;
    convertPosition(position(), &currentLine, &currentColumn);
    if (lineNumber != currentLine) {
876
        Core::EditorManager::addCurrentPositionToNavigationHistory();
877 878
        gotoLine(lineNumber, 0);
    }
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
}

// Locate a line number in the list of diff sections.
static int sectionOfLine(int line, const QList<int> &sections)
{
    const int sectionCount = sections.size();
    if (!sectionCount)
        return -1;
    // The section at s indicates where the section begins.
    for (int s = 0; s < sectionCount; s++) {
        if (line < sections.at(s))
            return s - 1;
    }
    return sectionCount - 1;
}

895
void VcsBaseEditorWidget::slotCursorPositionChanged()
896
{
897
    // Adapt entries combo to new position
898
    // if the cursor goes across a file line.
899
    const int newCursorLine = textCursor().blockNumber();
900 901 902 903
    if (newCursorLine == d->m_cursorLine)
        return;
    // Which section does it belong to?
    d->m_cursorLine = newCursorLine;
Orgad Shaneh's avatar
Orgad Shaneh committed
904
    const int section = sectionOfLine(d->m_cursorLine, d->m_entrySections);
905
    if (section != -1) {
906 907 908 909 910
        QComboBox *entriesComboBox = d->entriesComboBox();
        if (entriesComboBox->currentIndex() != section) {
            const bool blocked = entriesComboBox->blockSignals(true);
            entriesComboBox->setCurrentIndex(section);
            entriesComboBox->blockSignals(blocked);
911 912
        }
    }
con's avatar
con committed
913 914
}

hjk's avatar
hjk committed
915
void VcsBaseEditorWidget::contextMenuEvent(QContextMenuEvent *e)
con's avatar
con committed
916
{
Orgad Shaneh's avatar
Orgad Shaneh committed
917
    QPointer<QMenu> menu = createStandardContextMenu();
con's avatar
con committed
918
    // 'click on change-interaction'
919
    if (supportChangeLinks()) {
920
        const QTextCursor cursor = cursorForPosition(e->pos());
921
        if (Internal::AbstractTextCursorHandler *handler = d->findTextCursorHandler(cursor))
922 923
            handler->fillContextMenu(menu, d->m_parameters->type);
    }
924 925
    switch (d->m_parameters->type) {
    case LogOutput: // log might have diff
926 927
    case DiffOutput: {
        menu->addSeparator();
928 929 930
        connect(menu->addAction(tr("Send to CodePaster...")), SIGNAL(triggered()),
                this, SLOT(slotPaste()));
        menu->addSeparator();
931
        // Apply/revert diff chunk.
932
        const DiffChunk chunk = diffChunk(cursorForPosition(e->pos()));
933 934
        if (!canApplyDiffChunk(chunk))
            break;
935 936 937 938 939 940 941 942 943 944 945 946
        // Apply a chunk from a diff loaded into the editor. This typically will
        // not have the 'source' property set and thus will only work if the working
        // directory matches that of the patch (see findDiffFile()). In addition,
        // the user has "Open With" and choose the right diff editor so that
        // fileNameFromDiffSpecification() works.
        QAction *applyAction = menu->addAction(tr("Apply Chunk..."));
        applyAction->setData(qVariantFromValue(Internal::DiffChunkAction(chunk, false)));
        connect(applyAction, SIGNAL(triggered()), this, SLOT(slotApplyDiffChunk()));
        // Revert a chunk from a VCS diff, which might be linked to reloading the diff.
        QAction *revertAction = menu->addAction(tr("Revert Chunk..."));
        revertAction->setData(qVariantFromValue(Internal::DiffChunkAction(chunk, true)));
        connect(revertAction, SIGNAL(triggered()), this, SLOT(slotApplyDiffChunk()));
947 948
        // Custom diff actions
        addDiffActions(menu, chunk);
949
        break;
950
    }
951 952
    default:
        break;
con's avatar
con committed
953
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
954
    connect(this, SIGNAL(destroyed()), menu, SLOT(deleteLater()));
con's avatar
con committed
955 956 957 958
    menu->exec(e->globalPos());
    delete menu;
}

hjk's avatar
hjk committed
959
void VcsBaseEditorWidget::mouseMoveEvent(QMouseEvent *e)
con's avatar
con committed
960
{
961 962 963 964 965 966
    if (e->buttons()) {
        d->m_mouseDragging = true;
        TextEditor::BaseTextEditorWidget::mouseMoveEvent(e);
        return;
    }

967 968 969
    bool overrideCursor = false;
    Qt::CursorShape cursorShape;

970
    if (supportChangeLinks()) {
con's avatar
con committed
971
        // Link emulation behaviour for 'click on change-interaction'
972 973 974 975
        const QTextCursor cursor = cursorForPosition(e->pos());
        Internal::AbstractTextCursorHandler *handler = d->findTextCursorHandler(cursor);
        if (handler != 0) {
            handler->highlightCurrentContents();
976 977
            overrideCursor = true;
            cursorShape = Qt::PointingHandCursor;
978 979 980 981
        } else {
            setExtraSelections(OtherSelection, QList<QTextEdit::ExtraSelection>());
            overrideCursor = true;
            cursorShape = Qt::IBeamCursor;
con's avatar
con committed
982 983
        }
    }
984
    TextEditor::BaseTextEditorWidget::mouseMoveEvent(e);
985 986 987

    if (overrideCursor)
        viewport()->setCursor(cursorShape);
con's avatar
con committed
988 989
}

hjk's avatar
hjk committed
990
void VcsBaseEditorWidget::mouseReleaseEvent(QMouseEvent *e)
con's avatar
con committed
991
{
992 993
    const bool wasDragging = d->m_mouseDragging;
    d->m_mouseDragging = false;
994
    if (!wasDragging && supportChangeLinks()) {
con's avatar
con committed
995
        if (e->button() == Qt::LeftButton &&!(e->modifiers() & Qt::ShiftModifier)) {
996 997 998 999
            const QTextCursor cursor = cursorForPosition(e->pos());
            Internal::AbstractTextCursorHandler *handler = d->findTextCursorHandler(cursor);
            if (handler != 0) {
                handler->handleCurrentContents();
con's avatar
con committed
1000 1001 1002 1003 1004
                e->accept();
                return;
            }
        }
    }
1005
    TextEditor::BaseTextEditorWidget::mouseReleaseEvent(e);
con's avatar
con committed
1006 1007
}

hjk's avatar
hjk committed
1008
void VcsBaseEditorWidget::mouseDoubleClickEvent(QMouseEvent *e)
con's avatar
con committed
1009
{
Orgad Shaneh's avatar
Orgad Shaneh committed
1010 1011 1012
    if (hasDiff() && e->button() == Qt::LeftButton && !(e->modifiers() & Qt::ShiftModifier)) {
        QTextCursor cursor = cursorForPosition(e->pos());
        jumpToChangeFromDiff(cursor);
con's avatar
con committed
1013
    }
1014
    TextEditor::BaseTextEditorWidget::mouseDoubleClickEvent(e);
con's avatar
con committed
1015 1016
}

hjk's avatar
hjk committed
1017
void VcsBaseEditorWidget::keyPressEvent(QKeyEvent *e)
con's avatar
con committed
1018
{
1019
    // Do not intercept return in editable patches.
Orgad Shaneh's avatar
Orgad Shaneh committed