summaryrefslogtreecommitdiff
path: root/src/webenginequick/ui_delegates_manager.cpp
blob: b4036c5ee51274581e5978b4a31903cbb336d4a4 (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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "ui_delegates_manager.h"

#include "api/qquickwebengineaction_p.h"
#include "api/qquickwebengineview_p_p.h"

#include <authentication_dialog_controller.h>
#include <autofill_popup_controller.h>
#include <color_chooser_controller.h>
#include <file_picker_controller.h>
#include <javascript_dialog_controller.h>
#include <touch_selection_menu_controller.h>
#include <web_contents_adapter_client.h>

#include <QtCore/qfileinfo.h>
#include <QtCore/qlist.h>
#include <QtCore/qtimer.h>
#include <QtGui/qcursor.h>
#include <QtGui/qguiapplication.h>
#include <QtGui/qscreen.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlproperty.h>
#include <QtQuick/qquickwindow.h>

#include <algorithm>

// Uncomment for QML debugging
//#define UI_DELEGATES_DEBUG

namespace QtWebEngineCore {

#define NO_SEPARATOR
#define FILE_NAME_CASE_STATEMENT(TYPE, COMPONENT) \
    case UIDelegatesManager::TYPE:\
        return QStringLiteral(#TYPE".qml");

static QString fileNameForComponent(UIDelegatesManager::ComponentType type)
{
    switch (type) {
    FOR_EACH_COMPONENT_TYPE(FILE_NAME_CASE_STATEMENT, NO_SEPARATOR)
    default:
        Q_UNREACHABLE();
    }
    return QString();
}

static QPoint calculateToolTipPosition(QPoint &position, QSize &toolTip) {
    QRect screen;
    const QList<QScreen *> screens = QGuiApplication::screens();
    for (const QScreen *src : screens)
        if (src->availableGeometry().contains(position))
            screen = src->availableGeometry();

    position += QPoint(2, 16);

    if (position.x() + toolTip.width() > screen.x() + screen.width())
        position.rx() -= 4 + toolTip.width();
    if (position.y() + toolTip.height() > screen.y() + screen.height())
        position.ry() -= 24 + toolTip.height();
    if (position.y() < screen.y())
        position.setY(screen.y());
    if (position.x() + toolTip.width() > screen.x() + screen.width())
        position.setX(screen.x() + screen.width() - toolTip.width());
    if (position.x() < screen.x())
        position.setX(screen.x());
    if (position.y() + toolTip.height() > screen.y() + screen.height())
        position.setY(screen.y() + screen.height() - toolTip.height());

    return position;
}

const char *defaultPropertyName(QObject *obj)
{
    const QMetaObject *metaObject = obj->metaObject();

    int idx = metaObject->indexOfClassInfo("DefaultProperty");
    if (-1 == idx)
        return 0;

    QMetaClassInfo info = metaObject->classInfo(idx);
    return info.value();
}

#define COMPONENT_MEMBER_INIT(TYPE, COMPONENT) \
    , COMPONENT##Component(0)

// clang-format off
UIDelegatesManager::UIDelegatesManager(QQuickWebEngineView *view)
    : m_view(view)
    , m_toolTip(nullptr)
    , m_touchSelectionMenu(nullptr)
    , m_autofillPopup(nullptr)
    FOR_EACH_COMPONENT_TYPE(COMPONENT_MEMBER_INIT, NO_SEPARATOR)
// clang-format on
{
}

UIDelegatesManager::~UIDelegatesManager()
{
}

#define COMPONENT_MEMBER_CASE_STATEMENT(TYPE, COMPONENT) \
    case TYPE: \
        component = &COMPONENT##Component; \
        break;

bool UIDelegatesManager::ensureComponentLoaded(ComponentType type)
{
    QQmlEngine* engine = qmlEngine(m_view);
    if (m_importDirs.isEmpty() && !initializeImportDirs(m_importDirs, engine))
        return false;

    QQmlComponent **component;
    switch (type) {
    FOR_EACH_COMPONENT_TYPE(COMPONENT_MEMBER_CASE_STATEMENT, NO_SEPARATOR)
    default:
        Q_UNREACHABLE();
        return false;
    }
    QString fileName(fileNameForComponent(type));
#ifndef UI_DELEGATES_DEBUG
    if (*component)
        return true;
#else // Unconditionally reload the components each time.
    fprintf(stderr, "%s: %s\n", Q_FUNC_INFO, qPrintable(fileName));
#endif
    if (!engine)
        return false;

    for (const QString &importDir : std::as_const(m_importDirs)) {
        const QString componentFilePath = importDir % QLatin1Char('/') % fileName;

        if (!QFileInfo(componentFilePath).exists())
            continue;

        // FIXME: handle async loading
        *component = (new QQmlComponent(engine,
                                        importDir.startsWith(QLatin1String(":/")) ? QUrl(QLatin1String("qrc") + componentFilePath)
                                                                                  : QUrl::fromLocalFile(componentFilePath),
                                        QQmlComponent::PreferSynchronous, m_view));

        if ((*component)->status() != QQmlComponent::Ready) {
            const QList<QQmlError> errs = (*component)->errors();
            for (const QQmlError &err : errs)
                qWarning("QtWebEngine: component error: %s\n", qPrintable(err.toString()));
            delete *component;
            *component = nullptr;
            return false;
        }
        return true;
    }
    return false;
}

#define CHECK_QML_SIGNAL_PROPERTY(prop, location) \
    if (!prop.isSignalProperty()) \
        qWarning("%s is missing %s signal property.\n", qPrintable(location.toString()), qPrintable(prop.name()));

void UIDelegatesManager::addMenuSeparator(QObject *menu)
{
    if (!ensureComponentLoaded(MenuSeparator))
        return;

    QQmlContext *itemContext = qmlContext(m_view);
    QObject *sep = menuSeparatorComponent->create(itemContext);
    sep->setParent(menu);

    QQmlListReference entries(menu, defaultPropertyName(menu));
    if (entries.isValid() && entries.count() > 0)
        entries.append(sep);
}

#define ASSIGN_DIALOG_COMPONENT_DATA_CASE_STATEMENT(TYPE, COMPONENT) \
    case TYPE:\
        dialogComponent = COMPONENT##Component; \
        break;


void UIDelegatesManager::showDialog(QSharedPointer<JavaScriptDialogController> dialogController)
{
    Q_ASSERT(!dialogController.isNull());
    ComponentType dialogComponentType = Invalid;
    QString title;
    switch (dialogController->type()) {
    case WebContentsAdapterClient::AlertDialog:
        dialogComponentType = AlertDialog;
        title = tr("Javascript Alert - %1").arg(m_view->url().toString());
        break;
    case WebContentsAdapterClient::ConfirmDialog:
        dialogComponentType = ConfirmDialog;
        title = tr("Javascript Confirm - %1").arg(m_view->url().toString());
        break;
    case WebContentsAdapterClient::PromptDialog:
        dialogComponentType = PromptDialog;
        title = tr("Javascript Prompt - %1").arg(m_view->url().toString());
        break;
    case WebContentsAdapterClient::UnloadDialog:
        dialogComponentType = ConfirmDialog;
        title = tr("Are you sure you want to leave this page?");
        break;
    case WebContentsAdapterClient::InternalAuthorizationDialog:
        dialogComponentType = ConfirmDialog;
        title = dialogController->title();
        break;
    default:
        Q_UNREACHABLE();
    }

    if (!ensureComponentLoaded(dialogComponentType)) {
        // Let the controller know it couldn't be loaded
        qWarning("Failed to load dialog, rejecting.");
        dialogController->reject();
        return;
    }

    QQmlComponent *dialogComponent = nullptr;
    switch (dialogComponentType) {
    FOR_EACH_COMPONENT_TYPE(ASSIGN_DIALOG_COMPONENT_DATA_CASE_STATEMENT, NO_SEPARATOR)
    default:
        Q_UNREACHABLE();
    }

    QQmlContext *context = qmlContext(m_view);
    QObject *dialog = dialogComponent->beginCreate(context);
    // set visual parent for non-Window-based dialogs
    if (QQuickItem *item = qobject_cast<QQuickItem*>(dialog))
        item->setParentItem(m_view);
    dialog->setParent(m_view);
    QQmlProperty textProp(dialog, QStringLiteral("text"));
    if (dialogController->type() == WebContentsAdapterClient::UnloadDialog)
        textProp.write(tr("Changes that you made may not be saved."));
    else
        textProp.write(dialogController->message());

    QQmlProperty titleProp(dialog, QStringLiteral("title"));
    titleProp.write(title);

    QQmlProperty acceptSignal(dialog, QStringLiteral("onAccepted"));
    QQmlProperty rejectSignal(dialog, QStringLiteral("onRejected"));
    CHECK_QML_SIGNAL_PROPERTY(acceptSignal, dialogComponent->url());
    CHECK_QML_SIGNAL_PROPERTY(rejectSignal, dialogComponent->url());

    static int acceptIndex = dialogController->metaObject()->indexOfSlot("accept()");
    QObject::connect(dialog, acceptSignal.method(), dialogController.data(), dialogController->metaObject()->method(acceptIndex));
    static int rejectIndex = dialogController->metaObject()->indexOfSlot("reject()");
    QObject::connect(dialog, rejectSignal.method(), dialogController.data(), dialogController->metaObject()->method(rejectIndex));

    if (dialogComponentType == PromptDialog) {
        QQmlProperty promptProp(dialog, QStringLiteral("prompt"));
        promptProp.write(dialogController->defaultPrompt());
        QQmlProperty inputSignal(dialog, QStringLiteral("onInput"));
        CHECK_QML_SIGNAL_PROPERTY(inputSignal, dialogComponent->url());
        static int setTextIndex = dialogController->metaObject()->indexOfSlot("textProvided(QString)");
        QObject::connect(dialog, inputSignal.method(), dialogController.data(), dialogController->metaObject()->method(setTextIndex));
    }

    dialogComponent->completeCreate();

    QObject::connect(dialogController.data(), &JavaScriptDialogController::dialogCloseRequested, dialog, &QObject::deleteLater);

    QMetaObject::invokeMethod(dialog, "open");
}

void UIDelegatesManager::showColorDialog(QSharedPointer<ColorChooserController> controller)
{
    if (!ensureComponentLoaded(ColorDialog)) {
        // Let the controller know it couldn't be loaded
        qWarning("Failed to load dialog, rejecting.");
        controller->reject();
        return;
    }

    QQmlContext *context = qmlContext(m_view);
    QObject *colorDialog = colorDialogComponent->beginCreate(context);
    if (QQuickItem *item = qobject_cast<QQuickItem*>(colorDialog))
        item->setParentItem(m_view);
    colorDialog->setParent(m_view);

    if (controller->initialColor().isValid())
        colorDialog->setProperty("color", controller->initialColor());

    QQmlProperty selectedColorSignal(colorDialog, QStringLiteral("onSelectedColor"));
    CHECK_QML_SIGNAL_PROPERTY(selectedColorSignal, colorDialogComponent->url());
    QQmlProperty rejectedSignal(colorDialog, QStringLiteral("onRejected"));
    CHECK_QML_SIGNAL_PROPERTY(rejectedSignal, colorDialogComponent->url());

    static int acceptIndex = controller->metaObject()->indexOfSlot("accept(QVariant)");
    QObject::connect(colorDialog, selectedColorSignal.method(), controller.data(), controller->metaObject()->method(acceptIndex));
    static int rejectIndex = controller->metaObject()->indexOfSlot("reject()");
    QObject::connect(colorDialog, rejectedSignal.method(), controller.data(), controller->metaObject()->method(rejectIndex));

     // delete later
     static int deleteLaterIndex = colorDialog->metaObject()->indexOfSlot("deleteLater()");
     QObject::connect(colorDialog, selectedColorSignal.method(), colorDialog, colorDialog->metaObject()->method(deleteLaterIndex));
     QObject::connect(colorDialog, rejectedSignal.method(), colorDialog, colorDialog->metaObject()->method(deleteLaterIndex));

    colorDialogComponent->completeCreate();
    QMetaObject::invokeMethod(colorDialog, "open");
}

void UIDelegatesManager::showDialog(QSharedPointer<AuthenticationDialogController> dialogController)
{
    Q_ASSERT(!dialogController.isNull());

    if (!ensureComponentLoaded(AuthenticationDialog)) {
        // Let the controller know it couldn't be loaded
        qWarning("Failed to load authentication dialog, rejecting.");
        dialogController->reject();
        return;
    }

    QQmlContext *context = qmlContext(m_view);
    QObject *authenticationDialog = authenticationDialogComponent->beginCreate(context);
    // set visual parent for non-Window-based dialogs
    if (QQuickItem *item = qobject_cast<QQuickItem*>(authenticationDialog))
        item->setParentItem(m_view);
    authenticationDialog->setParent(m_view);

    QString introMessage;
    if (dialogController->isProxy()) {
        introMessage = tr("Connect to proxy \"%1\" using:");
        introMessage = introMessage.arg(dialogController->host().toHtmlEscaped());
    } else {
        const QUrl url = dialogController->url();
        introMessage = tr("Enter username and password for \"%1\" at %2://%3");
        introMessage = introMessage.arg(dialogController->realm(), url.scheme(), url.host());
    }
    QQmlProperty textProp(authenticationDialog, QStringLiteral("text"));
    textProp.write(introMessage);

    QQmlProperty acceptSignal(authenticationDialog, QStringLiteral("onAccepted"));
    QQmlProperty rejectSignal(authenticationDialog, QStringLiteral("onRejected"));
    CHECK_QML_SIGNAL_PROPERTY(acceptSignal, authenticationDialogComponent->url());
    CHECK_QML_SIGNAL_PROPERTY(rejectSignal, authenticationDialogComponent->url());

    static int acceptIndex = dialogController->metaObject()->indexOfSlot("accept(QString,QString)");
    static int deleteLaterIndex = authenticationDialog->metaObject()->indexOfSlot("deleteLater()");
    QObject::connect(authenticationDialog, acceptSignal.method(), dialogController.data(), dialogController->metaObject()->method(acceptIndex));
    QObject::connect(authenticationDialog, acceptSignal.method(), authenticationDialog, authenticationDialog->metaObject()->method(deleteLaterIndex));
    static int rejectIndex = dialogController->metaObject()->indexOfSlot("reject()");
    QObject::connect(authenticationDialog, rejectSignal.method(), dialogController.data(), dialogController->metaObject()->method(rejectIndex));
    QObject::connect(authenticationDialog, rejectSignal.method(), authenticationDialog, authenticationDialog->metaObject()->method(deleteLaterIndex));

    authenticationDialogComponent->completeCreate();
    QMetaObject::invokeMethod(authenticationDialog, "open");
}

void UIDelegatesManager::showFilePicker(QSharedPointer<FilePickerController> controller)
{
    if (controller->mode() == FilePickerController::UploadFolder) {
        showDirectoryPicker(controller);
        return;
    }

    if (!ensureComponentLoaded(FilePicker))
        return;

    QQmlContext *context = qmlContext(m_view);
    QObject *filePicker = filePickerComponent->beginCreate(context);
    if (QQuickItem *item = qobject_cast<QQuickItem*>(filePicker))
        item->setParentItem(m_view);
    filePicker->setParent(m_view);
    filePickerComponent->completeCreate();

    static int fileModeIndex = filePicker->metaObject()->indexOfEnumerator("FileMode");
    QMetaEnum fileModeEnum = filePicker->metaObject()->enumerator(fileModeIndex);

    // Fine-tune some properties depending on the mode.
    switch (controller->mode()) {
    case FilePickerController::Open:
        filePicker->setProperty("fileMode", fileModeEnum.keyToValue("OpenFile"));
        break;
    case FilePickerController::Save:
        filePicker->setProperty("fileMode", fileModeEnum.keyToValue("SaveFile"));
        break;
    case FilePickerController::OpenMultiple:
        filePicker->setProperty("fileMode", fileModeEnum.keyToValue("OpenFiles"));
        break;
    case FilePickerController::UploadFolder:
    default:
        Q_UNREACHABLE();
    }

    filePicker->setProperty("nameFilters", FilePickerController::nameFilters(controller->acceptedMimeTypes()));

    QQmlProperty filesPickedSignal(filePicker, QStringLiteral("onFilesSelected"));
    CHECK_QML_SIGNAL_PROPERTY(filesPickedSignal, filePickerComponent->url());
    QQmlProperty rejectSignal(filePicker, QStringLiteral("onRejected"));
    CHECK_QML_SIGNAL_PROPERTY(rejectSignal, filePickerComponent->url());
    static int acceptedIndex = controller->metaObject()->indexOfSlot("accepted(QVariant)");
    QObject::connect(filePicker, filesPickedSignal.method(), controller.data(), controller->metaObject()->method(acceptedIndex));
    static int rejectedIndex = controller->metaObject()->indexOfSlot("rejected()");
    QObject::connect(filePicker, rejectSignal.method(), controller.data(), controller->metaObject()->method(rejectedIndex));

    // delete when done.
    static int deleteLaterIndex = filePicker->metaObject()->indexOfSlot("deleteLater()");
    QObject::connect(filePicker, filesPickedSignal.method(), filePicker, filePicker->metaObject()->method(deleteLaterIndex));
    QObject::connect(filePicker, rejectSignal.method(), filePicker, filePicker->metaObject()->method(deleteLaterIndex));

    QMetaObject::invokeMethod(filePicker, "open");
}

void UIDelegatesManager::showDirectoryPicker(QSharedPointer<FilePickerController> controller)
{
    if (!ensureComponentLoaded(DirectoryPicker))
        return;

    QQmlContext *context = qmlContext(m_view);
    QObject *directoryPicker = directoryPickerComponent->beginCreate(context);
    if (QQuickItem *item = qobject_cast<QQuickItem*>(directoryPicker))
        item->setParentItem(m_view);
    directoryPicker->setParent(m_view);
    directoryPickerComponent->completeCreate();

    QQmlProperty directoryPickedSignal(directoryPicker, QStringLiteral("onFolderSelected"));
    CHECK_QML_SIGNAL_PROPERTY(directoryPickedSignal, directoryPickerComponent->url());
    QQmlProperty rejectSignal(directoryPicker, QStringLiteral("onRejected"));
    CHECK_QML_SIGNAL_PROPERTY(rejectSignal, directoryPickerComponent->url());
    static int acceptedIndex = controller->metaObject()->indexOfSlot("accepted(QVariant)");
    QObject::connect(directoryPicker, directoryPickedSignal.method(), controller.data(), controller->metaObject()->method(acceptedIndex));
    static int rejectedIndex = controller->metaObject()->indexOfSlot("rejected()");
    QObject::connect(directoryPicker, rejectSignal.method(), controller.data(), controller->metaObject()->method(rejectedIndex));

    // delete when done.
    static int deleteLaterIndex = directoryPicker->metaObject()->indexOfSlot("deleteLater()");
    QObject::connect(directoryPicker, directoryPickedSignal.method(), directoryPicker, directoryPicker->metaObject()->method(deleteLaterIndex));
    QObject::connect(directoryPicker, rejectSignal.method(), directoryPicker, directoryPicker->metaObject()->method(deleteLaterIndex));

    QMetaObject::invokeMethod(directoryPicker, "open");
}

class TemporaryCursorMove
{
public:
    TemporaryCursorMove(const QQuickItem *item, const QPoint &pos)
    {
        if (pos.isNull() || !item->contains(pos))
            return;
        const QPoint oldPos = QCursor::pos();
        const QPoint globalPos = item->mapToGlobal(QPointF(pos)).toPoint();
        if (oldPos == globalPos)
            return;
        m_oldCursorPos = oldPos;
        QCursor::setPos(globalPos);
    }

    ~TemporaryCursorMove()
    {
        if (!m_oldCursorPos.isNull())
            QCursor::setPos(m_oldCursorPos);
    }

private:
    QPoint m_oldCursorPos;
};

void UIDelegatesManager::showToolTip(const QString &text)
{
    if (text.isEmpty()) {
        m_toolTip.reset();
        return;
    }

    if (!ensureComponentLoaded(ToolTip))
        return;

    if (!m_toolTip.isNull())
        return;

    QQmlContext *context = qmlContext(m_view);
    m_toolTip.reset(toolTipComponent->beginCreate(context));
    if (QQuickItem *item = qobject_cast<QQuickItem *>(m_toolTip.data()))
        item->setParentItem(m_view);
    m_toolTip->setParent(m_view);
    toolTipComponent->completeCreate();

    QQmlProperty(m_toolTip.data(), QStringLiteral("text")).write(text);

    int height = QQmlProperty(m_toolTip.data(), QStringLiteral("height")).read().toInt();
    int width = QQmlProperty(m_toolTip.data(), QStringLiteral("width")).read().toInt();
    QSize toolTipSize(width, height);
    QPoint position = m_view->cursor().pos();
    position = m_view->mapFromGlobal(calculateToolTipPosition(position, toolTipSize)).toPoint();

    QQmlProperty(m_toolTip.data(), QStringLiteral("x")).write(position.x());
    QQmlProperty(m_toolTip.data(), QStringLiteral("y")).write(position.y());

    QMetaObject::invokeMethod(m_toolTip.data(), "open");
}

QQuickItem *UIDelegatesManager::createTouchHandle()
{
    if (!ensureComponentLoaded(TouchHandle))
        return nullptr;

    QQmlContext *context = qmlContext(m_view);
    QObject *touchHandle = touchHandleComponent->beginCreate(context);
    QQuickItem *item = qobject_cast<QQuickItem *>(touchHandle);
    Q_ASSERT(item);
    item->setParentItem(m_view);
    touchHandleComponent->completeCreate();

    return item;
}

void UIDelegatesManager::showTouchSelectionMenu(QtWebEngineCore::TouchSelectionMenuController *menuController, const QRect &bounds, const int spacing)
{
    if (!ensureComponentLoaded(TouchSelectionMenu))
        return;

    QQmlContext *context = qmlContext(m_view);
    m_touchSelectionMenu.reset(touchSelectionMenuComponent->beginCreate(context));
    if (QQuickItem *item = qobject_cast<QQuickItem *>(m_touchSelectionMenu.data()))
        item->setParentItem(m_view);
    m_touchSelectionMenu->setParent(m_view);

    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("width")).write(bounds.width());
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("height")).write(bounds.height());
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("x")).write(bounds.x());
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("y")).write(bounds.y());
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("border.width")).write(spacing);

    // Cut button
    bool cutEnabled = menuController->isCommandEnabled(TouchSelectionMenuController::Cut);
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("isCutEnabled")).write(cutEnabled);
    if (cutEnabled) {
        QQmlProperty cutSignal(m_touchSelectionMenu.data(), QStringLiteral("onCutTriggered"));
        CHECK_QML_SIGNAL_PROPERTY(cutSignal, touchSelectionMenuComponent->url());
        int cutIndex = menuController->metaObject()->indexOfSlot("cut()");
        QObject::connect(m_touchSelectionMenu.data(), cutSignal.method(), menuController, menuController->metaObject()->method(cutIndex));
    }

    // Copy button
    bool copyEnabled = menuController->isCommandEnabled(TouchSelectionMenuController::Copy);
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("isCopyEnabled")).write(copyEnabled);
    if (copyEnabled) {
        QQmlProperty copySignal(m_touchSelectionMenu.data(), QStringLiteral("onCopyTriggered"));
        CHECK_QML_SIGNAL_PROPERTY(copySignal, touchSelectionMenuComponent->url());
        int copyIndex = menuController->metaObject()->indexOfSlot("copy()");
        QObject::connect(m_touchSelectionMenu.data(), copySignal.method(), menuController, menuController->metaObject()->method(copyIndex));
    }

    // Paste button
    bool pasteEnabled = menuController->isCommandEnabled(TouchSelectionMenuController::Paste);
    QQmlProperty(m_touchSelectionMenu.data(), QStringLiteral("isPasteEnabled")).write(pasteEnabled);
    if (pasteEnabled) {
        QQmlProperty pasteSignal(m_touchSelectionMenu.data(), QStringLiteral("onPasteTriggered"));
        CHECK_QML_SIGNAL_PROPERTY(pasteSignal, touchSelectionMenuComponent->url());
        int pasteIndex = menuController->metaObject()->indexOfSlot("paste()");
        QObject::connect(m_touchSelectionMenu.data(), pasteSignal.method(), menuController, menuController->metaObject()->method(pasteIndex));
    }

    // Context menu button
    QQmlProperty contextMenuSignal(m_touchSelectionMenu.data(), QStringLiteral("onContextMenuTriggered"));
    CHECK_QML_SIGNAL_PROPERTY(contextMenuSignal, touchSelectionMenuComponent->url());
    int contextMenuIndex = menuController->metaObject()->indexOfSlot("runContextMenu()");
    QObject::connect(m_touchSelectionMenu.data(), contextMenuSignal.method(), menuController, menuController->metaObject()->method(contextMenuIndex));

    touchSelectionMenuComponent->completeCreate();
}

