summaryrefslogtreecommitdiffstats
path: root/src/winmain/qtmain_winrt.cpp
blob: 81ca07e447519ac4f80c967d41224c187a6825c7 (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
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
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
387
388
389
390
391
392
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Windows main function of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*
  This file contains the code in the qtmain library for WinRT.
  qtmain contains the WinRT startup code and is required for
  linking to the Qt DLL.

  When a Windows application starts, the WinMain function is
  invoked. This WinMain creates the WinRT application
  container, which in turn calls the application's main()
  entry point within the newly created GUI thread.
*/

#if _MSC_VER < 1900
#include <new.h>

typedef struct
{
    int newmode;
} _startupinfo;
#endif // _MSC_VER < 1900

extern "C" {
#if _MSC_VER < 1900
    int __getmainargs(int *argc, char ***argv, char ***env, int expandWildcards, _startupinfo *info);
#endif
    int main(int, char **);
}

#include <qbytearray.h>
#include <qstring.h>
#include <qdir.h>
#include <qstandardpaths.h>
#include <qfunctions_winrt.h>
#include <qcoreapplication.h>

#include <wrl.h>
#include <Windows.ApplicationModel.core.h>
#include <windows.ui.xaml.h>
#include <windows.ui.xaml.controls.h>

using namespace ABI::Windows::ApplicationModel;
using namespace ABI::Windows::ApplicationModel::Activation;
using namespace ABI::Windows::ApplicationModel::Core;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::UI;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

#define qHString(x) Wrappers::HString::MakeReference(x).Get()
#define CoreApplicationClass RuntimeClass_Windows_ApplicationModel_Core_CoreApplication
typedef ITypedEventHandler<CoreApplicationView *, Activation::IActivatedEventArgs *> ActivatedHandler;

static QtMessageHandler defaultMessageHandler;
static void devMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
#ifndef Q_OS_WINPHONE
    static HANDLE shmem = 0;
    static HANDLE event = 0;
    if (!shmem)
        shmem = CreateFileMappingFromApp(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 4096, L"qdebug-shmem");
    if (!event)
        event = CreateEventEx(NULL, L"qdebug-event", 0, EVENT_ALL_ACCESS);

    void *data = MapViewOfFileFromApp(shmem, FILE_MAP_WRITE, 0, 4096);
    memset(data, quint32(type), sizeof(quint32));
    memcpy_s(static_cast<quint32 *>(data) + 1, 4096 - sizeof(quint32),
             message.data(), (message.length() + 1) * sizeof(wchar_t));
    UnmapViewOfFile(data);
    SetEvent(event);
#endif // !Q_OS_WINPHONE
    defaultMessageHandler(type, context, message);
}

class QActivationEvent : public QEvent
{
public:
    explicit QActivationEvent(IInspectable *args)
        : QEvent(QEvent::WinEventAct)
    {
        setAccepted(false);
        args->AddRef();
        d = reinterpret_cast<QEventPrivate *>(args);
    }

    ~QActivationEvent() {
        IUnknown *args = reinterpret_cast<IUnknown *>(d);
        args->Release();
        d = nullptr;
    }
};

