summaryrefslogtreecommitdiffstats
path: root/src/main.cpp
blob: 9786cd022547f5f219a34aa7180de0b525702eea (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
/**************************************************************************
**
** This file is part of Qt Simulator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "qtsingleapplication.h"

#include "ui/mainwindow.h"
#include "qsimulatordata_p.h"
#include "messaging.h"

#ifdef Q_OS_UNIX
    extern "C" {
        #include <sys/types.h>
        #include <sys/ipc.h>
        #include <sys/shm.h>
    }
#endif

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
#include <QtGui/QApplication>
#include <QtGui/QDesktopServices>
#ifdef Q_OS_WIN
#include <QtGui/QMessageBox>
#endif

static void registerSimulator(const QString &location)
{
    QSettings userSettings;
    QSettings *settings = &userSettings;
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
    // If the system settings are writable, don't touch the user settings.
    // The reason is that a simulator started with sudo could otherwise create
    // a root-owned configuration file a user directory.
    QSettings systemSettings(QSettings::SystemScope, SIMULATOR_APP_VENDOR, SIMULATOR_APP_NAME);

    // QSettings::isWritable isn't reliable enough in 4.7, determine writability experimentally
    systemSettings.setValue(SIMULATOR_APP_LOCATION_KEY, QLatin1String("SETTABLE"));
    systemSettings.sync();
    if (systemSettings.status() == QSettings::NoError) {
        settings = &systemSettings;
        if (userSettings.contains(SIMULATOR_APP_LOCATION_KEY))
            userSettings.remove(SIMULATOR_APP_LOCATION_KEY);
    }
#endif

    settings->beginGroup(SIMULATOR_APP_LOCATION_KEY);
    QString simulatorVersionString = simulatorVersion.toString();
    QVariant value = settings->value(simulatorVersionString);
    if (!value.isValid() || settings->value(simulatorVersionString).toString() != location)
        settings->setValue(simulatorVersionString, location);
    settings->endGroup();

    settings->beginGroup(SIMULATOR_APP_QT_VERSIONS_KEY);
    QList<QString> supportedQtVersion;
    supportedQtVersion << "4.7.4.0" << "4.7.4.1" << "4.8.0.0" << "4.8.0.1";
    foreach(const QString &version, supportedQtVersion) {
        QList<QString> simulators;
        QVariant value = settings->value(version);
        if (value.isValid())
            simulators = value.toStringList();
        if (!simulators.contains(simulatorVersionString))
            simulators.append(simulatorVersionString);
        settings->setValue(version, QVariant::fromValue<QStringList>(simulators));
    }
    settings->endGroup();

    const QString dataKey = QLatin1String(SIMULATOR_APP_DATA_KEY);
    QString appDataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
    if (appDataLocation.isEmpty())
        appDataLocation = location;

    value = settings->value(dataKey);
    if (!value.isValid() || settings->value(dataKey).toString() != appDataLocation)
        settings->setValue(dataKey, appDataLocation);
}

void cleanupUnusedSharedMemory()
{
#ifdef Q_OS_UNIX
    // This code depends on the implementation of QSharedMemory
    QDir tmp(QDir::tempPath());
    QStringList possibleFiles = tmp.entryList(QStringList("qipc_sharedmemory_QTSIMULATORSHAREDMEMORY*"), QDir::Files);

    foreach (QString fileName, possibleFiles) {
        int unix_key = ::ftok(QFile::encodeName(tmp.absoluteFilePath(fileName)).constData(), 'Q');

        // Get the number of current attachments
        int id = ::shmget(unix_key, 0, 0444);

        struct shmid_ds shmid_ds;
        if (0 != ::shmctl(id, IPC_STAT, &shmid_ds)) {
            qWarning("getting the number of current attachments failed");
            continue;
        }

        // If there are no attachments then remove it.
        if (shmid_ds.shm_nattch == 0) {
            // mark for removal
            if (-1 == ::shmctl(id, IPC_RMID, &shmid_ds)) {
                qWarning("mark shared memory segment for removal failed");
                continue;
            }

            // remove file
            if (!tmp.remove(fileName)) {
                qWarning("could not remove shared memory segment 'file'");
                continue;
            }
            qDebug() << "superfluous shared memory segment removed";
        }
    }
#endif
}
int main(int argc, char **argv)
{
    cleanupUnusedSharedMemory();

    QCoreApplication::setOrganizationName(SIMULATOR_APP_VENDOR);
    QCoreApplication::setApplicationName(SIMULATOR_APP_NAME);

    SharedTools::QtSingleApplication app(SIMULATOR_APP_NAME + simulatorVersion.toString(), argc, argv);

    QDir::setCurrent(app.applicationDirPath());

    QDir pluginsDir = QDir::current();
    if (pluginsDir.cd("plugins"))
        QApplication::addLibraryPath(pluginsDir.absolutePath());

    registerSimulator(app.applicationFilePath());

    QStringList arguments;
    for (int i = 1; i < argc; ++i) {
        arguments += QString(argv[i]);
    }

    if (arguments.size() == 1) {
        if (arguments[0] == QLatin1String("-registeronly")
                || arguments[0] == QLatin1String("--registeronly")) {
            //As creation of the messaging folder takes ages, we do that when
            //registering the simulator
            Messaging m;
            m.setInitialData();
            // Don't return directly. Otherwise we crash.
            QTimer::singleShot(1000, &app, SLOT(quit()));
            return app.exec();
        }
        if (arguments[0] == QLatin1String("--version")) {
            QString output = "Qt Simulator version " + simulatorVersion.toString() + "\n";
#ifndef Q_OS_WIN
            QTextStream stream(stdout);
            stream << output;
#else
            QMessageBox::information(0, app.applicationName(), output);
#endif
            return EXIT_SUCCESS;
        }
        if (arguments[0] == QLatin1String("--help")) {
            QString output = "Usage: " + QString(argv[0]) + " [arguments]\n"
                      "\n"
                      "Arguments:\n"
                      "    --runscript <file-name>: Execute a script file on a running Simulator instance\n"
                      "    --version: Report the Simulator's version\n";
#ifndef Q_OS_WIN
            QTextStream stream(stdout);
            stream << output;
#else
            QMessageBox::information(0, app.applicationName(), output);
#endif
            return EXIT_SUCCESS;
        }
    }

    bool isFirstInstance = !app.isRunning();

    for (int a = 0; a < arguments.size(); ++a) {
        if (arguments[a] == QLatin1String("-runscript")
                || arguments[a] == QLatin1String("--runscript")) {

            if (isFirstInstance) {
                qWarning() << "Ignored --runscript: No running simulator found";
                return EXIT_FAILURE;
            }

            if (a + 1 >= arguments.size()) {
                qWarning() << "Syntax: --runscript <file-name>";
                return EXIT_FAILURE;
            }
            const QString targetFile = arguments[a + 1];
            ++a;

            if (!app.sendMessage(QString("runscript %1").arg(targetFile))) {
                qWarning() << "Could not send message to running simulator.";
                return EXIT_FAILURE;
            } else {
                return EXIT_SUCCESS;
            }
        }
    }

    if (!isFirstInstance) {
        app.sendMessage(QString("activate"));
        return 0;
    }

    qsrand(QDateTime::currentMSecsSinceEpoch());

    app.initialize();
    MainWindow main;
    app.setActivationWindow(&main);
    QObject::connect(&app, SIGNAL(messageReceived(QString)), &main, SLOT(handleMessage(QString)));
    main.show();
    return app.exec();
}