beautifierplugin.cpp 16.1 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
#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/messagemanager.h>
#include <diffeditor/differ.h>
42
#include <texteditor/convenience.h>
43 44 45
#include <texteditor/textdocument.h>
#include <texteditor/textdocumentlayout.h>
#include <texteditor/texteditor.h>
46
#include <utils/qtcassert.h>
Eike Ziller's avatar
Eike Ziller committed
47
#include <utils/runextensions.h>
48
#include <utils/synchronousprocess.h>
Lorenz Haas's avatar
Lorenz Haas committed
49

hjk's avatar
hjk committed
50
#include <QDir>
Lorenz Haas's avatar
Lorenz Haas committed
51
#include <QFileInfo>
52
#include <QFutureWatcher>
53
#include <QMenu>
Lorenz Haas's avatar
Lorenz Haas committed
54 55 56 57 58
#include <QPlainTextEdit>
#include <QProcess>
#include <QScrollBar>
#include <QTextBlock>

59 60
using namespace TextEditor;

Lorenz Haas's avatar
Lorenz Haas committed
61 62 63
namespace Beautifier {
namespace Internal {

64
FormatTask format(FormatTask task)
Lorenz Haas's avatar
Lorenz Haas committed
65
{
66 67
    task.error.clear();
    task.formattedData.clear();
Lorenz Haas's avatar
Lorenz Haas committed
68

69
    const QString executable = task.command.executable();
70
    if (executable.isEmpty())
71
        return task;
Lorenz Haas's avatar
Lorenz Haas committed
72

73
    switch (task.command.processing()) {
74 75
    case Command::FileProcessing: {
        // Save text to temporary file
76
        const QFileInfo fi(task.filePath);
77
        Utils::TempFileSaver sourceFile(QDir::tempPath() + "/qtc_beautifier_XXXXXXXX."
78 79
                                        + fi.suffix());
        sourceFile.setAutoRemove(true);
80
        sourceFile.write(task.sourceData.toUtf8());
81
        if (!sourceFile.finalize()) {
Takumi ASAKI's avatar
Takumi ASAKI committed
82
            task.error = BeautifierPlugin::tr("Cannot create temporary file \"%1\": %2.")
83 84
                    .arg(sourceFile.fileName()).arg(sourceFile.errorString());
            return task;
85 86 87
        }

        // Format temporary file
88
        QStringList options = task.command.options();
89 90 91 92 93 94
        options.replaceInStrings(QLatin1String("%file"), sourceFile.fileName());
        Utils::SynchronousProcess process;
        process.setTimeoutS(5);
        Utils::SynchronousProcessResponse response = process.run(executable, options);
        if (response.result != Utils::SynchronousProcessResponse::Finished) {
            task.error = QObject::tr("Failed to format: %1.").arg(response.exitMessage(executable, 5));
95
            return task;
96
        }
97
        const QString output = response.stdErr;
98
        if (!output.isEmpty())
99
            task.error = executable + QLatin1String(": ") + output;
100 101 102 103

        // Read text back
        Utils::FileReader reader;
        if (!reader.fetch(sourceFile.fileName(), QIODevice::Text)) {
Takumi ASAKI's avatar
Takumi ASAKI committed
104
            task.error = BeautifierPlugin::tr("Cannot read file \"%1\": %2.")
105 106
                    .arg(sourceFile.fileName()).arg(reader.errorString());
            return task;
107
        }
108
        task.formattedData = QString::fromUtf8(reader.data());
109
    }
110
    return task;
111 112 113

    case Command::PipeProcessing: {
        QProcess process;
114
        QStringList options = task.command.options();
115 116
        options.replaceInStrings("%filename", QFileInfo(task.filePath).fileName());
        options.replaceInStrings("%file", task.filePath);
117
        process.start(executable, options);
118
        if (!process.waitForStarted(3000)) {
Takumi ASAKI's avatar
Takumi ASAKI committed
119
            task.error = BeautifierPlugin::tr("Cannot call %1 or some other error occurred.")
120 121
                    .arg(executable);
            return task;
122
        }
123
        process.write(task.sourceData.toUtf8());
124
        process.closeWriteChannel();
125
        if (!process.waitForFinished(5000) && process.state() == QProcess::Running) {
126
            process.kill();
Takumi ASAKI's avatar
Takumi ASAKI committed
127
            task.error = BeautifierPlugin::tr("Cannot call %1 or some other error occurred. Timeout "
128 129 130
                                     "reached while formatting file %2.")
                    .arg(executable).arg(task.filePath);
            return task;
131
        }
132 133
        const QByteArray errorText = process.readAllStandardError();
        if (!errorText.isEmpty()) {
134 135 136
            task.error = QString::fromLatin1("%1: %2").arg(executable)
                    .arg(QString::fromUtf8(errorText));
            return task;
137 138
        }

139 140
        const bool addsNewline = task.command.pipeAddsNewline();
        const bool returnsCRLF = task.command.returnsCRLF();
141
        if (addsNewline || returnsCRLF) {
142
            task.formattedData = QString::fromUtf8(process.readAllStandardOutput());
143
            if (addsNewline)
144
                task.formattedData.remove(QRegExp("(\\r\\n|\\n)$"));
145
            if (returnsCRLF)
146
                task.formattedData.replace("\r\n", "\n");
147
            return task;
148
        }
149 150
        task.formattedData = QString::fromUtf8(process.readAllStandardOutput());
        return task;
Lorenz Haas's avatar
Lorenz Haas committed
151 152
    }
    }
153

154
    return task;
Lorenz Haas's avatar
Lorenz Haas committed
155 156
}

157
QString sourceData(TextEditorWidget *editor, int startPos, int endPos)
Lorenz Haas's avatar
Lorenz Haas committed
158
{
159 160 161 162
    return (startPos < 0)
            ? editor->toPlainText()
            : Convenience::textAt(editor->textCursor(), startPos, (endPos - startPos));
}
163

164 165 166 167 168 169 170 171 172 173 174
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));
175
    menu->setOnAllDisabledBehavior(Core::ActionContainer::Show);
