aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/diffeditor/diffeditordocument.cpp
blob: 0845f3ef03c82bc4e0e1a8750734a211ff588e86 (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "diffeditordocument.h"
#include "diffeditorconstants.h"
#include "diffeditorcontroller.h"
#include "diffutils.h"

#include <utils/fileutils.h>
#include <utils/qtcassert.h>

#include <coreplugin/editormanager/editormanager.h>

#include <QCoreApplication>
#include <QFile>
#include <QDir>
#include <QMenu>
#include <QTextCodec>
#include <QUuid>

using namespace Utils;

namespace DiffEditor {
namespace Internal {

DiffEditorDocument::DiffEditorDocument() :
    Core::BaseTextDocument()
{
    setId(Constants::DIFF_EDITOR_ID);
    setMimeType(Constants::DIFF_EDITOR_MIMETYPE);
    setTemporary(true);
}

/**
 * @brief Set a controller for a document
 * @param controller The controller to set.
 *
 * This method takes ownership of the controller and will delete it after it is done with it.
 */
void DiffEditorDocument::setController(DiffEditorController *controller)
{
    if (m_controller == controller)
        return;

    QTC_ASSERT(isTemporary(), return);

    if (m_controller)
        m_controller->deleteLater();
    m_controller = controller;

    if (m_controller) {
        connect(this, &DiffEditorDocument::requestMoreInformation,
                m_controller, &DiffEditorController::requestMoreInformation);
    }
}

DiffEditorController *DiffEditorDocument::controller() const
{
    return m_controller;
}

QString DiffEditorDocument::makePatch(int fileIndex, int chunkIndex,
                                      bool revert, bool addPrefix,
                                      const QString &overriddenFileName) const
{
    if (fileIndex < 0 || chunkIndex < 0)
        return QString();

    if (fileIndex >= m_diffFiles.count())
        return QString();

    const FileData &fileData = m_diffFiles.at(fileIndex);
    if (chunkIndex >= fileData.chunks.count())
        return QString();

    const ChunkData &chunkData = fileData.chunks.at(chunkIndex);
    const bool lastChunk = (chunkIndex == fileData.chunks.count() - 1);

    const QString fileName = !overriddenFileName.isEmpty()
            ? overriddenFileName : revert
              ? fileData.rightFileInfo.fileName
              : fileData.leftFileInfo.fileName;

    QString leftPrefix, rightPrefix;
    if (addPrefix) {
        leftPrefix = "a/";
        rightPrefix = "b/";
    }
    return DiffUtils::makePatch(chunkData,
                                leftPrefix + fileName,
                                rightPrefix + fileName,
                                lastChunk && fileData.lastChunkAtTheEndOfFile);
}

void DiffEditorDocument::setDiffFiles(const QList<FileData> &data, const QString &directory,
                                      const QString &startupFile)
{
    m_diffFiles = data;
    m_baseDirectory = directory;
    m_startupFile = startupFile;
    emit documentChanged();
}

QList<FileData> DiffEditorDocument::diffFiles() const
{
    return m_diffFiles;
}

QString DiffEditorDocument::baseDirectory() const
{
    return m_baseDirectory;
}

QString DiffEditorDocument::startupFile() const
{
    return m_startupFile;
}

void DiffEditorDocument::setDescription(const QString &description)
{
    if (m_description == description)
        return;

    m_description = description;
    emit descriptionChanged();
}

QString DiffEditorDocument::description() const
{
    return m_description;
}

void DiffEditorDocument::setContextLineCount(int lines)
{
    QTC_ASSERT(!m_isContextLineCountForced, return);
    m_contextLineCount = lines;
}

int DiffEditorDocument::contextLineCount() const
{
    return m_contextLineCount;
}

void DiffEditorDocument::forceContextLineCount(int lines)
{
    m_contextLineCount = lines;
    m_isContextLineCountForced = true;
}

bool DiffEditorDocument::isContextLineCountForced() const
{
    return m_isContextLineCountForced;
}

void DiffEditorDocument::setIgnoreWhitespace(bool ignore)
{
    m_ignoreWhitespace = ignore;
}

bool DiffEditorDocument::ignoreWhitespace() const
{
    return m_ignoreWhitespace;
}

bool DiffEditorDocument::setContents(const QByteArray &contents)
{
    Q_UNUSED(contents);
    return true;
}

QString DiffEditorDocument::fallbackSaveAsPath() const
{
    if (!m_baseDirectory.isEmpty())
        return m_baseDirectory;
    return QDir::homePath();
}

bool DiffEditorDocument::isSaveAsAllowed() const
{
    return state() == LoadOK;
}

bool DiffEditorDocument::save(QString *errorString, const QString &fileName, bool autoSave)
{
    Q_UNUSED(errorString)
    Q_UNUSED(autoSave)

    if (state() != LoadOK)
        return false;

    const bool ok = write(fileName, format(), plainText(), errorString);

    if (!ok)
        return false;

    setController(0);
    setDescription(QString());
    Core::EditorManager::clearUniqueId(this);

    const QFileInfo fi(fileName);
    setTemporary(false);
    setFilePath(FileName::fromString(fi.absoluteFilePath()));
    setPreferredDisplayName(QString());
    emit temporaryStateChanged();

    return true;
}

void DiffEditorDocument::reload()
{
    if (m_controller) {
        m_controller->requestReload();
    } else {
        QString errorMessage;
        reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents);
    }
}

bool DiffEditorDocument::reload(QString *errorString, ReloadFlag flag, ChangeType type)
{
    Q_UNUSED(type)
    if (flag == FlagIgnore)
        return true;
    return open(errorString, filePath().toString(), filePath().toString()) == OpenResult::Success;
}

Core::IDocument::OpenResult DiffEditorDocument::open(QString *errorString, const QString &fileName,
                              const QString &realFileName)
{
    QTC_CHECK(fileName == realFileName); // does not support autosave
    beginReload();
    QString patch;
    ReadResult readResult = read(fileName, &patch, errorString);
    if (readResult == TextFileFormat::ReadEncodingError)
        return OpenResult::CannotHandle;
    else if (readResult != TextFileFormat::ReadSuccess)
        return OpenResult::ReadError;

    bool ok = false;
    QList<FileData> fileDataList = DiffUtils::readPatch(patch, &ok);
    if (!ok) {
        *errorString = tr("Could not parse patch file \"%1\". "
                          "The content is not of unified diff format.")
                .arg(fileName);
    } else {
        const QFileInfo fi(fileName);
        setTemporary(false);
        emit temporaryStateChanged();
        setFilePath(FileName::fromString(fi.absoluteFilePath()));
        setDiffFiles(fileDataList, fi.absolutePath());
    }
    endReload(ok);
    return ok ? OpenResult::Success : OpenResult::CannotHandle;
}

QString DiffEditorDocument::fallbackSaveAsFileName() const
{
    const int maxSubjectLength = 50;

    const QString desc = description();
    if (!desc.isEmpty()) {
        QString name = QString::fromLatin1("0001-%1").arg(desc.left(desc.indexOf('\n')));
        name = FileUtils::fileSystemFriendlyName(name);
        name.truncate(maxSubjectLength);
        name.append(".patch");
        return name;
    }
    return QStringLiteral("0001.patch");
}

// ### fixme: git-specific handling should be done in the git plugin:
// Remove unexpanded branches and follows-tag, clear indentation
// and create E-mail
static void formatGitDescription(QString *description)
{
    QString result;
    result.reserve(description->size());
    const auto descriptionList = description->split('\n');
    for (QString line : descriptionList) {
        if (line.startsWith("commit ") || line.startsWith("Branches: <Expand>"))
            continue;

        if (line.startsWith("Author: "))
            line.replace(0, 8, "From: ");
        else if (line.startsWith("    "))
            line.remove(0, 4);
        result.append(line);
        result.append('\n');
    }
    *description = result;
}

QString DiffEditorDocument::plainText() const
{
    QString result = description();
    const int formattingOptions = DiffUtils::GitFormat;
    if (formattingOptions & DiffUtils::GitFormat)
        formatGitDescription(&result);

    const QString diff = DiffUtils::makePatch(diffFiles(), formattingOptions);
    if (!diff.isEmpty()) {
        if (!result.isEmpty())
            result += '\n';
        result += diff;
    }
    return result;
}

void DiffEditorDocument::beginReload()
{
    emit aboutToReload();
    m_state = Reloading;
    emit changed();
    QSignalBlocker blocker(this);
    setDiffFiles(QList<FileData>(), QString());
    setDescription(QString());
}

void DiffEditorDocument::endReload(bool success)
{
    m_state = success ? LoadOK : LoadFailed;
    emit changed();
    emit reloadFinished(success);
}

} // namespace Internal
} // namespace DiffEditor