vcsbaseeditor.cpp 29.8 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** 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.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31 32 33 34 35
#include "vcsbaseeditor.h"
#include "diffhighlighter.h"
#include "baseannotationhighlighter.h"
#include "vcsbasetextdocument.h"
#include "vcsbaseconstants.h"

36
#include <coreplugin/editormanager/editormanager.h>
37
#include <coreplugin/ifile.h>
38
#include <coreplugin/iversioncontrol.h>
39 40
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/editorconfiguration.h>
con's avatar
con committed
41
#include <projectexplorer/projectexplorer.h>
42
#include <projectexplorer/project.h>
con's avatar
con committed
43
#include <projectexplorer/session.h>
44 45
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>
46
#include <utils/qtcassert.h>
con's avatar
con committed
47

48
#include <QtCore/QDebug>
con's avatar
con committed
49
#include <QtCore/QFileInfo>
50
#include <QtCore/QProcess>
con's avatar
con committed
51
#include <QtCore/QRegExp>
52
#include <QtCore/QSet>
con's avatar
con committed
53
#include <QtCore/QTextCodec>
54 55
#include <QtCore/QTextStream>
#include <QtGui/QAction>
con's avatar
con committed
56 57 58 59
#include <QtGui/QKeyEvent>
#include <QtGui/QLayout>
#include <QtGui/QMenu>
#include <QtGui/QTextCursor>
60
#include <QtGui/QTextEdit>
61 62
#include <QtGui/QComboBox>
#include <QtGui/QToolBar>
63 64
#include <QtGui/QClipboard>
#include <QtGui/QApplication>
con's avatar
con committed
65 66 67 68

namespace VCSBase {

// VCSBaseEditorEditable: An editable with no support for duplicates
69
// Creates a browse combo in the toolbar for diff output.
70 71
// It also mirrors the signals of the VCSBaseEditor since the editor
// manager passes the Editable around.
con's avatar
con committed
72 73
class VCSBaseEditorEditable : public TextEditor::BaseTextEditorEditable
{
74
    Q_OBJECT
con's avatar
con committed
75 76
public:
    VCSBaseEditorEditable(VCSBaseEditor *,
77
                          const VCSBaseEditorParameters *type);
78
    Core::Context context() const;
con's avatar
con committed
79 80 81

    bool duplicateSupported() const { return false; }
    Core::IEditor *duplicate(QWidget * /*parent*/) { return 0; }
82
    QString id() const { return m_id; }
con's avatar
con committed
83

84 85
    bool isTemporary() const { return m_temporary; }
    void setTemporary(bool t) { m_temporary = t; }
dt's avatar
dt committed
86

87 88
signals:
    void describeRequested(const QString &source, const QString &change);
89
    void annotateRevisionRequested(const QString &source, const QString &change, int line);
90

con's avatar
con committed
91
private:
92
    QString m_id;
93
    Core::Context m_context;
94
    bool m_temporary;
con's avatar
con committed
95 96 97
};

VCSBaseEditorEditable::VCSBaseEditorEditable(VCSBaseEditor *editor,
98 99
                                             const VCSBaseEditorParameters *type)  :
    BaseTextEditorEditable(editor),
100
    m_id(type->id),
101
    m_context(type->context, TextEditor::Constants::C_TEXTEDITOR),
102
    m_temporary(false)
con's avatar
con committed
103 104 105
{
}

106
Core::Context VCSBaseEditorEditable::context() const
con's avatar
con committed
107 108 109 110
{
    return m_context;
}

111 112 113 114 115
// Diff editable: creates a browse combo in the toolbar for diff output.
class VCSBaseDiffEditorEditable : public VCSBaseEditorEditable
{
public:
    VCSBaseDiffEditorEditable(VCSBaseEditor *, const VCSBaseEditorParameters *type);
dt's avatar
dt committed
116
    ~VCSBaseDiffEditorEditable();
117

con's avatar
con committed
118
    virtual QWidget *toolBar()                { return m_toolBar; }
119 120 121 122
    QComboBox *diffFileBrowseComboBox() const  { return m_diffFileBrowseComboBox; }

private:
    QToolBar *m_toolBar;
dt's avatar
dt committed
123
    QComboBox *m_diffFileBrowseComboBox;
124 125 126 127
};

VCSBaseDiffEditorEditable::VCSBaseDiffEditorEditable(VCSBaseEditor *e, const VCSBaseEditorParameters *type) :
    VCSBaseEditorEditable(e, type),
dt's avatar
dt committed
128 129
    m_toolBar(new QToolBar),
    m_diffFileBrowseComboBox(new QComboBox(m_toolBar))
130 131 132 133 134 135 136 137 138 139
{
    m_diffFileBrowseComboBox->setMinimumContentsLength(20);
    m_diffFileBrowseComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    // Make the combo box prefer to expand
    QSizePolicy policy = m_diffFileBrowseComboBox->sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_diffFileBrowseComboBox->setSizePolicy(policy);
    m_toolBar->addWidget(m_diffFileBrowseComboBox);
}

dt's avatar
dt committed
140 141 142 143 144
VCSBaseDiffEditorEditable::~VCSBaseDiffEditorEditable()
{
    delete m_toolBar;
}

con's avatar
con committed
145 146
// ----------- VCSBaseEditorPrivate

147 148
struct VCSBaseEditorPrivate
{
149
    VCSBaseEditorPrivate(const VCSBaseEditorParameters *type);
con's avatar
con committed
150 151