176 177
    Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu);

178
    for (BeautifierAbstractTool *tool : m_tools) {
179 180
        tool->initialize();
        const QList<QObject *> autoReleasedObjects = tool->autoReleaseObjects();
181
        for (QObject *object : autoReleasedObjects)
182
            addAutoReleasedObject(object);
183
    }
184

185
    updateActions();
186 187 188 189 190 191 192 193 194 195 196 197 198 199
    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;
200 201
}

202
void BeautifierPlugin::updateActions(Core::IEditor *editor)
203
{
204
    for (BeautifierAbstractTool *tool : m_tools)
205
        tool->updateActions(editor);
206 207
}

208
void BeautifierPlugin::formatCurrentFile(const Command &command, int startPos, int endPos)
209
{
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    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())
228
        return;
229 230 231
    checkAndApplyTask(format(FormatTask(editor, editor->textDocument()->filePath().toString(), sd,
                                        command, startPos, endPos)));
}
232

233 234 235 236 237 238 239 240 241 242
/**
 * 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())
243 244
        return;

245 246 247 248 249 250 251 252 253 254 255 256 257
    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)));
}
258

259 260 261 262 263 264 265 266
/**
 * 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);
267 268 269
        return;
    }

270 271 272 273 274
    if (task.formattedData.isEmpty()) {
        showError(tr("Could not format file %1.").arg(task.filePath));
        return;
    }

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

281 282
    const QString formattedData = (task.startPos < 0)
            ? task.formattedData
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            : 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
298 299
        return;

300 301 302
    // Calculate diff
    DiffEditor::Differ differ;
    const QList<DiffEditor::Diff> diff = differ.diff(editorText, text);
303

Lorenz Haas's avatar
Lorenz Haas committed
304 305 306
    // 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;
307
    QTextBlock block = editor->document()->firstBlock();
Lorenz Haas's avatar
Lorenz Haas committed
308
    while (block.isValid()) {
309
        if (const TextBlockUserData *userdata = static_cast<TextBlockUserData *>(block.userData())) {
Lorenz Haas's avatar
Lorenz Haas committed
310 311
            if (userdata->folded()) {
                foldedBlocks << block.blockNumber();
312
                TextDocumentLayout::doFoldOrUnfold(block, true);
Lorenz Haas's avatar
Lorenz Haas committed
313 314 315 316
            }
        }
        block = block.next();
    }
317
    editor->update();
Lorenz Haas's avatar
Lorenz Haas committed
318 319 320

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

    // Update changed lines and keep track of the cursor position
324
    QTextCursor cursor = editor->textCursor();
Lorenz Haas's avatar
Lorenz Haas committed
325 326 327 328
    int charactersInfrontOfCursor = cursor.position();
    int newCursorPos = charactersInfrontOfCursor;
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
329
    for (const DiffEditor::Diff &d : diff) {
Lorenz Haas's avatar
Lorenz Haas committed
330 331 332 333 334 335 336 337 338 339
        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.
340 341
            if (d.text.contains('\n')) {
                const int newLineCount = d.text.count('\n');
Lorenz Haas's avatar
Lorenz Haas committed
342 343 344 345 346 347 348 349 350
                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;
351 352
        }

Lorenz Haas's avatar
Lorenz Haas committed
353 354 355 356 357 358 359 360 361 362 363 364
        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.
365 366
            if (d.text.contains('\n')) {
                const int newLineCount = d.text.count('\n');
Lorenz Haas's avatar
Lorenz Haas committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
                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;
382 383
        }

Lorenz Haas's avatar
Lorenz Haas committed
384 385 386 387 388 389 390 391 392
        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);
393
    editor->setTextCursor(cursor);
Lorenz Haas's avatar
Lorenz Haas committed
394 395

    // Adjust vertical scrollbar
396 397 398
    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
399 400
                                              + absoluteVerticalCursorOffset / fontHeight);
    // Restore folded blocks
401
    const QTextDocument *doc = editor->document();
402
    for (int blockId : foldedBlocks) {
403
        const QTextBlock block = doc->findBlockByNumber(qMax(0, blockId));
Lorenz Haas's avatar
Lorenz Haas committed
404
        if (block.isValid())
405
            TextDocumentLayout::doFoldOrUnfold(block, false);
Lorenz Haas's avatar
Lorenz Haas committed
406 407
    }

408
    editor->document()->setModified(true);
Lorenz Haas's avatar
Lorenz Haas committed
409 410 411 412
}

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

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
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
439 440
} // namespace Internal
} // namespace Beautifier