beautifierplugin.cpp 16.4 KB
Newer Older
1
/****************************************************************************
Lorenz Haas's avatar
Lorenz Haas committed
2
**
3 4
** Copyright (C) 2016 Lorenz Haas
** Contact: https://www.qt.io/licensing/
Lorenz Haas's avatar
Lorenz Haas committed
5 6 7 8 9 10 11
**
** 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
12 13 14
** 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.
Lorenz Haas's avatar
Lorenz Haas committed
15
**
16 17 18 19 20 21 22
** 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.
Lorenz Haas's avatar
Lorenz Haas committed
23 24 25 26 27 28
**
****************************************************************************/

#include "beautifierplugin.h"

#include "beautifierconstants.h"
29

Lorenz Haas's avatar
Lorenz Haas committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "artisticstyle/artisticstyle.h"
#include "clangformat/clangformat.h"
#include "uncrustify/uncrustify.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <diffeditor/differ.h>
44
#include <texteditor/convenience.h>
45 46 47
#include <texteditor/textdocument.h>
#include <texteditor/textdocumentlayout.h>
#include <texteditor/texteditor.h>
Lorenz Haas's avatar
Lorenz Haas committed
48 49
#include <texteditor/texteditorconstants.h>
#include <utils/fileutils.h>
50
#include <utils/qtcassert.h>
Eike Ziller's avatar
Eike Ziller committed
51
#include <utils/runextensions.h>
Lorenz Haas's avatar
Lorenz Haas committed
52 53

#include <QAction>
hjk's avatar
hjk committed
54
#include <QDir>
Lorenz Haas's avatar
Lorenz Haas committed
55
#include <QFileInfo>
56
#include <QFutureWatcher>
57
#include <QMenu>
Lorenz Haas's avatar
Lorenz Haas committed
58 59 60 61 62 63
#include <QPlainTextEdit>
#include <QProcess>
#include <QScrollBar>
#include <QTextBlock>
#include <QtPlugin>

64 65
using namespace TextEditor;