    const VCSBaseEditorParameters *m_parameters;
152

con's avatar
con committed
153 154
    QString m_currentChange;
    QString m_source;
155
    QString m_diffBaseDirectory;
156 157 158 159

    QRegExp m_diffFilePattern;
    QList<int> m_diffSections; // line number where this section starts
    int m_cursorLine;
160
    QString m_annotateRevisionTextFormat;
161
    QString m_copyRevisionTextFormat;
162
    bool m_fileLogAnnotateEnabled;
con's avatar
con committed
163 164
};

165 166 167 168
VCSBaseEditorPrivate::VCSBaseEditorPrivate(const VCSBaseEditorParameters *type)  :
    m_parameters(type),
    m_cursorLine(-1),
    m_annotateRevisionTextFormat(VCSBaseEditor::tr("Annotate \"%1\"")),
169
    m_copyRevisionTextFormat(VCSBaseEditor::tr("Copy \"%1\"")),
170
    m_fileLogAnnotateEnabled(false)
con's avatar
con committed
171 172 173 174
{
}

// ------------ VCSBaseEditor
175 176
VCSBaseEditor::VCSBaseEditor(const VCSBaseEditorParameters *type, QWidget *parent)
  : BaseTextEditor(parent),
177
    d(new VCSBaseEditorPrivate(type))
con's avatar
con committed
178 179
{
    if (VCSBase::Constants::Internal::debug)
180
        qDebug() << "VCSBaseEditor::VCSBaseEditor" << type->type << type->id;
con's avatar
con committed
181 182 183

    viewport()->setMouseTracking(true);
    setBaseTextDocument(new Internal::VCSBaseTextDocument);
184
    setMimeType(QLatin1String(d->m_parameters->mimeType));
con's avatar
con committed
185 186 187 188
}

void VCSBaseEditor::init()
{
189
    switch (d->m_parameters->type) {
con's avatar
con committed
190 191 192 193 194 195
    case RegularCommandOutput:
    case LogOutput:
    case AnnotateOutput:
        // Annotation highlighting depends on contents, which is set later on
        connect(this, SIGNAL(textChanged()), this, SLOT(slotActivateAnnotation()));
        break;
196 197 198 199 200 201 202
    case DiffOutput: {
        DiffHighlighter *dh = createDiffHighlighter();
        baseTextDocument()->setSyntaxHighlighter(dh);
        d->m_diffFilePattern = dh->filePattern();
        connect(this, SIGNAL(textChanged()), this, SLOT(slotPopulateDiffBrowser()));
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotDiffCursorPositionChanged()));
    }
con's avatar
con committed
203 204 205 206 207 208
        break;
    }
}

VCSBaseEditor::~VCSBaseEditor()
{
209
    delete d;
con's avatar
con committed
210 211
}

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
void VCSBaseEditor::setForceReadOnly(bool b)
{
    Internal::VCSBaseTextDocument *vbd = qobject_cast<Internal::VCSBaseTextDocument*>(baseTextDocument());
    VCSBaseEditorEditable *eda = qobject_cast<VCSBaseEditorEditable *>(editableInterface());
    QTC_ASSERT(vbd != 0 && eda != 0, return);
    setReadOnly(b);
    vbd->setForceReadOnly(b);
    eda->setTemporary(b);
}

