aboutsummaryrefslogtreecommitdiffstats
path: root/examples/demos/windowembedding/main.cpp
blob: 049afd8ab486719e413a5288648b486576cc3bb5 (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
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include <QRasterWindow>
#include <QPainter>
#include <QShortcut>

#include <QApplication>
#include <QVBoxLayout>
#include <QWidget>

#include <QQmlApplicationEngine>
#include <QQuickView>

QList<std::function<void()>> cleanupFunctions;

#if defined(Q_OS_MACOS)

//! [macos]
#include <AppKit/NSDatePicker.h>
#include <AppKit/NSLayoutConstraint.h>

QWindow *createCalendarWindow()
{
    auto *datePicker = [NSDatePicker new];
    cleanupFunctions.push_back([=]{ [datePicker release]; });

    datePicker.datePickerStyle = NSDatePickerStyleClockAndCalendar;
    datePicker.datePickerElements = NSDatePickerElementFlagYearMonthDay;
    datePicker.drawsBackground = YES;
    datePicker.dateValue = [NSDate now];

    auto *calendarWindow = QWindow::fromWinId(WId(datePicker));
    calendarWindow->setMinimumSize(QSizeF::fromCGSize(datePicker.fittingSize).toSize());

    return calendarWindow;
}
//! [macos]

#elif defined(QT_PLATFORM_UIKIT)

//! [ios]
#include <UIKit/UIDatePicker.h>

QWindow *createCalendarWindow()
{
    auto *datePicker = [UIDatePicker new];
    cleanupFunctions.push_back([=]{ [datePicker release]; });

    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.preferredDatePickerStyle = UIDatePickerStyleInline;
    datePicker.backgroundColor = UIColor.systemBackgroundColor;

    auto *calendarWindow = QWindow::fromWinId(WId(datePicker));
    calendarWindow->setMinimumSize(QSizeF::fromCGSize(datePicker.frame.size).toSize());

    return calendarWindow;
}
//! [ios]

#elif defined(Q_OS_WIN)

//! [windows]
#include <windows.h>
#include <commctrl.h>

QWindow *createCalendarWindow()
{
    static bool initializedDateControl = []{
        INITCOMMONCONTROLSEX icex;
        icex.dwSize = sizeof(icex);
        icex.dwICC = ICC_DATE_CLASSES;
        return InitCommonControlsEx(&icex);
    }();
    Q_ASSERT(initializedDateControl);

    HWND monthCalendar = CreateWindow(MONTHCAL_CLASSW,
        nullptr, MCS_NOTODAYCIRCLE | MCS_NOTODAY, 0, 0, 0, 0,
        nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
    cleanupFunctions.push_back([=]{ DestroyWindow(monthCalendar); });

    auto *calendarWindow = QWindow::fromWinId(WId(monthCalendar));

    RECT minimumSize;
    MonthCal_GetMinReqRect(monthCalendar, &minimumSize);
    const auto dpr = calendarWindow->devicePixelRatio();
    calendarWindow->setMinimumSize(QSize(
        minimumSize.right / dpr,minimumSize.bottom / dpr));

    return calendarWindow;
}
//! [windows]

#elif defined(Q_OS_ANDROID)

//! [android]
Q_DECLARE_JNI_CLASS(CalendarView, "android/widget/CalendarView")
Q_DECLARE_JNI_CLASS(Color, "android/graphics/Color")

QWindow *createCalendarWindow()
{
    using namespace QtJniTypes;
    using namespace QNativeInterface;

    auto *androidApp = qGuiApp->nativeInterface<QAndroidApplication>();
    Q_ASSERT(androidApp);

    auto *calendarView = new CalendarView(androidApp->context());
    cleanupFunctions.push_back([=]{ delete calendarView; });

    // Resolving Android default colors is not trivial, so let's ask Qt
    QColor paletteColor = qGuiApp->palette().color(QPalette::Window);
    int backgroundColor = Color::callStaticMethod<int>("rgb",
        paletteColor.red(), paletteColor.green(), paletteColor.blue());
    calendarView->callMethod<void>("setBackgroundColor", backgroundColor);

    auto *calendarWindow = QWindow::fromWinId(WId(calendarView->object()));
    calendarWindow->setMinimumSize(QSize(200, 220));

    return calendarWindow;
}
//! [android]

#elif QT_CONFIG(xcb) && __has_include(<gtk/gtk.h>)

QT_REQUIRE_CONFIG(glib);

//! [x11]
#include <gtk/gtk.h>
#include <gtk/gtkx.h>

QWindow *createCalendarWindow()
{
    static bool initializedGTK = []{
        qputenv("GDK_BACKEND", "x11");
        return gtk_init_check(nullptr, nullptr);
    }();
    Q_ASSERT(initializedGTK);

    auto *plug = gtk_plug_new(0);
    g_signal_connect(GTK_WIDGET(plug), "delete-event", G_CALLBACK(+[]{
        return true; // Don't destroy on close
    }), nullptr);
    cleanupFunctions.push_back([=]{ gtk_widget_destroy(GTK_WIDGET(plug)); });

    auto *calendar = gtk_calendar_new();
    gtk_container_add(GTK_CONTAINER(plug), GTK_WIDGET(calendar));
    gtk_widget_show_all(plug);

    auto *calendarWindow = QWindow::fromWinId(gtk_plug_get_id(GTK_PLUG(plug)));

    GtkRequisition minimumSize;
    gtk_widget_get_preferred_size(calendar, &minimumSize, NULL);
    calendarWindow->setMinimumSize(QSize(minimumSize.width, minimumSize.height));

    return calendarWindow;
}
//! [x11]

#elif defined(Q_OS_WASM)

//! [webassembly]
#include <emscripten.h>
#include <emscripten/val.h>
using emscripten::val;
using emscripten::EM_VAL;

EM_JS(EM_VAL, createCalendarElement, (), {
    var calendar = document.createElement("calendar-date");
    calendar.innerHTML = "<calendar-month></calendar-month>";
    return Emval.toHandle(calendar);
});

QWindow *createCalendarWindow()
{
    static bool initializedCalendarComponent = []{
        return EM_ASM_INT(
            var script = document.createElement('script');
            script.src = "https://unpkg.com/cally";
            script.type = "module";
            document.head.appendChild(script);
            return true;
        );
    }();
    Q_ASSERT(initializedCalendarComponent);

    val *calendarElement = new val(val::take_ownership(createCalendarElement()));
    cleanupFunctions.push_back([calendarElement]{ delete calendarElement; });

    QWindow *window = QWindow::fromWinId(WId(calendarElement));
    window->setMinimumSize(QSize(250, 300));
    return window;
}
//! [webassembly]

#else

class GrayWindow : public QRasterWindow
{
protected:
    void paintEvent(QPaintEvent *) override
    {
        QPainter painter(this);
        QRectF rect(0, 0, width(), height());
        painter.fillRect(rect, Qt::gray);
        painter.drawText(rect, Qt::AlignCenter,
            "Qt fallback\nforeign window");

    }
};

QWindow *createCalendarWindow()
{
    #warning Using Qt fallback implementation of foreign window

    auto *calendarWindow = new GrayWindow;
    calendarWindow->setMinimumSize(QSize(150, 150));
    return calendarWindow;
}

#endif

constexpr QMargins contentsMargins = {20, 20, 20, 20};

//! [qt-gui-container-window]
class ContainerWindow : public QRasterWindow
{
protected:
    bool event(QEvent *event) override
    {
        if (event->type() == QEvent::ChildWindowAdded) {
            auto *childWindow = static_cast<QChildWindowEvent*>(event)->child();
            childWindow->resize(childWindow->minimumSize());
            setMinimumSize(childWindow->size().grownBy(contentsMargins));
            resize(minimumSize());
        }

        return QRasterWindow::event(event);
    }

    void showEvent(QShowEvent *) override
    {
        findChild<QWindow*>()->setVisible(true);
    }

    void resizeEvent(QResizeEvent *) override
    {
        auto *containedWindow = findChild<QWindow*>();
        containedWindow->setPosition(
            (width() / 2)  - containedWindow->width() / 2,
            (height() / 2) - containedWindow->height() / 2
        );
    }

    void paintEvent(QPaintEvent *) override
    {
        QPainter painter(this);
        painter.fillRect(0, 0, width(), height(), "#00414A");
    }
};
//! [qt-gui-container-window]

int main(int argc, char* argv[])
{
    QApplication app(argc,argv);
    QCoreApplication::setOrganizationName("QtProject");
    QCoreApplication::setOrganizationDomain("qt-project.org");
    QCoreApplication::setApplicationName("Window Embedding");

    QShortcut quitShortcut(QKeySequence::Quit, &app, &app,
        &QCoreApplication::quit, Qt::ApplicationShortcut);

    qAddPostRoutine([]{
        for (auto cleanupFunction : cleanupFunctions)
            cleanupFunction();
    });

    //! [qt-gui]
    ContainerWindow window;
    window.setTitle("Qt Gui");

    auto *calendarWindow = createCalendarWindow();
    calendarWindow->setParent(&window);
    //! [qt-gui]

    //! [qt-widgets]
    QWidget widget;
    widget.setPalette(QColor("#CDB0FF"));
    widget.setWindowTitle("Qt Widgets");
    widget.setLayout(new QVBoxLayout);
    widget.layout()->setContentsMargins(contentsMargins);
    widget.layout()->setAlignment(Qt::AlignCenter);

    auto *calendarWidget = QWidget::createWindowContainer(createCalendarWindow());
    widget.layout()->addWidget(calendarWidget);
    //! [qt-widgets]

    //! [qt-quick]
    QQmlApplicationEngine engine;
    engine.setInitialProperties({{ "calendarWindow", QVariant::fromValue(createCalendarWindow()) }});
    engine.loadFromModule("windowembedding", "Main");
    //! [qt-quick]

    auto &quickWindow = *qobject_cast<QQuickWindow *>(engine.rootObjects().first());

    auto positionWindows = [&]{
        auto screenCenter = app.primaryScreen()->availableGeometry().center();
        widget.adjustSize();
        auto top = screenCenter.y() - widget.height() / 2;
        widget.setGeometry(screenCenter.x() - widget.width() / 2, top, widget.width(), widget.height());
        window.setPosition(QPoint(widget.geometry().left() - window.width() - contentsMargins.left(), top));
        quickWindow.setPosition(QPoint(widget.geometry().right() + contentsMargins.right(), top));
    };
    // Handle mobile devices by dynamically adjusting to the screen geometry
    QObject::connect(app.primaryScreen(), &QScreen::availableGeometryChanged, positionWindows);

    positionWindows();

    widget.showNormal();
    window.showNormal();
    quickWindow.showNormal();

    return app.exec();
}