void UIDelegatesManager::hideTouchSelectionMenu()
{
    QTimer::singleShot(0, m_view, [this] { m_touchSelectionMenu.reset(); });
}

bool AutofillPopupEventFilter::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::ShortcutOverride) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Escape) {
            m_manager->hideAutofillPopup();
            return true;
        }

        // Ignore shortcuts while the popup is open. It may result unwanted
        // edit commands sent to Chromium that blocks the key press.
        event->ignore();
        return true;
    }

    // AutofillPopupControllerImpl::HandleKeyPressEvent()
    // chrome/browser/ui/autofill/autofill_popup_controller_impl.cc

    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        switch (keyEvent->key()) {
        case Qt::Key_Up:
            m_controller->selectPreviousSuggestion();
            return true;
        case Qt::Key_Down:
            m_controller->selectNextSuggestion();
            return true;
        case Qt::Key_PageUp:
            m_controller->selectFirstSuggestion();
            return true;
        case Qt::Key_PageDown:
            m_controller->selectLastSuggestion();
            return true;
        case Qt::Key_Escape:
            m_manager->hideAutofillPopup();
            return true;
        case Qt::Key_Enter:
        case Qt::Key_Return:
            m_controller->acceptSuggestion();
            return true;
        case Qt::Key_Delete:
            // Remove suggestion is not supported for datalist.
            // Forward delete to view to be able to remove selected text.
            break;
        case Qt::Key_Tab:
            m_controller->acceptSuggestion();
            break;
        default:
            break;
        }
    }

    // Do not forward release events of the overridden key presses.
    if (event->type() == QEvent::KeyRelease) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        switch (keyEvent->key()) {
        case Qt::Key_Up:
        case Qt::Key_Down:
        case Qt::Key_PageUp:
        case Qt::Key_PageDown:
        case Qt::Key_Escape:
        case Qt::Key_Enter:
        case Qt::Key_Return:
            return true;
        default:
            break;
        }
    }

    return QObject::eventFilter(object, event);
}