bool VCSBaseEditor::isForceReadOnly() const
{
    const Internal::VCSBaseTextDocument *vbd = qobject_cast<const Internal::VCSBaseTextDocument*>(baseTextDocument());
    QTC_ASSERT(vbd, return false);
    return vbd->isForceReadOnly();
}

con's avatar
con committed
229 230
QString VCSBaseEditor::source() const
{
231
    return d->m_source;
con's avatar
con committed
232 233 234 235
}

void VCSBaseEditor::setSource(const  QString &source)
{
236
    d->m_source = source;
con's avatar
con committed
237 238
}

239 240 241 242 243 244 245 246 247 248
QString VCSBaseEditor::annotateRevisionTextFormat() const
{
    return d->m_annotateRevisionTextFormat;
}

void VCSBaseEditor::setAnnotateRevisionTextFormat(const QString &f)
{
    d->m_annotateRevisionTextFormat = f;
}

249 250 251 252 253 254 255 256 257 258
QString VCSBaseEditor::copyRevisionTextFormat() const
{
    return d->m_copyRevisionTextFormat;
}

void VCSBaseEditor::setCopyRevisionTextFormat(const QString &f)
{
    d->m_copyRevisionTextFormat = f;
}

259 260 261 262 263 264 265 266 267 268
bool VCSBaseEditor::isFileLogAnnotateEnabled() const
{
    return d->m_fileLogAnnotateEnabled;
}

void VCSBaseEditor::setFileLogAnnotateEnabled(bool e)
{
    d->m_fileLogAnnotateEnabled = e;
}

269 270 271 272 273 274 275 276 277 278
QString VCSBaseEditor::diffBaseDirectory() const
{
    return d->m_diffBaseDirectory;
}

void VCSBaseEditor::setDiffBaseDirectory(const QString &bd)
{
    d->m_diffBaseDirectory = bd;
}

con's avatar
con committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
QTextCodec *VCSBaseEditor::codec() const
{
    return baseTextDocument()->codec();
}

void VCSBaseEditor::setCodec(QTextCodec *c)
{
    if (c) {
        baseTextDocument()->setCodec(c);
    } else {
        qWarning("%s: Attempt to set 0 codec.", Q_FUNC_INFO);
    }
}

EditorContentType VCSBaseEditor::contentType() const
{
295
    return d->m_parameters->type;
con's avatar
con committed
296 297 298 299 300 301 302 303 304
}

bool VCSBaseEditor::isModified() const
{
    return false;
}

TextEditor::BaseTextEditorEditable *VCSBaseEditor::createEditableInterface()
{
305 306 307 308 309
    TextEditor::BaseTextEditorEditable *editable = 0;
    if (d->m_parameters->type == DiffOutput) {
        // Diff: set up diff file browsing
        VCSBaseDiffEditorEditable *de = new VCSBaseDiffEditorEditable(this, d->m_parameters);
        QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
310
        connect(diffBrowseComboBox, SIGNAL(activated(int)), this, SLOT(slotDiffBrowse(int)));
311 312 313 314 315 316 317
        editable = de;
    } else {
        editable = new VCSBaseEditorEditable(this, d->m_parameters);
    }
    // Pass on signals.
    connect(this, SIGNAL(describeRequested(QString,QString)),
            editable, SIGNAL(describeRequested(QString,QString)));
318 319
    connect(this, SIGNAL(annotateRevisionRequested(QString,QString,int)),
            editable, SIGNAL(annotateRevisionRequested(QString,QString,int)));
320
    return editable;
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
}

void VCSBaseEditor::slotPopulateDiffBrowser()
{
    VCSBaseDiffEditorEditable *de = static_cast<VCSBaseDiffEditorEditable*>(editableInterface());
    QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
    diffBrowseComboBox->clear();
    d->m_diffSections.clear();
    // 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)
        if (d->m_diffFilePattern.exactMatch(text)) {
            const QString file = fileNameFromDiffSpecification(it);
            if (!file.isEmpty() && lastFileName != file) {
                lastFileName = file;
                // ignore any headers
                d->m_diffSections.push_back(d->m_diffSections.empty() ? 0 : lineNumber);
                diffBrowseComboBox->addItem(QFileInfo(file).fileName());
            }
        }
    }
}