Lorenz Haas's avatar
Lorenz Haas committed
66 67 68
namespace Beautifier {
namespace Internal {

69
FormatTask format(FormatTask task)
Lorenz Haas's avatar
Lorenz Haas committed
70
{
71 72
    task.error.clear();
    task.formattedData.clear();
Lorenz Haas's avatar
Lorenz Haas committed
73

74
    const QString executable = task.command.executable();
75
    if (executable.isEmpty())
76
        return task;
Lorenz Haas's avatar
Lorenz Haas committed
77

78
    switch (task.command.processing()) {
79 80
    case Command::FileProcessing: {
        // Save text to temporary file
81
        const QFileInfo fi(task.filePath);
82 83 84
        Utils::TempFileSaver sourceFile(QDir::tempPath() + QLatin1String("/qtc_beautifier_XXXXXXXX.")
                                        + fi.suffix());
        sourceFile.setAutoRemove(true);
85
        sourceFile.write(task.sourceData.toUtf8());
86
        if (!sourceFile.finalize()) {
87 88 89
            task.error = QObject::tr("Cannot create temporary file \"%1\": %2.")
                    .arg(sourceFile.fileName()).arg(sourceFile.errorString());
            return task;
90 91 92 93
        }

        // Format temporary file
        QProcess process;
94
        QStringList options = task.command.options();
95 96
        options.replaceInStrings(QLatin1String("%file"), sourceFile.fileName());
        process.start(executable, options);
97 98
        if (!process.waitForFinished(5000)) {
            process.kill();
Robert Loehning's avatar
Robert Loehning committed
99
            task.error = QObject::tr("Cannot call %1 or some other error occurred. Timeout "
100 101 102
                                     "reached while formatting file %2.")
                    .arg(executable).arg(task.filePath);
            return task;
103 104 105
        }
        const QByteArray output = process.readAllStandardError();
        if (!output.isEmpty())
106
            task.error = executable + QLatin1String(": ") + QString::fromUtf8(output);
107 108 109 110

        // Read text back
        Utils::FileReader reader;
        if (!reader.fetch(sourceFile.fileName(), QIODevice::Text)) {
111 112 113
            task.error = QObject::tr("Cannot read file \"%1\": %2.")
                    .arg(sourceFile.fileName()).arg(reader.errorString());
            return task;
114
        }
115 116
        task.formattedData = QString::fromUtf8(reader.data());
        return task;
117 118 119 120
    } break;

    case Command::PipeProcessing: {
        QProcess process;
121
        QStringList options = task.command.options();
122
        options.replaceInStrings(QLatin1String("%filename"), QFileInfo(task.filePath).fileName());
123
        options.replaceInStrings(QLatin1String("%file"), task.filePath);
124
        process.start(executable, options);
125
        if (!process.waitForStarted(3000)) {
126 127 128
            task.error = QObject::tr("Cannot call %1 or some other error occurred.")
                    .arg(executable);
            return task;
129
        }
130
        process.write(task.sourceData.toUtf8());
131
        process.closeWriteChannel();
132 133
        if (!process.waitForFinished(5000)) {
            process.kill();
Robert Loehning's avatar
Robert Loehning committed
134
            task.error = QObject::tr("Cannot call %1 or some other error occurred. Timeout "
135 136 137
                                     "reached while formatting file %2.")
                    .arg(executable).arg(task.filePath);
            return task;
138
        }
139 140
        const QByteArray errorText = process.readAllStandardError();
        if (!errorText.isEmpty()) {
141 142 143
            task.error = QString::fromLatin1("%1: %2").arg(executable)
                    .arg(QString::fromUtf8(errorText));
            return task;
144 145
        }

146 147
        const bool addsNewline = task.command.pipeAddsNewline();
        const bool returnsCRLF = task.command.returnsCRLF();
148
        if (addsNewline || returnsCRLF) {
149
            task.formattedData = QString::fromUtf8(process.readAllStandardOutput());
150
            if (addsNewline)
151
                task.formattedData.remove(QRegExp(QLatin1String("(\\r\\n|\\n)$")));
152
            if (returnsCRLF)
153 154
                task.formattedData.replace(QLatin1String("\r\n"), QLatin1String("\n"));
            return task;
155
        }
156 157
        task.formattedData = QString::fromUtf8(process.readAllStandardOutput());
        return task;
Lorenz Haas's avatar
Lorenz Haas committed
158 159
    }
    }
160

161
    return task;
Lorenz Haas's avatar
Lorenz Haas committed
162 163
}

164
QString sourceData(TextEditorWidget *editor, int startPos, int endPos)
Lorenz Haas's avatar
Lorenz Haas committed
165
{
166 167 168 169
    return (startPos < 0)
            ? editor->toPlainText()
            : Convenience::textAt(editor->textCursor(), startPos, (endPos - startPos));
}
170

171 172 173 174 175 176 177 178 179 180 181
bool BeautifierPlugin::initialize(const QStringList &arguments, QString *errorString)
{
    Q_UNUSED(arguments)
    Q_UNUSED(errorString)

    m_tools << new ArtisticStyle::ArtisticStyle(this);
    m_tools << new ClangFormat::ClangFormat(this);
    m_tools << new Uncrustify::Uncrustify(this);

    Core::ActionContainer *menu = Core::ActionManager::createMenu(Constants::MENU_ID);
    menu->menu()->setTitle(QCoreApplication::translate("Beautifier", Constants::OPTION_TR_CATEGORY));
182
    menu->setOnAllDisabledBehavior(Core::ActionContainer::Show);
183 184 185 186 187 188 189
    Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu);

