beautifierplugin.cpp 15.7 KB
Newer Older
Lorenz Haas's avatar
Lorenz Haas committed
1 2
/**************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 Lorenz Haas
** Contact: http://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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
Lorenz Haas's avatar
Lorenz Haas committed
15 16 17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
Lorenz Haas's avatar
Lorenz Haas committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
Lorenz Haas's avatar
Lorenz Haas committed
27 28 29 30 31 32 33
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "beautifierplugin.h"

#include "beautifierconstants.h"
34

Lorenz Haas's avatar
Lorenz Haas committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48
#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>
49 50 51
#include <texteditor/textdocument.h>
#include <texteditor/textdocumentlayout.h>
#include <texteditor/texteditor.h>
Lorenz Haas's avatar
Lorenz Haas committed
52 53
#include <texteditor/texteditorconstants.h>
#include <utils/fileutils.h>
54
#include <utils/QtConcurrentTools>
Lorenz Haas's avatar
Lorenz Haas committed
55 56

#include <QAction>
hjk's avatar
hjk committed
57
#include <QDir>
Lorenz Haas's avatar
Lorenz Haas committed
58
#include <QFileInfo>
59
#include <QFutureWatcher>
Lorenz Haas's avatar
Lorenz Haas committed
60 61 62 63 64 65 66
#include <QPlainTextEdit>
#include <QProcess>
#include <QScrollBar>
#include <QTextBlock>
#include <QTimer>
#include <QtPlugin>

67 68
using namespace TextEditor;

Lorenz Haas's avatar
Lorenz Haas committed
69 70 71
namespace Beautifier {
namespace Internal {

72 73
BeautifierPlugin::BeautifierPlugin() :
    m_asyncFormatMapper(new QSignalMapper)
Lorenz Haas's avatar
Lorenz Haas committed
74
{
Robert Loehning's avatar
Robert Loehning committed
75
    connect(m_asyncFormatMapper, SIGNAL(mapped(QObject*)),
76
            this, SLOT(formatCurrentFileContinue(QObject*)));
Montel Laurent's avatar
Montel Laurent committed
77
    connect(this, &BeautifierPlugin::pipeError, this, &BeautifierPlugin::showError);
Lorenz Haas's avatar
Lorenz Haas committed
78 79 80 81
}

BeautifierPlugin::~BeautifierPlugin()
{
82
    m_asyncFormatMapper->deleteLater();
Lorenz Haas's avatar
Lorenz Haas committed
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
}

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(QLatin1String("Beautifier"));
    Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu);

    for (int i = 0, total = m_tools.count(); i < total; ++i) {
        BeautifierAbstractTool *tool = m_tools.at(i);
        tool->initialize();
        const QList<QObject *> autoReleasedObjects = tool->autoReleaseObjects();
        for (int j = 0, total = autoReleasedObjects.count(); j < total; ++j)
            addAutoReleasedObject(autoReleasedObjects.at(j));
    }

    // The single shot is needed, otherwise the menu will stay disabled even
    // when the submenu's actions get enabled later on.
    QTimer::singleShot(0, this, SLOT(updateActions()));
    return true;
}

void BeautifierPlugin::extensionsInitialized()
{
    if (const Core::EditorManager *editorManager = Core::EditorManager::instance()) {
Robert Loehning's avatar
Robert Loehning committed
115 116
        connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
                this, SLOT(updateActions(Core::IEditor*)));
Lorenz Haas's avatar
Lorenz Haas committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130
    }
}

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

void BeautifierPlugin::updateActions(Core::IEditor *editor)
{
    for (int i = 0, total = m_tools.count(); i < total; ++i)
        m_tools.at(i)->updateActions(editor);
}

131 132 133
// Use pipeError() instead of calling showError() because this function may run in another thread.
QString BeautifierPlugin::format(const QString &text, const Command &command,
                                 const QString &fileName, bool *timeout)
Lorenz Haas's avatar
Lorenz Haas committed
134
{
135 136
    const QString executable = command.executable();
    if (executable.isEmpty())
Lorenz Haas's avatar
Lorenz Haas committed
137 138
        return QString();

139 140 141 142 143 144 145 146 147
    switch (command.processing()) {
    case Command::FileProcessing: {
        // Save text to temporary file
        QFileInfo fi(fileName);
        Utils::TempFileSaver sourceFile(QDir::tempPath() + QLatin1String("/qtc_beautifier_XXXXXXXX.")
                                        + fi.suffix());
        sourceFile.setAutoRemove(true);
        sourceFile.write(text.toUtf8());
        if (!sourceFile.finalize()) {
148 149
            emit pipeError(tr("Cannot create temporary file \"%1\": %2.")
                           .arg(sourceFile.fileName()).arg(sourceFile.errorString()));
150 151 152 153 154 155 156 157
            return QString();
        }

        // Format temporary file
        QProcess process;
        QStringList options = command.options();
        options.replaceInStrings(QLatin1String("%file"), sourceFile.fileName());
        process.start(executable, options);
158 159 160 161 162
        if (!process.waitForFinished(5000)) {
            if (timeout)
                *timeout = true;
            process.kill();
            emit pipeError(tr("Cannot call %1 or some other error occurred.").arg(executable));
163 164 165 166
            return QString();
        }
        const QByteArray output = process.readAllStandardError();
        if (!output.isEmpty())
167
            emit pipeError(executable + QLatin1String(": ") + QString::fromUtf8(output));
168 169 170 171

        // Read text back
        Utils::FileReader reader;
        if (!reader.fetch(sourceFile.fileName(), QIODevice::Text)) {
172 173
            emit pipeError(tr("Cannot read file \"%1\": %2.")
                           .arg(sourceFile.fileName()).arg(reader.errorString()));
174 175 176 177 178 179 180 181 182 183
            return QString();
        }
        return QString::fromUtf8(reader.data());
    } break;

    case Command::PipeProcessing: {
        QProcess process;
        QStringList options = command.options();
        options.replaceInStrings(QLatin1String("%file"), fileName);
        process.start(executable, options);
184 185
        if (!process.waitForStarted(3000)) {
            emit pipeError(tr("Cannot call %1 or some other error occurred.").arg(executable));
186 187 188 189
            return QString();
        }
        process.write(text.toUtf8());
        process.closeWriteChannel();
190 191 192 193 194
        if (!process.waitForFinished(5000)) {
            if (timeout)
                *timeout = true;
            process.kill();
            emit pipeError(tr("Cannot call %1 or some other error occurred.").arg(executable));
195 196
            return QString();
        }
197 198 199 200
        const QByteArray errorText = process.readAllStandardError();
        if (!errorText.isEmpty()) {
            emit pipeError(QString::fromLatin1("%1: %2").arg(executable)
                           .arg(QString::fromUtf8(errorText)));
201 202 203
            return QString();
        }

204 205 206
        const bool addsNewline = command.pipeAddsNewline();
        const bool returnsCRLF = command.returnsCRLF();
        if (addsNewline || returnsCRLF) {
207
            QString formatted = QString::fromUtf8(process.readAllStandardOutput());
208 209 210 211
            if (addsNewline)
                formatted.remove(QRegExp(QLatin1String("(\\r\\n|\\n)$")));
            if (returnsCRLF)
                formatted.replace(QLatin1String("\r\n"), QLatin1String("\n"));
212 213 214
            return formatted;
        }
        return QString::fromUtf8(process.readAllStandardOutput());
Lorenz Haas's avatar
Lorenz Haas committed
215 216
    }
    }
217 218

    return QString();
Lorenz Haas's avatar
Lorenz Haas committed
219 220
}

221
void BeautifierPlugin::formatCurrentFile(const Command &command)
Lorenz Haas's avatar
Lorenz Haas committed
222
{
223 224
    TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
    if (!widget)
Lorenz Haas's avatar
Lorenz Haas committed
225 226
        return;

227
    const QString sourceData = widget->toPlainText();
Lorenz Haas's avatar
Lorenz Haas committed
228 229 230
    if (sourceData.isEmpty())
        return;

231
    QFutureWatcher<FormatTask> *watcher = new QFutureWatcher<FormatTask>;
232 233
    connect(widget->textDocument(), &TextDocument::contentsChanged,
            watcher, &QFutureWatcher<FormatTask>::cancel);
234 235
    connect(watcher, SIGNAL(finished()), m_asyncFormatMapper, SLOT(map()));
    m_asyncFormatMapper->setMapping(watcher, watcher);
236
    const QString filePath = widget->textDocument()->filePath().toString();
237
    watcher->setFuture(QtConcurrent::run(&BeautifierPlugin::formatAsync, this,
238
                                         FormatTask(widget, filePath, sourceData, command)));
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
}

void BeautifierPlugin::formatAsync(QFutureInterface<FormatTask> &future, FormatTask task)
{
    task.formattedData = format(task.sourceData, task.command, task.filePath, &task.timeout);
    future.reportResult(task);
}

void BeautifierPlugin::formatCurrentFileContinue(QObject *watcher)
{
    QFutureWatcher<FormatTask> *futureWatcher = static_cast<QFutureWatcher<FormatTask>*>(watcher);
    if (!futureWatcher) {
        if (watcher)
            watcher->deleteLater();
        return;
    }

    if (futureWatcher->isCanceled()) {
        showError(tr("File was modified."));
        futureWatcher->deleteLater();
        return;
    }

    const FormatTask task = futureWatcher->result();
    futureWatcher->deleteLater();

    if (task.timeout) {
        showError(tr("Time out reached while formatting file %1.").arg(task.filePath));
        return;
    }

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

    const QString sourceData = textEditor->toPlainText();
    const QString formattedData = task.formattedData;
Lorenz Haas's avatar
Lorenz Haas committed
278 279 280 281 282 283 284 285
    if ((sourceData == formattedData) || formattedData.isEmpty())
        return;

    // 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;
    QTextBlock block = textEditor->document()->firstBlock();
    while (block.isValid()) {
286
        if (const TextBlockUserData *userdata = static_cast<TextBlockUserData *>(block.userData())) {
Lorenz Haas's avatar
Lorenz Haas committed
287 288
            if (userdata->folded()) {
                foldedBlocks << block.blockNumber();
289
                TextDocumentLayout::doFoldOrUnfold(block, true);
Lorenz Haas's avatar
Lorenz Haas committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
            }
        }
        block = block.next();
    }
    textEditor->update();

    // Save the current viewport position of the cursor to ensure the same vertical position after
    // the formatted text has set to the editor.
    int absoluteVerticalCursorOffset = textEditor->cursorRect().y();

    // Calculate diff
    DiffEditor::Differ differ;
    const QList<DiffEditor::Diff> diff = differ.diff(sourceData, formattedData);

    // Update changed lines and keep track of the cursor position
    QTextCursor cursor = textEditor->textCursor();
    int charactersInfrontOfCursor = cursor.position();
    int newCursorPos = charactersInfrontOfCursor;
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
    const int diffSize = diff.size();
    for (int i = 0; i < diffSize; ++i) {
        const DiffEditor::Diff d = diff.at(i);
        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);
    textEditor->setTextCursor(cursor);

    // Adjust vertical scrollbar
    absoluteVerticalCursorOffset = textEditor->cursorRect().y() - absoluteVerticalCursorOffset;
    const double fontHeight = QFontMetrics(textEditor->document()->defaultFont()).height();
    textEditor->verticalScrollBar()->setValue(textEditor->verticalScrollBar()->value()
                                              + absoluteVerticalCursorOffset / fontHeight);
    // Restore folded blocks
    const QTextDocument *doc = textEditor->document();
    const int total = foldedBlocks.size();
    for (int i = 0; i < total; ++i) {
        QTextBlock block = doc->findBlockByNumber(qMax(0, foldedBlocks.at(i)));
        if (block.isValid())
387
            TextDocumentLayout::doFoldOrUnfold(block, false);
Lorenz Haas's avatar
Lorenz Haas committed
388 389 390 391 392 393 394
    }

    textEditor->document()->setModified(true);
}

void BeautifierPlugin::showError(const QString &error)
{
395
    Core::MessageManager::write(tr("Error in Beautifier: %1").arg(error.trimmed()));
Lorenz Haas's avatar
Lorenz Haas committed
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
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
421 422
} // namespace Internal
} // namespace Beautifier