349
void VCSBaseEditor::slotDiffBrowse(int index)
350 351 352
{
    // goto diffed file as indicated by index/line number
    if (index < 0 || index >= d->m_diffSections.size())
353
        return;
354 355 356 357 358 359 360 361 362
    const int lineNumber = d->m_diffSections.at(index) + 1; // TextEdit uses 1..n convention
    // check if we need to do something, especially to avoid messing up navigation history
    int currentLine, currentColumn;
    convertPosition(position(), &currentLine, &currentColumn);
    if (lineNumber != currentLine) {
        Core::EditorManager *editorManager = Core::EditorManager::instance();
        editorManager->addCurrentPositionToNavigationHistory();
        gotoLine(lineNumber, 0);
    }
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
}

// 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;
}

void VCSBaseEditor::slotDiffCursorPositionChanged()
{
    // Adapt diff file browse combo to new position
    // if the cursor goes across a file line.
    QTC_ASSERT(d->m_parameters->type == DiffOutput, return)
384
    const int newCursorLine = textCursor().blockNumber();
385 386 387 388 389 390 391 392 393 394 395 396 397 398
    if (newCursorLine == d->m_cursorLine)
        return;
    // Which section does it belong to?
    d->m_cursorLine = newCursorLine;
    const int section = sectionOfLine(d->m_cursorLine, d->m_diffSections);
    if (section != -1) {
        VCSBaseDiffEditorEditable *de = static_cast<VCSBaseDiffEditorEditable*>(editableInterface());
        QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
        if (diffBrowseComboBox->currentIndex() != section) {
            const bool blocked = diffBrowseComboBox->blockSignals(true);
            diffBrowseComboBox->setCurrentIndex(section);
            diffBrowseComboBox->blockSignals(blocked);
        }
    }
con's avatar
con committed
399 400
}

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
QAction *VCSBaseEditor::createDescribeAction(const QString &change)
{
    QAction *a = new QAction(tr("Describe change %1").arg(change), 0);
    connect(a, SIGNAL(triggered()), this, SLOT(describe()));
    return a;
}

QAction *VCSBaseEditor::createAnnotateAction(const QString &change)
{
    QAction *a = new QAction(d->m_annotateRevisionTextFormat.arg(change), 0);
    a->setData(change);
    connect(a, SIGNAL(triggered()), this, SLOT(slotAnnotateRevision()));
    return a;
}

416 417 418 419 420 421 422 423
QAction *VCSBaseEditor::createCopyRevisionAction(const QString &change)
{
    QAction *a = new QAction(d->m_copyRevisionTextFormat.arg(change), 0);
    a->setData(change);
    connect(a, SIGNAL(triggered()), this, SLOT(slotCopyRevision()));
    return a;
}

con's avatar
con committed
424 425 426 427
void VCSBaseEditor::contextMenuEvent(QContextMenuEvent *e)
{
    QMenu *menu = createStandardContextMenu();
    // 'click on change-interaction'
428 429 430
    if (d->m_parameters->type == LogOutput || d->m_parameters->type == AnnotateOutput) {
        d->m_currentChange = changeUnderCursor(cursorForPosition(e->pos()));
        if (!d->m_currentChange.isEmpty()) {
431 432 433
            switch (d->m_parameters->type) {
            case LogOutput: // Describe current / Annotate file of current
                menu->addSeparator();
434
                menu->addAction(createCopyRevisionAction(d->m_currentChange));
435 436 437 438 439
                menu->addAction(createDescribeAction(d->m_currentChange));
                if (d->m_fileLogAnnotateEnabled)
                    menu->addAction(createAnnotateAction(d->m_currentChange));
                break;
            case AnnotateOutput: { // Describe current / annotate previous
440
                    menu->addSeparator();
441
                    menu->addAction(createCopyRevisionAction(d->m_currentChange));
442 443 444 445 446 447 448
                    menu->addAction(createDescribeAction(d->m_currentChange));
                    const QStringList previousVersions = annotationPreviousVersions(d->m_currentChange);
                    if (!previousVersions.isEmpty()) {
                        menu->addSeparator();
                        foreach(const QString &pv, previousVersions)
                            menu->addAction(createAnnotateAction(pv));
                    } // has previous versions
449
                }
450 451 452 453 454
                break;
            default:
                break;
            }         // switch type
        }             // has current change
con's avatar
con committed
455 456 457 458 459 460 461
    }
    menu->exec(e->globalPos());
    delete menu;
}