    foreach (BeautifierAbstractTool *tool, m_tools) {
        tool->initialize();
        const QList<QObject *> autoReleasedObjects = tool->autoReleaseObjects();
        foreach (QObject *object, autoReleasedObjects)
            addAutoReleasedObject(object);
190
    }
191

192
    updateActions();
193 194 195 196 197 198 199 200 201 202 203 204 205 206
    return true;
}

void BeautifierPlugin::extensionsInitialized()
{
    if (const Core::EditorManager *editorManager = Core::EditorManager::instance()) {
        connect(editorManager, &Core::EditorManager::currentEditorChanged,
                this, &BeautifierPlugin::updateActions);
    }
}

ExtensionSystem::IPlugin::ShutdownFlag BeautifierPlugin::aboutToShutdown()
{
    return SynchronousShutdown;
207 208
}

209
void BeautifierPlugin::updateActions(Core::IEditor *editor)
210
{
211 212
    foreach (BeautifierAbstractTool *tool, m_tools)
        tool->updateActions(editor);
213 214
}

215
void BeautifierPlugin::formatCurrentFile(const Command &command, int startPos, int endPos)
216
{
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    if (TextEditorWidget *editor = TextEditorWidget::currentTextEditorWidget())
        formatEditorAsync(editor, command, startPos, endPos);
}

/**
 * Formats the text of @a editor using @a command. @a startPos and @a endPos specifies the range of
 * the editor's text that will be formatted. If @a startPos is negative the editor's entire text is
 * formatted.
 *
 * @pre @a endPos must be greater than or equal to @a startPos
 */
void BeautifierPlugin::formatEditor(TextEditorWidget *editor, const Command &command, int startPos,
                                    int endPos)
{
    QTC_ASSERT(startPos <= endPos, return);

    const QString sd = sourceData(editor, startPos, endPos);
    if (sd.isEmpty())
235
        return;
236 237 238
    checkAndApplyTask(format(FormatTask(editor, editor->textDocument()->filePath().toString(), sd,
                                        command, startPos, endPos)));
}
239

240 241 242 243 244 245 246 247 248 249
/**
 * Behaves like formatEditor except that the formatting is done asynchronously.
 */
void BeautifierPlugin::formatEditorAsync(TextEditorWidget *editor, const Command &command,
                                         int startPos, int endPos)
{
    QTC_ASSERT(startPos <= endPos, return);

    const QString sd = sourceData(editor, startPos, endPos);
    if (sd.isEmpty())
250 251
        return;

252 253 254 255 256 257 258 259 260 261 262 263 264
    QFutureWatcher<FormatTask> *watcher = new QFutureWatcher<FormatTask>;
    const TextDocument *doc = editor->textDocument();
    connect(doc, &TextDocument::contentsChanged, watcher, &QFutureWatcher<FormatTask>::cancel);
    connect(watcher, &QFutureWatcherBase::finished, [this, watcher]() {
        if (watcher->isCanceled())
            showError(tr("File was modified."));
        else
            checkAndApplyTask(watcher->result());
        watcher->deleteLater();
    });
    watcher->setFuture(Utils::runAsync(&format, FormatTask(editor, doc->filePath().toString(), sd,
                                                           command, startPos, endPos)));
}
265

266 267 268 269 270 271 272 273
/**
 * Checks the state of @a task and if the formatting was successful calls updateEditorText() with
 * the respective members of @a task.
 */
void BeautifierPlugin::checkAndApplyTask(const FormatTask &task)
{
    if (!task.error.isEmpty()) {
        showError(task.error);
274 275 276
        return;
    }

277 278 279 280 281
    if (task.formattedData.isEmpty()) {
        showError(tr("Could not format file %1.").arg(task.filePath));
        return;
    }

282 283 284 285 286 287
    QPlainTextEdit *textEditor = task.editor;
    if (!textEditor) {
        showError(tr("File %1 was closed.").arg(task.filePath));
        return;
    }

288 289
    const QString formattedData = (task.startPos < 0)
            ? task.formattedData
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
            : QString(textEditor->toPlainText()).replace(
                  task.startPos, (task.endPos - task.startPos), task.formattedData);

    updateEditorText(textEditor, formattedData);
}

/**
 * Sets the text of @a editor to @a text. Instead of replacing the entire text, however, only the
 * actually changed parts are updated while preserving the cursor position, the folded
 * blocks, and the scroll bar position.
 */
void BeautifierPlugin::updateEditorText(QPlainTextEdit *editor, const QString &text)
{
    const QString editorText = editor->toPlainText();
    if (editorText == text)
Lorenz Haas's avatar
Lorenz Haas committed
305 306
        return;

307 308 309
    // Calculate diff
    DiffEditor::Differ differ;
    const QList<DiffEditor::Diff> diff = differ.diff(editorText, text);
310

Lorenz Haas's avatar
Lorenz Haas committed
311 312 313
    // Since QTextCursor does not work properly with folded blocks, all blocks must be unfolded.
    // To restore the current state at the end, keep track of which block is folded.
    QList<int> foldedBlocks;
314
    QTextBlock block = editor->document()->firstBlock();
Lorenz Haas's avatar
Lorenz Haas committed
315
    while (block.isValid()) {
316
        if (const TextBlockUserData *userdata = static_cast<TextBlockUserData *>(block.userData())) {
Lorenz Haas's avatar
Lorenz Haas committed
317 318
            if (userdata->folded()) {
                foldedBlocks << block.blockNumber();
319
                TextDocumentLayout::doFoldOrUnfold(block, true);
Lorenz Haas's avatar
Lorenz Haas committed
320 321 322 323
            }
        }
        block = block.next();
    }
324
    editor->update();
Lorenz Haas's avatar
Lorenz Haas committed
325 326 327

    // Save the current viewport position of the cursor to ensure the same vertical position after
    // the formatted text has set to the editor.
328
    int absoluteVerticalCursorOffset = editor->cursorRect().y();
Lorenz Haas's avatar
Lorenz Haas committed
329 330

    // Update changed lines and keep track of the cursor position
331
    QTextCursor cursor = editor->textCursor();
Lorenz Haas's avatar
Lorenz Haas committed
332 333 334 335
    int charactersInfrontOfCursor = cursor.position();
    int newCursorPos = charactersInfrontOfCursor;
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
336
    foreach (const DiffEditor::Diff &d, diff) {
Lorenz Haas's avatar
Lorenz Haas committed
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
        switch (d.command) {
        case DiffEditor::Diff::Insert:
        {
            // Adjust cursor position if we do work in front of the cursor.
            if (charactersInfrontOfCursor > 0) {
                const int size = d.text.size();
                charactersInfrontOfCursor += size;
                newCursorPos += size;
            }
            // Adjust folded blocks, if a new block is added.
            if (d.text.contains(QLatin1Char('\n'))) {
                const int newLineCount = d.text.count(QLatin1Char('\n'));
                const int number = cursor.blockNumber();
                const int total = foldedBlocks.size();
                for (int i = 0; i < total; ++i) {
                    if (foldedBlocks.at(i) > number)
                        foldedBlocks[i] += newLineCount;
                }
            }
            cursor.insertText(d.text);
        }
            break;
        case DiffEditor::Diff::Delete:
        {
            // Adjust cursor position if we do work in front of the cursor.
            if (charactersInfrontOfCursor > 0) {
                const int size = d.text.size();
                charactersInfrontOfCursor -= size;
                newCursorPos -= size;
                // Cursor was inside the deleted text, so adjust the new cursor position
                if (charactersInfrontOfCursor < 0)
                    newCursorPos -= charactersInfrontOfCursor;
            }
            // Adjust folded blocks, if at least one block is being deleted.
            if (d.text.contains(QLatin1Char('\n'))) {
                const int newLineCount = d.text.count(QLatin1Char('\n'));
                const int number = cursor.blockNumber();
                for (int i = 0, total = foldedBlocks.size(); i < total; ++i) {
                    if (foldedBlocks.at(i) > number) {
                        foldedBlocks[i] -= newLineCount;
                        if (foldedBlocks[i] < number) {
                            foldedBlocks.removeAt(i);
                            --i;
                            --total;
                        }
                    }
                }
            }
            cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, d.text.size());
            cursor.removeSelectedText();
        }
            break;
        case DiffEditor::Diff::Equal:
            // Adjust cursor position
            charactersInfrontOfCursor -= d.text.size();
            cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, d.text.size());
            break;
        }
    }
    cursor.endEditBlock();
    cursor.setPosition(newCursorPos);
