aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmakeprojectmanager/externaleditors.cpp
blob: 0590b4f1d0a7ea915e780d1bb1f30d15bfa7b931 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "externaleditors.h"

#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/session.h>

#include <qtsupport/qtkitinformation.h>

#include <designer/designerconstants.h>

#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>

#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>

using namespace ProjectExplorer;
using namespace Utils;

enum { debug = 0 };

namespace QmakeProjectManager {
namespace Internal {

// ------------ Messages
static inline QString msgStartFailed(const QString &binary, QStringList arguments)
{
    arguments.push_front(binary);
    return ExternalQtEditor::tr("Unable to start \"%1\"").arg(arguments.join(QLatin1Char(' ')));
}

static inline QString msgAppNotFound(const QString &id)
{
    return ExternalQtEditor::tr("The application \"%1\" could not be found.").arg(id);
}

// -- Commands and helpers
static QString linguistBinary(const QtSupport::QtVersion *qtVersion)
{
    if (qtVersion)
        return qtVersion->linguistFilePath().toString();
    return QLatin1String(Utils::HostOsInfo::isMacHost() ? "Linguist" : "linguist");
}

static QString designerBinary(const QtSupport::QtVersion *qtVersion)
{
    if (qtVersion)
        return qtVersion->designerFilePath().toString();
    return QLatin1String(Utils::HostOsInfo::isMacHost() ? "Designer" : "designer");
}

// Mac: Change the call 'Foo.app/Contents/MacOS/Foo <filelist>' to
// 'open -a Foo.app <filelist>'. doesn't support generic command line arguments
static ExternalQtEditor::LaunchData createMacOpenCommand(const ExternalQtEditor::LaunchData &data)
{
    ExternalQtEditor::LaunchData openData = data;
    const int appFolderIndex = data.binary.lastIndexOf(QLatin1String("/Contents/MacOS/"));
    if (appFolderIndex != -1) {
        openData.binary = "open";
        openData.arguments = QStringList({QString("-a"), data.binary.left(appFolderIndex)})
                + data.arguments;
    }
    return openData;
}

static const char designerIdC[] = "Qt.Designer";
static const char linguistIdC[] = "Qt.Linguist";

static const char designerDisplayName[] = QT_TRANSLATE_NOOP("OpenWith::Editors", "Qt Designer");
static const char linguistDisplayName[] = QT_TRANSLATE_NOOP("OpenWith::Editors", "Qt Linguist");

// -------------- ExternalQtEditor
ExternalQtEditor::ExternalQtEditor(Utils::Id id,
                                   const QString &displayName,
                                   const QString &mimetype,
                                   const CommandForQtVersion &commandForQtVersion)
    : m_commandForQtVersion(commandForQtVersion)
{
    setId(id);
    setDisplayName(displayName);
    setMimeTypes({mimetype});
}

ExternalQtEditor *ExternalQtEditor::createLinguistEditor()
{
    return new ExternalQtEditor(linguistIdC,
                                QLatin1String(linguistDisplayName),
                                QLatin1String(ProjectExplorer::Constants::LINGUIST_MIMETYPE),
                                linguistBinary);
}

ExternalQtEditor *ExternalQtEditor::createDesignerEditor()
{
    if (Utils::HostOsInfo::isMacHost()) {
        return new ExternalQtEditor(designerIdC,
                                    QLatin1String(designerDisplayName),
                                    QLatin1String(ProjectExplorer::Constants::FORM_MIMETYPE),
                                    designerBinary);
    } else {
        return new DesignerExternalEditor;
    }
}

static QString findFirstCommand(QVector<QtSupport::QtVersion *> qtVersions,
                                ExternalQtEditor::CommandForQtVersion command)
{
    foreach (QtSupport::QtVersion *qt, qtVersions) {
        if (qt) {
            const QString binary = command(qt);
            if (!binary.isEmpty())
                return binary;
        }
    }
    return QString();
}

bool ExternalQtEditor::getEditorLaunchData(const Utils::FilePath &filePath,
                                           LaunchData *data,
                                           QString *errorMessage) const
{
    // Check in order for Qt version with the binary:
    // - active kit of project
    // - any other of the project
    // - default kit
    // - any other kit
    // As fallback check PATH
    data->workingDirectory.clear();
    QVector<QtSupport::QtVersion *> qtVersionsToCheck; // deduplicated after being filled
    if (const Project *project = SessionManager::projectForFile(filePath)) {
        data->workingDirectory = project->projectDirectory();
        // active kit
        if (const Target *target = project->activeTarget()) {
            qtVersionsToCheck << QtSupport::QtKitAspect::qtVersion(target->kit());
        }
        // all kits of project
        qtVersionsToCheck += Utils::transform<QVector>(project->targets(), [](Target *t) {
            return QTC_GUARD(t) ? QtSupport::QtKitAspect::qtVersion(t->kit()) : nullptr;
        });
    }
    // default kit
    qtVersionsToCheck << QtSupport::QtKitAspect::qtVersion(KitManager::defaultKit());
    // all kits
    qtVersionsToCheck += Utils::transform<QVector>(KitManager::kits(), QtSupport::QtKitAspect::qtVersion);
    qtVersionsToCheck = Utils::filteredUnique(qtVersionsToCheck); // can still contain nullptr
    data->binary = findFirstCommand(qtVersionsToCheck, m_commandForQtVersion);
    // fallback
    if (data->binary.isEmpty()) {
        const QString path = qEnvironmentVariable("PATH");
        data->binary = Utils::QtcProcess::locateBinary(path, m_commandForQtVersion(nullptr));
    }

    if (data->binary.isEmpty()) {
        *errorMessage = msgAppNotFound(id().toString());
        return false;
    }
    // Setup binary + arguments, use Mac Open if appropriate
    data->arguments.push_back(filePath.toString());
    if (Utils::HostOsInfo::isMacHost())
        *data = createMacOpenCommand(*data);
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << data->binary << data->arguments;
    return true;
}

bool ExternalQtEditor::startEditor(const Utils::FilePath &filePath, QString *errorMessage)
{
    LaunchData data;
    return getEditorLaunchData(filePath, &data, errorMessage)
            && startEditorProcess(data, errorMessage);
}

bool ExternalQtEditor::startEditorProcess(const LaunchData &data, QString *errorMessage)
{
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << data.binary << data.arguments << data.workingDirectory;
    qint64 pid = 0;
    if (!QtcProcess::startDetached({FilePath::fromString(data.binary), data.arguments}, data.workingDirectory, &pid)) {
        *errorMessage = msgStartFailed(data.binary, data.arguments);
        return false;
    }
    return true;
}

// --------------- DesignerExternalEditor with Designer Tcp remote control.
DesignerExternalEditor::DesignerExternalEditor() :
    ExternalQtEditor(designerIdC,
                     QLatin1String(designerDisplayName),
                     QLatin1String(Designer::Constants::FORM_MIMETYPE),
                     designerBinary)
{
}

void DesignerExternalEditor::processTerminated(const QString &binary)
{
    const ProcessCache::iterator it = m_processCache.find(binary);
    if (it == m_processCache.end())
        return;
    // Make sure socket is closed and cleaned, remove from cache
    QTcpSocket *socket = it.value();
    m_processCache.erase(it); // Note that closing will cause the slot to be retriggered
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << binary << socket->state();
    if (socket->state() == QAbstractSocket::ConnectedState)
        socket->close();
    socket->deleteLater();
}

bool DesignerExternalEditor::startEditor(const Utils::FilePath &filePath, QString *errorMessage)
{
    LaunchData data;
    // Find the editor binary
    if (!getEditorLaunchData(filePath, &data, errorMessage)) {
        return false;
    }
    // Known one?
    const ProcessCache::iterator it = m_processCache.find(data.binary);
    if (it != m_processCache.end()) {
        // Process is known, write to its socket to cause it to open the file
        if (debug)
           qDebug() << Q_FUNC_INFO << "\nWriting to socket:" << data.binary << filePath;
        QTcpSocket *socket = it.value();
        if (!socket->write(filePath.toString().toUtf8() + '\n')) {
            *errorMessage = tr("Qt Designer is not responding (%1).").arg(socket->errorString());
            return false;
        }
        return true;
    }
    // No process yet. Create socket & launch the process
    QTcpServer server;
    if (!server.listen(QHostAddress::LocalHost)) {
        *errorMessage = tr("Unable to create server socket: %1").arg(server.errorString());
        return false;
    }
    const quint16 port = server.serverPort();
    if (debug)
        qDebug() << Q_FUNC_INFO << "\nLaunching server:" << port << data.binary << filePath;
    // Start first one with file and socket as '-client port file'
    // Wait for the socket listening
    data.arguments.push_front(QString::number(port));
    data.arguments.push_front(QLatin1String("-client"));

    if (!startEditorProcess(data, errorMessage))
        return false;
    // Insert into cache if socket is created, else try again next time
    if (server.waitForNewConnection(3000)) {
        QTcpSocket *socket = server.nextPendingConnection();
        socket->setParent(this);
        const QString binary = data.binary;
        m_processCache.insert(binary, socket);
        auto mapSlot = [this, binary] { processTerminated(binary); };
        connect(socket, &QAbstractSocket::disconnected, this, mapSlot);
        connect(socket, &QAbstractSocket::errorOccurred, this, mapSlot);
    }
    return true;
}

} // namespace Internal
} // namespace QmakeProjectManager