void VCSBaseEditor::mouseMoveEvent(QMouseEvent *e)
{
462 463 464
    bool overrideCursor = false;
    Qt::CursorShape cursorShape;

465
    if (d->m_parameters->type == LogOutput || d->m_parameters->type == AnnotateOutput) {
con's avatar
con committed
466 467 468 469 470 471 472 473 474
        // Link emulation behaviour for 'click on change-interaction'
        QTextCursor cursor = cursorForPosition(e->pos());
        QString change = changeUnderCursor(cursor);
        if (!change.isEmpty()) {
            QTextEdit::ExtraSelection sel;
            sel.cursor = cursor;
            sel.cursor.select(QTextCursor::WordUnderCursor);
            sel.format.setFontUnderline(true);
            sel.format.setProperty(QTextFormat::UserProperty, change);
475
            setExtraSelections(OtherSelection, QList<QTextEdit::ExtraSelection>() << sel);
476 477
            overrideCursor = true;
            cursorShape = Qt::PointingHandCursor;
con's avatar
con committed
478
        }
479 480
    } else {
        setExtraSelections(OtherSelection, QList<QTextEdit::ExtraSelection>());
481 482
        overrideCursor = true;
        cursorShape = Qt::IBeamCursor;
con's avatar
con committed
483 484
    }
    TextEditor::BaseTextEditor::mouseMoveEvent(e);
485 486 487

    if (overrideCursor)
        viewport()->setCursor(cursorShape);
con's avatar
con committed
488 489 490 491
}

void VCSBaseEditor::mouseReleaseEvent(QMouseEvent *e)
{
492
    if (d->m_parameters->type == LogOutput || d->m_parameters->type == AnnotateOutput) {
con's avatar
con committed
493 494
        if (e->button() == Qt::LeftButton &&!(e->modifiers() & Qt::ShiftModifier)) {
            QTextCursor cursor = cursorForPosition(e->pos());
495 496
            d->m_currentChange = changeUnderCursor(cursor);
            if (!d->m_currentChange.isEmpty()) {
con's avatar
con committed
497 498 499 500 501 502 503 504 505 506 507
                describe();
                e->accept();
                return;
            }
        }
    }
    TextEditor::BaseTextEditor::mouseReleaseEvent(e);
}

void VCSBaseEditor::mouseDoubleClickEvent(QMouseEvent *e)
{
508
    if (d->m_parameters->type == DiffOutput) {
con's avatar
con committed
509 510 511 512 513 514 515 516 517 518
        if (e->button() == Qt::LeftButton &&!(e->modifiers() & Qt::ShiftModifier)) {
            QTextCursor cursor = cursorForPosition(e->pos());
            jumpToChangeFromDiff(cursor);
        }
    }
    TextEditor::BaseTextEditor::mouseDoubleClickEvent(e);
}

void VCSBaseEditor::keyPressEvent(QKeyEvent *e)
{
519 520 521
    // Do not intercept return in editable patches.
    if (d->m_parameters->type == DiffOutput && isReadOnly()
        && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)) {
con's avatar
con committed
522 523 524 525 526 527 528 529 530
        jumpToChangeFromDiff(textCursor());
        return;
    }
    BaseTextEditor::keyPressEvent(e);
}

void VCSBaseEditor::describe()
{
    if (VCSBase::Constants::Internal::debug)
531 532 533
        qDebug() << "VCSBaseEditor::describe" << d->m_currentChange;
    if (!d->m_currentChange.isEmpty())
        emit describeRequested(d->m_source, d->m_currentChange);
con's avatar
con committed
534 535 536 537 538 539
}

void VCSBaseEditor::slotActivateAnnotation()
{
    // The annotation highlighting depends on contents (change number
    // set with assigned colors)
540
    if (d->m_parameters->type != AnnotateOutput)
con's avatar
con committed
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
        return;

    const QSet<QString> changes = annotationChanges();
    if (changes.isEmpty())
        return;
    if (VCSBase::Constants::Internal::debug)
        qDebug() << "VCSBaseEditor::slotActivateAnnotation(): #" << changes.size();

    disconnect(this, SIGNAL(textChanged()), this, SLOT(slotActivateAnnotation()));

    if (BaseAnnotationHighlighter *ah = qobject_cast<BaseAnnotationHighlighter *>(baseTextDocument()->syntaxHighlighter())) {
        ah->setChangeNumbers(changes);
        ah->rehighlight();
    } else {
        baseTextDocument()->setSyntaxHighlighter(createAnnotationHighlighter(changes));
    }
}