class AppContainer : public RuntimeClass<Xaml::IApplicationOverrides>
{
public:
    AppContainer()
    {
        ComPtr<Xaml::IApplicationFactory> applicationFactory;
        HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Application).Get(),
                                            IID_PPV_ARGS(&applicationFactory));
        Q_ASSERT_SUCCEEDED(hr);

        hr = applicationFactory->CreateInstance(this, &base, &core);
        RETURN_VOID_IF_FAILED("Failed to create application container instance");

        pidFile = INVALID_HANDLE_VALUE;
    }

    ~AppContainer()
    {
    }

    int exec(int argc, char **argv)
    {
        args.reserve(argc);
        for (int i = 0; i < argc; ++i)
            args.append(argv[i]);

        mainThread = CreateThread(NULL, 0, [](void *param) -> DWORD {
            AppContainer *app = reinterpret_cast<AppContainer *>(param);
            int argc = app->args.count();
            char **argv = app->args.data();
            const int res = main(argc, argv);
            if (app->pidFile != INVALID_HANDLE_VALUE) {
                const QByteArray resString = QByteArray::number(res);
                WriteFile(app->pidFile, reinterpret_cast<LPCVOID>(resString.constData()),
                          resString.size(), NULL, NULL);
                FlushFileBuffers(app->pidFile);
                CloseHandle(app->pidFile);
            }
            app->core->Exit();
            return res;
        }, this, CREATE_SUSPENDED, nullptr);

        HRESULT hr;
        ComPtr<Xaml::IApplicationStatics> appStatics;
        hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Xaml_Application).Get(),
                                    IID_PPV_ARGS(&appStatics));
        Q_ASSERT_SUCCEEDED(hr);
        hr = appStatics->Start(Callback<Xaml::IApplicationInitializationCallback>([](Xaml::IApplicationInitializationCallbackParams *) {
            return S_OK;
        }).Get());
        Q_ASSERT_SUCCEEDED(hr);

        WaitForSingleObjectEx(mainThread, INFINITE, FALSE);
        DWORD exitCode;
        GetExitCodeThread(mainThread, &exitCode);
        return exitCode;
    }

private:
    HRESULT activatedLaunch(IInspectable *activateArgs) {
        QCoreApplication *app = QCoreApplication::instance();

        // Check whether the app already runs
        if (!app) {
#if _MSC_VER >= 1900
            // I*EventArgs have no launch arguments, hence we
            // need to prepend the application binary manually
            wchar_t fn[513];
            DWORD res = GetModuleFileName(0, fn, 512);

            if (SUCCEEDED(res))
                args.prepend(QString::fromWCharArray(fn, res).toUtf8().data());
#endif _MSC_VER >= 1900

            ResumeThread(mainThread);

            // We give main() a max of 100ms to create an application object.
            // No eventhandling needs to happen at that point, all we want is
            // append our activation event
            int iterations = 0;
            while (true) {
                app = QCoreApplication::instance();
                if (app || iterations++ > 10)
                    break;
                Sleep(10);
            }
        }

        if (app)
            QCoreApplication::postEvent(app, new QActivationEvent(activateArgs));
        return S_OK;
    }

    HRESULT __stdcall OnActivated(IActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        return activatedLaunch(args);
    }

    HRESULT __stdcall OnLaunched(ILaunchActivatedEventArgs *launchArgs) Q_DECL_OVERRIDE
    {
#if _MSC_VER >= 1900
        ComPtr<IPrelaunchActivatedEventArgs> preArgs;
        HRESULT hr = launchArgs->QueryInterface(preArgs.GetAddressOf());
        if (SUCCEEDED(hr)) {
            boolean prelaunched;
            preArgs->get_PrelaunchActivated(&prelaunched);
            if (prelaunched)
                return S_OK;
        }

        commandLine = QString::fromWCharArray(GetCommandLine()).toUtf8();
#endif
        HString launchCommandLine;
        launchArgs->get_Arguments(launchCommandLine.GetAddressOf());
        if (launchCommandLine.IsValid()) {
            quint32 launchCommandLineLength;
            const wchar_t *launchCommandLineBuffer = launchCommandLine.GetRawBuffer(&launchCommandLineLength);
            if (!commandLine.isEmpty() && launchCommandLineLength)
                commandLine += ' ';
            if (launchCommandLineLength)
                commandLine += QString::fromWCharArray(launchCommandLineBuffer, launchCommandLineLength).toUtf8();
        }
        if (!commandLine.isEmpty())
            args.append(commandLine.data());

        bool quote = false;
        bool escape = false;
        for (int i = 0; i < commandLine.size(); ++i) {
            switch (commandLine.at(i)) {
            case '\\':
                escape = true;
                break;
            case '"':
                if (escape) {
                    escape = false;
                    break;
                }
                quote = !quote;
                commandLine[i] = '\0';
                break;
            case ' ':
                if (quote)
                    break;
                commandLine[i] = '\0';
                if (args.last()[0] != '\0')
                    args.append(commandLine.data() + i + 1);
                // fall through
            default:
                if (args.last()[0] == '\0')
                    args.last() = commandLine.data() + i;
                escape = false; // only quotes are escaped
                break;
            }
        }

        if (args.count() >= 2 && strncmp(args.at(1), "-ServerName:", 12) == 0)
            args.remove(1);

        bool develMode = false;
        bool debugWait = false;
        foreach (const char *arg, args) {
            if (strcmp(arg, "-qdevel") == 0)
                develMode = true;
            if (strcmp(arg, "-qdebug") == 0)
                debugWait = true;
        }
        if (develMode) {
            // Write a PID file to help runner
            const QString pidFileName = QDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation))
                    .absoluteFilePath(QString::number(uint(GetCurrentProcessId())) + QStringLiteral(".pid"));
            CREATEFILE2_EXTENDED_PARAMETERS params = {
                sizeof(CREATEFILE2_EXTENDED_PARAMETERS),
                FILE_ATTRIBUTE_NORMAL
            };
            pidFile = CreateFile2(reinterpret_cast<LPCWSTR>(pidFileName.utf16()),
                        GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, &params);
            // Install the develMode message handler