void UIDelegatesManager::showAutofillPopup(QtWebEngineCore::AutofillPopupController *controller,
                                           QPointF pos, int width, bool autoselectFirstSuggestion)
{
    static const int padding = 1;
    static const int itemHeight = 20;
    const int proposedHeight = itemHeight * (controller->model()->rowCount()) + padding * 2;

    bool popupWasNull = false;
    if (m_autofillPopup.isNull()) {
        popupWasNull = true;
        if (!ensureComponentLoaded(AutofillPopup))
            return;

        QQmlContext *context = qmlContext(m_view);
        m_autofillPopup.reset(autofillPopupComponent->beginCreate(context));
        if (QQuickItem *item = qobject_cast<QQuickItem *>(m_autofillPopup.data()))
            item->setParentItem(m_view);
        m_autofillPopup->setParent(m_view);
    }

    m_autofillPopup->setProperty("controller", QVariant::fromValue(controller));
    m_autofillPopup->setProperty("x", pos.x());
    m_autofillPopup->setProperty("y", pos.y());
    m_autofillPopup->setProperty("width", width);
    m_autofillPopup->setProperty("height",
                                 std::min(proposedHeight, qRound(m_view->height() - pos.y())));
    m_autofillPopup->setProperty("padding", padding);
    m_autofillPopup->setProperty("itemHeight", itemHeight);

    if (popupWasNull) {
        QQmlProperty selectedSignal(m_autofillPopup.data(), QStringLiteral("onSelected"));
        CHECK_QML_SIGNAL_PROPERTY(selectedSignal, autofillPopupComponent->url());
        static int selectSuggestionIndex =
                controller->metaObject()->indexOfSlot("selectSuggestion(int)");
        QObject::connect(m_autofillPopup.data(), selectedSignal.method(), controller,
                         controller->metaObject()->method(selectSuggestionIndex));

        QQmlProperty acceptedSignal(m_autofillPopup.data(), QStringLiteral("onAccepted"));
        CHECK_QML_SIGNAL_PROPERTY(acceptedSignal, autofillPopupComponent->url());
        static int acceptSuggestionIndex =
                controller->metaObject()->indexOfSlot("acceptSuggestion()");
        QObject::connect(m_autofillPopup.data(), acceptedSignal.method(), controller,
                         controller->metaObject()->method(acceptSuggestionIndex));

        QObject::connect(controller, &QtWebEngineCore::AutofillPopupController::currentIndexChanged,
                         [this](const QModelIndex &index) {
                             QMetaObject::invokeMethod(m_autofillPopup.data(), "setCurrentIndex",
                                                       Qt::DirectConnection,
                                                       Q_ARG(QVariant, index.row()));
                         });

        autofillPopupComponent->completeCreate();

        m_view->window()->installEventFilter(
                new AutofillPopupEventFilter(controller, this, m_autofillPopup.data()));

        QMetaObject::invokeMethod(m_autofillPopup.data(), "open");
        controller->notifyPopupShown();
    }

    if (autoselectFirstSuggestion)
        controller->selectFirstSuggestion();
}