// Check for a change chunk "@@ -91,7 +95,7 @@" and return
// the modified line number (95).
// Note that git appends stuff after "  @@" (function names, etc.).
static inline bool checkChunkLine(const QString &line, int *modifiedLineNumber)
{
    if (!line.startsWith(QLatin1String("@@ ")))
        return false;
    const int endPos = line.indexOf(QLatin1String(" @@"), 3);
    if (endPos == -1)
        return false;
    // the first chunk range applies to the original file, the second one to
    // the modified file, the one we're interested int
    const int plusPos = line.indexOf(QLatin1Char('+'), 3);
    if (plusPos == -1 || plusPos > endPos)
        return false;
    const int lineNumberPos = plusPos + 1;
    const int commaPos = line.indexOf(QLatin1Char(','), lineNumberPos);
    if (commaPos == -1 || commaPos > endPos)
        return false;
    const QString lineNumberStr = line.mid(lineNumberPos, commaPos - lineNumberPos);
    bool ok;
    *modifiedLineNumber = lineNumberStr.toInt(&ok);
    return ok;
}

void VCSBaseEditor::jumpToChangeFromDiff(QTextCursor cursor)
{
    int chunkStart = 0;
    int lineCount = -1;
    const QChar deletionIndicator = QLatin1Char('-');
    // find nearest change hunk
    QTextBlock block = cursor.block();
    for ( ; block.isValid() ; block = block.previous()) {
        const QString line = block.text();
        if (checkChunkLine(line, &chunkStart)) {
            break;
        } else {
            if (!line.startsWith(deletionIndicator))
                ++lineCount;
        }
    }

    if (VCSBase::Constants::Internal::debug)
        qDebug() << "VCSBaseEditor::jumpToChangeFromDiff()1" << chunkStart << lineCount;

    if (chunkStart == -1 || lineCount < 0 || !block.isValid())
        return;

    // find the filename in previous line, map depot name back
    block = block.previous();
    if (!block.isValid())
        return;
    const QString fileName = fileNameFromDiffSpecification(block);

    const bool exists = fileName.isEmpty() ? false : QFile::exists(fileName);

    if (VCSBase::Constants::Internal::debug)
        qDebug() << "VCSBaseEditor::jumpToChangeFromDiff()2" << fileName << "ex=" << exists << "line" << chunkStart <<  lineCount;

    if (!exists)
        return;

621
    Core::EditorManager *em = Core::EditorManager::instance();
622 623 624
    Core::IEditor *ed = em->openEditor(fileName);
    em->ensureEditorManagerVisible();
    if (TextEditor::ITextEditor *editor = qobject_cast<TextEditor::ITextEditor *>(ed))
con's avatar
con committed
625 626 627 628 629
        editor->gotoLine(chunkStart + lineCount);
}

void VCSBaseEditor::setPlainTextData(const QByteArray &data)
{
630 631 632 633 634
    if (data.size() > Core::EditorManager::maxTextFileSize()) {
        setPlainText(msgTextTooLarge(data.size()));
    } else {
        setPlainText(codec()->toUnicode(data));
    }
con's avatar
con committed
635 636 637 638 639
}

void VCSBaseEditor::setFontSettings(const TextEditor::FontSettings &fs)
{
    TextEditor::BaseTextEditor::setFontSettings(fs);
640
    if (d->m_parameters->type == DiffOutput) {
con's avatar
con committed
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
        if (DiffHighlighter *highlighter = qobject_cast<DiffHighlighter*>(baseTextDocument()->syntaxHighlighter())) {
            static QVector<QString> categories;
            if (categories.isEmpty()) {
                categories << QLatin1String(TextEditor::Constants::C_TEXT)
                           << QLatin1String(TextEditor::Constants::C_ADDED_LINE)
                           << QLatin1String(TextEditor::Constants::C_REMOVED_LINE)
                           << QLatin1String(TextEditor::Constants::C_DIFF_FILE)
                           << QLatin1String(TextEditor::Constants::C_DIFF_LOCATION);
            }
            highlighter->setFormats(fs.toTextCharFormats(categories));
            highlighter->rehighlight();
        }
    }
}

