externaleditors.cpp 11.2 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29

30
31
32
33
#include "externaleditors.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"

34
#include <utils/hostosinfo.h>
35
36
#include <utils/synchronousprocess.h>
#include <projectexplorer/projectexplorer.h>
Tobias Hunger's avatar
Tobias Hunger committed
37
#include <projectexplorer/target.h>
38
#include <projectexplorer/session.h>
Tobias Hunger's avatar
Tobias Hunger committed
39
#include <qtsupport/qtkitinformation.h>
40
41
#include <designer/designerconstants.h>

42
43
44
#include <QProcess>
#include <QDebug>
#include <QSignalMapper>
45

46
47
#include <QTcpSocket>
#include <QTcpServer>
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

enum { debug = 0 };

namespace Qt4ProjectManager {
namespace Internal {

// Figure out the Qt4 project used by the file if any
static Qt4Project *qt4ProjectFor(const QString &fileName)
{
    ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
    if (ProjectExplorer::Project *baseProject = pe->session()->projectForFile(fileName))
        if (Qt4Project *project = qobject_cast<Qt4Project*>(baseProject))
            return project;
    return 0;
}

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

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

// -- Commands and helpers
77
78
79
80
81
82
83
84
85
static QString linguistBinary()
{
    return QLatin1String(Utils::HostOsInfo::isMacHost() ? "Linguist" : "linguist");
}

static QString designerBinary()
{
    return QLatin1String(Utils::HostOsInfo::isMacHost() ? "Designer" : "designer");
}
86

87
88
// Mac: Change the call 'Foo.app/Contents/MacOS/Foo <filelist>' to
// 'open -a Foo.app <filelist>'. doesn't support generic command line arguments
89
90
91
92
93
94
static void createMacOpenCommand(QString *binary, QStringList *arguments)
{
    const int appFolderIndex = binary->lastIndexOf(QLatin1String("/Contents/MacOS/"));
    if (appFolderIndex != -1) {
        binary->truncate(appFolderIndex);
        arguments->push_front(*binary);
95
        arguments->push_front(QLatin1String("-a"));
96
97
98
99
        *binary = QLatin1String("open");
    }
}

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

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

// -------------- ExternalQtEditor
107
ExternalQtEditor::ExternalQtEditor(Core::Id id,
108
109
110
                                   const QString &displayName,
                                   const QString &mimetype,
                                   QObject *parent) :
111
112
    Core::IExternalEditor(parent),
    m_mimeTypes(mimetype),
113
    m_id(id),
114
    m_displayName(displayName)
115
116
117
118
119
120
121
122
{
}

QStringList ExternalQtEditor::mimeTypes() const
{
    return m_mimeTypes;
}

hjk's avatar
hjk committed
123
Core::Id ExternalQtEditor::id() const
124
125
126
127
128
{
    return m_id;
}

QString ExternalQtEditor::displayName() const
129
{
130
    return m_displayName;
131
132
133
134
135
136
137
138
139
140
141
}

bool ExternalQtEditor::getEditorLaunchData(const QString &fileName,
                                           QtVersionCommandAccessor commandAccessor,
                                           const QString &fallbackBinary,
                                           const QStringList &additionalArguments,
                                           bool useMacOpenCommand,
                                           EditorLaunchData *data,
                                           QString *errorMessage) const
{
    // Get the binary either from the current Qt version of the project or Path
142
    if (const Qt4Project *project = qt4ProjectFor(fileName)) {
Tobias Hunger's avatar
Tobias Hunger committed
143
        if (const ProjectExplorer::Target *target = project->activeTarget()) {
Tobias Hunger's avatar
Tobias Hunger committed
144
            if (const QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(target->kit())) {
Tobias Hunger's avatar
Tobias Hunger committed
145
146
                data->binary = (qtVersion->*commandAccessor)();
                data->workingDirectory = project->projectDirectory();
147
148
149
150
            }
        }
    }
    if (data->binary.isEmpty()) {
151
        data->workingDirectory.clear();
152
        data->binary = Utils::SynchronousProcess::locateBinary(fallbackBinary);
153
154
    }
    if (data->binary.isEmpty()) {
hjk's avatar
hjk committed
155
        *errorMessage = msgAppNotFound(id().toString());
156
157
158
159
160
        return false;
    }
    // Setup binary + arguments, use Mac Open if appropriate
    data->arguments = additionalArguments;
    data->arguments.push_back(fileName);
161
    if (Utils::HostOsInfo::isMacHost() && useMacOpenCommand)
Friedemann Kleint's avatar
Friedemann Kleint committed
162
        createMacOpenCommand(&(data->binary), &(data->arguments));
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << data->binary << data->arguments;
    return true;
}

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

// --------------- LinguistExternalEditor
LinguistExternalEditor::LinguistExternalEditor(QObject *parent) :
182
       ExternalQtEditor(linguistIdC,
183
                        QLatin1String(linguistDisplayName),
184
185
186
187
188
189
190
191
                        QLatin1String(Qt4ProjectManager::Constants::LINGUIST_MIMETYPE),
                        parent)
{
}

bool LinguistExternalEditor::startEditor(const QString &fileName, QString *errorMessage)
{
    EditorLaunchData data;
192
    return getEditorLaunchData(fileName, &QtSupport::BaseQtVersion::linguistCommand,
193
194
                            linguistBinary(), QStringList(), true, &data, errorMessage)
            && startEditorProcess(data, errorMessage);
195
196
197
198
}

// --------------- MacDesignerExternalEditor, using Mac 'open'
MacDesignerExternalEditor::MacDesignerExternalEditor(QObject *parent) :
199
       ExternalQtEditor(designerIdC,
200
                        QLatin1String(designerDisplayName),
201
202
203
204
205
206
207
208
                        QLatin1String(Qt4ProjectManager::Constants::FORM_MIMETYPE),
                        parent)
{
}

bool MacDesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage)
{
    EditorLaunchData data;
209
    return getEditorLaunchData(fileName, &QtSupport::BaseQtVersion::designerCommand,
210
                            designerBinary(), QStringList(), true, &data, errorMessage)
211
212
213
214
215
216
        && startEditorProcess(data, errorMessage);
    return false;
}

// --------------- DesignerExternalEditor with Designer Tcp remote control.
DesignerExternalEditor::DesignerExternalEditor(QObject *parent) :
217
    ExternalQtEditor(designerIdC,
218
                     QLatin1String(designerDisplayName),
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
                     QLatin1String(Designer::Constants::FORM_MIMETYPE),
                     parent),
    m_terminationMapper(0)
{
}

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 QString &fileName, QString *errorMessage)
{
    EditorLaunchData data;
    // Find the editor binary
244
    if (!getEditorLaunchData(fileName, &QtSupport::BaseQtVersion::designerCommand,
245
                            designerBinary(), QStringList(), false, &data, errorMessage)) {
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
        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 << fileName;
        QTcpSocket *socket = it.value();
        if (!socket->write(fileName.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 << fileName;
    // 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;
    // Set up signal mapper to track process termination via socket
    if (!m_terminationMapper) {
        m_terminationMapper = new QSignalMapper(this);
        connect(m_terminationMapper, SIGNAL(mapped(QString)), this, SLOT(processTerminated(QString)));
    }
    // Insert into cache if socket is created, else try again next time
    if (server.waitForNewConnection(3000)) {
        QTcpSocket *socket = server.nextPendingConnection();
        socket->setParent(this);
        m_processCache.insert(data.binary, socket);
        m_terminationMapper->setMapping(socket, data.binary);
        connect(socket, SIGNAL(disconnected()), m_terminationMapper, SLOT(map()));
        connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), m_terminationMapper, SLOT(map()));
    }
    return true;
}

} // namespace Internal
} // namespace Qt4ProjectManager