void UIDelegatesManager::hideAutofillPopup()
{
    if (!m_autofillPopup)
        return;

    QTimer::singleShot(0, m_view, [this] {
        if (m_autofillPopup) {
            QtWebEngineCore::AutofillPopupController *controller =
                    m_autofillPopup->property("controller")
                            .value<QtWebEngineCore::AutofillPopupController *>();
            m_autofillPopup.reset();
            controller->notifyPopupHidden();
        }
    });
}

bool UIDelegatesManager::initializeImportDirs(QStringList &dirs, QQmlEngine *engine)
{
    const QStringList paths = engine->importPathList();
    for (const QString &path : paths) {
        QString controlsImportPath = path % QLatin1String("/QtWebEngine/ControlsDelegates/");

        // resource paths have to be tested using the ":/" prefix
        if (controlsImportPath.startsWith(QLatin1String("qrc:/"))) {
            controlsImportPath.remove(0, 3);
        }

        QFileInfo fi(controlsImportPath);
        if (fi.exists())
            dirs << fi.absolutePath();
    }
    return !dirs.isEmpty();
}

QObject *UIDelegatesManager::addMenu(QObject *parentMenu, const QString &title, const QPoint &pos)
{
    Q_ASSERT(parentMenu);
    if (!ensureComponentLoaded(Menu))
        return nullptr;
    QQmlContext *context = qmlContext(m_view);
    QObject *menu = menuComponent->beginCreate(context);

    // set visual parent for non-Window-based menus
    if (QQuickItem *item = qobject_cast<QQuickItem*>(menu))
        item->setParentItem(m_view);

    if (!title.isEmpty())
        menu->setProperty("title", title);
    if (!pos.isNull()) {
        menu->setProperty("x", pos.x());
        menu->setProperty("y", pos.y());
    }

    menu->setParent(parentMenu);
    QQmlProperty doneSignal(menu, QStringLiteral("onDone"));
    CHECK_QML_SIGNAL_PROPERTY(doneSignal, menuComponent->url())
    static int deleteLaterIndex = menu->metaObject()->indexOfSlot("deleteLater()");
    QObject::connect(menu, doneSignal.method(), menu, menu->metaObject()->method(deleteLaterIndex));
    menuComponent->completeCreate();
    return menu;
}

void UIDelegatesManager::addMenuItem(QQuickWebEngineAction *action, QObject *menu, bool checkable, bool checked)
{
    Q_ASSERT(action);
    if (!ensureComponentLoaded(MenuItem))
        return;

    QObject *it = menuItemComponent->beginCreate(qmlContext(m_view));

    it->setProperty("text", action->text());
    it->setProperty("enabled", action->isEnabled());
    it->setProperty("checked", checked);
    it->setProperty("checkable", checkable);

    QQmlProperty signal(it, QStringLiteral("onTriggered"));
    CHECK_QML_SIGNAL_PROPERTY(signal, menuItemComponent->url());
    const QMetaObject *actionMeta = action->metaObject();
    QObject::connect(it, signal.method(), action, actionMeta->method(actionMeta->indexOfSlot("trigger()")));
    menuItemComponent->completeCreate();

    it->setParent(menu);

    QQmlListReference entries(menu, defaultPropertyName(menu));
    if (entries.isValid())
        entries.append(it);
}

void UIDelegatesManager::showMenu(QObject *menu)
{
    QMetaObject::invokeMethod(menu, "open");
}

} // namespace QtWebEngineCore