const VCSBaseEditorParameters *VCSBaseEditor::findType(const VCSBaseEditorParameters *array,
                                                       int arraySize,
                                                       EditorContentType et)
{
    for (int i = 0; i < arraySize; i++)
        if (array[i].type == et)
            return array + i;
    return 0;
}

// Find the codec used for a file querying the editor.
667
static QTextCodec *findFileCodec(const QString &source)
con's avatar
con committed
668 669 670
{
    typedef QList<Core::IEditor *> EditorList;

671
    const EditorList editors = Core::EditorManager::instance()->editorsForFileName(source);
con's avatar
con committed
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
    if (!editors.empty()) {
        const EditorList::const_iterator ecend =  editors.constEnd();
        for (EditorList::const_iterator it = editors.constBegin(); it != ecend; ++it)
            if (const TextEditor::BaseTextEditorEditable *be = qobject_cast<const TextEditor::BaseTextEditorEditable *>(*it)) {
                QTextCodec *codec = be->editor()->textCodec();
                if (VCSBase::Constants::Internal::debug)
                    qDebug() << Q_FUNC_INFO << source << codec->name();
                return codec;
            }
    }
    if (VCSBase::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << source << "not found";
    return 0;
}

// Find the codec by checking the projects (root dir of project file)
static QTextCodec *findProjectCodec(const QString &dir)
{
    typedef  QList<ProjectExplorer::Project*> ProjectList;
    // Try to find a project under which file tree the file is.
    const ProjectExplorer::SessionManager *sm = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
    const ProjectList projects = sm->projects();
    if (!projects.empty()) {
        const ProjectList::const_iterator pcend = projects.constEnd();
        for (ProjectList::const_iterator it = projects.constBegin(); it != pcend; ++it)
            if (const Core::IFile *file = (*it)->file())
                if (file->fileName().startsWith(dir)) {
                    QTextCodec *codec = (*it)->editorConfiguration()->defaultTextCodec();
                    if (VCSBase::Constants::Internal::debug)
701
                        qDebug() << Q_FUNC_INFO << dir << (*it)->displayName() << codec->name();
con's avatar
con committed
702 703 704 705 706 707 708 709
                    return codec;
                }
    }
    if (VCSBase::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << dir << "not found";
    return 0;
}

710
QTextCodec *VCSBaseEditor::getCodec(const QString &source)
con's avatar
con committed
711 712 713 714 715
{
    if (!source.isEmpty()) {
        // Check file
        const QFileInfo sourceFi(source);
        if (sourceFi.isFile())
716
            if (QTextCodec *fc = findFileCodec(source))
con's avatar
con committed
717 718 719 720 721 722 723 724 725 726 727
                return fc;
        // Find by project via directory
        if (QTextCodec *pc = findProjectCodec(sourceFi.isFile() ? sourceFi.absolutePath() : source))
            return pc;
    }
    QTextCodec *sys = QTextCodec::codecForLocale();
    if (VCSBase::Constants::Internal::debug)
        qDebug() << Q_FUNC_INFO << source << "defaulting to " << sys->name();
    return sys;
}

728 729 730 731 732 733 734
QTextCodec *VCSBaseEditor::getCodec(const QString &workingDirectory, const QStringList &files)
{
    if (files.empty())
        return getCodec(workingDirectory);
    return getCodec(workingDirectory + QLatin1Char('/') + files.front());
}

con's avatar
con committed
735 736 737 738 739 740 741
VCSBaseEditor *VCSBaseEditor::getVcsBaseEditor(const Core::IEditor *editor)
{
    if (const TextEditor::BaseTextEditorEditable *be = qobject_cast<const TextEditor::BaseTextEditorEditable *>(editor))
        return qobject_cast<VCSBaseEditor *>(be->editor());
    return 0;
}

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
// Return line number of current editor if it matches.
int VCSBaseEditor::lineNumberOfCurrentEditor(const QString &currentFile)
{
    Core::IEditor *ed = Core::EditorManager::instance()->currentEditor();
    if (!ed)
        return -1;
    if (!currentFile.isEmpty()) {
        const Core::IFile *ifile  = ed->file();
        if (!ifile || ifile->fileName() != currentFile)
            return -1;
    }
    const TextEditor::BaseTextEditorEditable *eda = qobject_cast<const TextEditor::BaseTextEditorEditable *>(ed);
    if (!eda)
        return -1;
    return eda->currentLine();
}

bool VCSBaseEditor::gotoLineOfEditor(Core::IEditor *e, int lineNumber)
{
    if (lineNumber >= 0 && e) {
        if (TextEditor::BaseTextEditorEditable *be = qobject_cast<TextEditor::BaseTextEditorEditable*>(e)) {
            be->gotoLine(lineNumber);
            return true;
        }
    }
    return false;
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
// Return source file or directory string depending on parameters
// ('git diff XX' -> 'XX' , 'git diff XX file' -> 'XX/file').
QString VCSBaseEditor::getSource(const QString &workingDirectory,
                                 const QString &fileName)
{
    if (fileName.isEmpty())
        return workingDirectory;

    QString rc = workingDirectory;
    const QChar slash = QLatin1Char('/');
    if (!rc.isEmpty() && !(rc.endsWith(slash) || rc.endsWith(QLatin1Char('\\'))))
        rc += slash;
    rc += fileName;
    return rc;
}

QString VCSBaseEditor::getSource(const QString &workingDirectory,
                                 const QStringList &fileNames)
{
    return fileNames.size() == 1 ?
            getSource(workingDirectory, fileNames.front()) :
            workingDirectory;
}

794 795 796
QString VCSBaseEditor::getTitleId(const QString &workingDirectory,
                                  const QStringList &fileNames,
                                  const QString &revision)
797
{
798
    QString rc;
799 800
    switch (fileNames.size()) {
    case 0:
801 802
        rc = workingDirectory;
        break;
803
    case 1:
804 805
        rc = fileNames.front();
        break;
806
    default:
807
        rc = fileNames.join(QLatin1String(", "));
808 809
        break;
    }
810 811 812 813 814
    if (!revision.isEmpty()) {
        rc += QLatin1Char(':');
        rc += revision;
    }
    return rc;
815
}
816

817 818 819
// Find the complete file from a diff relative specification.
QString VCSBaseEditor::findDiffFile(const QString &f, Core::IVersionControl *control /* = 0 */) const
{
820
    // Try the file itself, expand to absolute.
821 822 823 824 825
    const QFileInfo in(f);
    if (in.isAbsolute())
        return in.isFile() ? f : QString();
    if (in.isFile())
        return in.absoluteFilePath();
826 827 828 829 830 831 832 833
    // 1) Try base dir
    const QChar slash = QLatin1Char('/');
    if (!d->m_diffBaseDirectory.isEmpty()) {
        const QFileInfo baseFileInfo(d->m_diffBaseDirectory + slash + f);
        if (baseFileInfo.isFile())
            return baseFileInfo.absoluteFilePath();
    }
    // 2) Try in source (which can be file or directory)
834 835 836 837
    if (source().isEmpty())
        return QString();
    const QFileInfo sourceInfo(source());
    const QString sourceDir = sourceInfo.isDir() ? sourceInfo.absoluteFilePath() : sourceInfo.absolutePath();
838
    const QFileInfo sourceFileInfo(sourceDir + slash + f);
839 840 841 842 843
    if (sourceFileInfo.isFile())
        return sourceFileInfo.absoluteFilePath();
    // Try to locate via repository.
    if (!control)
        return QString();
844 845
    QString topLevel;
    if (!control->managesDirectory(sourceDir, &topLevel))
846
        return QString();
847
    const QFileInfo topLevelFileInfo(topLevel + slash + f);
848 849 850 851 852
    if (topLevelFileInfo.isFile())
        return topLevelFileInfo.absoluteFilePath();
    return QString();
}

853
void VCSBaseEditor::slotAnnotateRevision()
854 855
{
    if (const QAction *a = qobject_cast<const QAction *>(sender()))
856
        emit annotateRevisionRequested(source(), a->data().toString(),
857 858 859
                                       editableInterface()->currentLine());
}

860 861 862 863 864
void VCSBaseEditor::slotCopyRevision()
{
    QApplication::clipboard()->setText(d->m_currentChange);
}

865
QStringList VCSBaseEditor::annotationPreviousVersions(const QString &) const
866 867 868 869
{
    return QStringList();
}

hjk's avatar
hjk committed
870
} // namespace VCSBase
871 872

#include "vcsbaseeditor.moc"