#ifndef Q_OS_WINPHONE
            defaultMessageHandler = qInstallMessageHandler(devMessageHandler);
#endif
        }
        // Wait for debugger before continuing
        if (debugWait) {
            while (!IsDebuggerPresent())
                WaitForSingleObjectEx(GetCurrentThread(), 1, true);
        }

        ResumeThread(mainThread);
        return S_OK;
    }

    HRESULT __stdcall OnFileActivated(IFileActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        return activatedLaunch(args);
    }

    HRESULT __stdcall OnSearchActivated(ISearchActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        Q_UNUSED(args);
        return S_OK;
    }

    HRESULT __stdcall OnShareTargetActivated(IShareTargetActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        return activatedLaunch(args);
    }

    HRESULT __stdcall OnFileOpenPickerActivated(IFileOpenPickerActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        Q_UNUSED(args);
        return S_OK;
    }

    HRESULT __stdcall OnFileSavePickerActivated(IFileSavePickerActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        Q_UNUSED(args);
        return S_OK;
    }

    HRESULT __stdcall OnCachedFileUpdaterActivated(ICachedFileUpdaterActivatedEventArgs *args) Q_DECL_OVERRIDE
    {
        Q_UNUSED(args);
        return S_OK;
    }

    HRESULT __stdcall OnWindowCreated(Xaml::IWindowCreatedEventArgs *args) Q_DECL_OVERRIDE
    {
        Q_UNUSED(args);
        return S_OK;
    }

    ComPtr<Xaml::IApplicationOverrides> base;
    ComPtr<Xaml::IApplication> core;
    QByteArray commandLine;
    QVarLengthArray<char *> args;
    HANDLE mainThread{0};
    HANDLE pidFile;
};

// Main entry point for Appx containers
int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    int argc = 0;
    char **argv = 0, **env = 0;
#if _MSC_VER < 1900
    _startupinfo info = { _query_new_mode() };
    if (int init = __getmainargs(&argc, &argv, &env, false, &info))
        return init;
#endif // _MSC_VER >= 1900
    for (int i = 0; env && env[i]; ++i) {
        QByteArray var(env[i]);
        int split = var.indexOf('=');
        if (split > 0)
            qputenv(var.mid(0, split), var.mid(split + 1));
    }

    if (FAILED(RoInitialize(RO_INIT_MULTITHREADED)))
        return 1;

    ComPtr<AppContainer> app = Make<AppContainer>();
    return app->exec(argc, argv);
}