398
    editor->setTextCursor(cursor);
Lorenz Haas's avatar
Lorenz Haas committed
399 400

    // Adjust vertical scrollbar
401 402 403
    absoluteVerticalCursorOffset = editor->cursorRect().y() - absoluteVerticalCursorOffset;
    const double fontHeight = QFontMetrics(editor->document()->defaultFont()).height();
    editor->verticalScrollBar()->setValue(editor->verticalScrollBar()->value()
Lorenz Haas's avatar
Lorenz Haas committed
404 405
                                              + absoluteVerticalCursorOffset / fontHeight);
    // Restore folded blocks
406
    const QTextDocument *doc = editor->document();
407
    foreach (const int blockId, foldedBlocks) {
408
        const QTextBlock block = doc->findBlockByNumber(qMax(0, blockId));
Lorenz Haas's avatar
Lorenz Haas committed
409
        if (block.isValid())
410
            TextDocumentLayout::doFoldOrUnfold(block, false);
Lorenz Haas's avatar
Lorenz Haas committed
411 412
    }

413
    editor->document()->setModified(true);
Lorenz Haas's avatar
Lorenz Haas committed
414 415 416 417
}

void BeautifierPlugin::showError(const QString &error)
{
418
    Core::MessageManager::write(tr("Error in Beautifier: %1").arg(error.trimmed()));
Lorenz Haas's avatar
Lorenz Haas committed
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
QString BeautifierPlugin::msgCannotGetConfigurationFile(const QString &command)
{
    return tr("Cannot get configuration file for %1.").arg(command);
}

QString BeautifierPlugin::msgFormatCurrentFile()
{
    //: Menu entry
    return tr("Format Current File");
}

QString BeautifierPlugin::msgFormatSelectedText()
{
    //: Menu entry
    return tr("Format Selected Text");
}

QString BeautifierPlugin::msgCommandPromptDialogTitle(const QString &command)
{
    //: File dialog title for path chooser when choosing binary
    return tr("%1 Command").arg(command);
}

Lorenz Haas's avatar
Lorenz Haas committed
444 445
} // namespace Internal
} // namespace Beautifier