summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/settings/editors/UIHostComboEditor.cpp
blob: d140c73eff4c599b560cabb012455e8a208e8d3e (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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/* $Id$ */
/** @file
 * VBox Qt GUI - UIHostComboEditor class implementation.
 */

/*
 * Copyright (C) 2006-2022 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

/* Qt includes: */
#include <QApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QStyleOption>
#include <QStylePainter>
#include <QTimer>
#if defined(VBOX_WS_MAC) || defined(VBOX_WS_WIN)
# include <QAbstractNativeEventFilter>
#endif

/* GUI includes: */
#include "QIToolButton.h"
#include "UICommon.h"
#include "UIExtraDataManager.h"
#include "UIHostComboEditor.h"
#include "UIIconPool.h"
#ifdef VBOX_WS_MAC
# include "UICocoaApplication.h"
# include "VBoxUtils-darwin.h"
# include "DarwinKeyboard.h"
#elif defined(VBOX_WS_WIN)
# include "WinKeyboard.h"
#elif defined(VBOX_WS_X11)
# include "XKeyboard.h"
# include "VBoxUtils-x11.h"
#endif

/* Other VBox includes: */
#if defined(VBOX_WS_X11)
# include <VBox/VBoxKeyboard.h>
#endif

/* External includes: */
#if defined(VBOX_WS_MAC)
# include <Carbon/Carbon.h>
#elif defined(VBOX_WS_X11)
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# include <X11/keysym.h>
# include <xcb/xcb.h>
#endif /* VBOX_WS_X11 */

/* Namespaces: */
using namespace UIExtraDataDefs;


#if defined(VBOX_WS_MAC) || defined(VBOX_WS_WIN)
/** QAbstractNativeEventFilter extension
  * allowing to handle native platform events.
  * Why do we need it? It's because Qt5 have unhandled
  * well .. let's call it 'a bug' about native keyboard events
  * which come to top-level widget (window) instead of focused sub-widget
  * which actually supposed to get them. The strange thing is that target of
  * those events on at least Windows host (MSG::hwnd) is indeed window itself,
  * not the sub-widget we expect, so that's probably the reason Qt devs
  * haven't fixed that bug so far for Windows and Mac OS X hosts. */
class ComboEditorEventFilter : public QAbstractNativeEventFilter
{
public:

    /** Constructor which takes the passed @a pParent to redirect events to. */
    ComboEditorEventFilter(UIHostComboEditorPrivate *pParent)
        : m_pParent(pParent)
    {}

    /** Handles all native events. */
# ifdef VBOX_IS_QT6_OR_LATER
    virtual bool nativeEventFilter(const QByteArray &eventType, void *pMessage, qintptr *pResult) RT_OVERRIDE
# else
    virtual bool nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pResult) RT_OVERRIDE
# endif
    {
        /* Redirect event to parent: */
        return m_pParent->nativeEvent(eventType, pMessage, pResult);
    }

private:

    /** Holds the passed parent reference. */
    UIHostComboEditorPrivate *m_pParent;
};
#endif /* VBOX_WS_MAC || VBOX_WS_WIN */


/*********************************************************************************************************************************
*   Namespace UINativeHotKey implementation.                                                                                     *
*********************************************************************************************************************************/

#ifdef VBOX_WS_X11
namespace UINativeHotKey
{
    QMap<QString, QString> m_keyNames;
}
#endif /* VBOX_WS_X11 */

QString UINativeHotKey::toString(int iKeyCode)
{
    QString strKeyName;

#if defined(VBOX_WS_MAC)

    UInt32 modMask = DarwinKeyCodeToDarwinModifierMask(iKeyCode);
    switch (modMask)
    {
        case shiftKey:
        case optionKey:
        case controlKey:
        case cmdKey:
            strKeyName = UIHostComboEditor::tr("Left %1");
            break;
        case rightShiftKey:
        case rightOptionKey:
        case rightControlKey:
        case kEventKeyModifierRightCmdKeyMask:
            strKeyName = UIHostComboEditor::tr("Right %1");
            break;
        default:
            AssertMsgFailedReturn(("modMask=%#x\n", modMask), QString());
    }
    switch (modMask)
    {
        case shiftKey:
        case rightShiftKey:
            strKeyName = strKeyName.arg(QChar(kShiftUnicode));
            break;
        case optionKey:
        case rightOptionKey:
            strKeyName = strKeyName.arg(QChar(kOptionUnicode));
            break;
        case controlKey:
        case rightControlKey:
            strKeyName = strKeyName.arg(QChar(kControlUnicode));
            break;
        case cmdKey:
        case kEventKeyModifierRightCmdKeyMask:
            strKeyName = strKeyName.arg(QChar(kCommandUnicode));
            break;
    }

#elif defined(VBOX_WS_WIN)

    // WORKAROUND:
    // MapVirtualKey doesn't distinguish between right and left vkeys,
    // even under XP, despite that it stated in MSDN. Do it by hands.
    // Besides that it can't recognize such virtual keys as
    // VK_DIVIDE & VK_PAUSE, this is also known bug.
    int iScan;
    switch (iKeyCode)
    {
        /* Processing special keys... */
        case VK_PAUSE: iScan = 0x45 << 16; break;
        case VK_RSHIFT: iScan = 0x36 << 16; break;
        case VK_RCONTROL: iScan = (0x1D << 16) | (1 << 24); break;
        case VK_RMENU: iScan = (0x38 << 16) | (1 << 24); break;
        /* Processing extended keys... */
        case VK_APPS:
        case VK_LWIN:
        case VK_RWIN:
        case VK_NUMLOCK: iScan = (::MapVirtualKey(iKeyCode, 0) | 256) << 16; break;
        default: iScan = ::MapVirtualKey(iKeyCode, 0) << 16;
    }
    TCHAR *pKeyName = new TCHAR[256];
    if (::GetKeyNameText(iScan, pKeyName, 256))
    {
        strKeyName = QString::fromUtf16(pKeyName);
    }
    else
    {
        AssertMsgFailed(("That key have no name!\n"));
        strKeyName = UIHostComboEditor::tr("<key_%1>").arg(iKeyCode);
    }
    delete[] pKeyName;

#elif defined(VBOX_WS_X11)

    if (char *pNativeKeyName = ::XKeysymToString((KeySym)iKeyCode))
    {
        strKeyName = m_keyNames[pNativeKeyName].isEmpty() ?
                     QString(pNativeKeyName) : m_keyNames[pNativeKeyName];
    }
    else
    {
        AssertMsgFailed(("That key have no name!\n"));
        strKeyName = UIHostComboEditor::tr("<key_%1>").arg(iKeyCode);
    }

#else

# warning "port me!"

#endif

    return strKeyName;
}

bool UINativeHotKey::isValidKey(int iKeyCode)
{
#if defined(VBOX_WS_MAC)

    UInt32 modMask = ::DarwinKeyCodeToDarwinModifierMask(iKeyCode);
    switch (modMask)
    {
        case shiftKey:
        case optionKey:
        case controlKey:
        case rightShiftKey:
        case rightOptionKey:
        case rightControlKey:
        case cmdKey:
        case kEventKeyModifierRightCmdKeyMask:
            return true;
        default:
            return false;
    }

#elif defined(VBOX_WS_WIN)

    return (   iKeyCode >= VK_SHIFT  && iKeyCode <= VK_CAPITAL
            && iKeyCode != VK_PAUSE)
        || (iKeyCode >= VK_LSHIFT && iKeyCode <= VK_RMENU)
        || (iKeyCode >= VK_F1     && iKeyCode <= VK_F24)
        || iKeyCode == VK_NUMLOCK
        || iKeyCode == VK_SCROLL
        || iKeyCode == VK_LWIN
        || iKeyCode == VK_RWIN
        || iKeyCode == VK_APPS
        || iKeyCode == VK_PRINT;

#elif defined(VBOX_WS_X11)

    return (IsModifierKey(iKeyCode) /* allow modifiers */ ||
            IsFunctionKey(iKeyCode) /* allow function keys */ ||
            IsMiscFunctionKey(iKeyCode) /* allow miscellaneous function keys */ ||
            iKeyCode == XK_Scroll_Lock /* allow 'Scroll Lock' missed in IsModifierKey() */) &&
           (iKeyCode != NoSymbol /* ignore some special symbol */ &&
            iKeyCode != XK_Insert /* ignore 'insert' included into IsMiscFunctionKey */);

#else

# warning "port me!"

    return false;

#endif
}

unsigned UINativeHotKey::modifierToSet1ScanCode(int iKeyCode)
{
    switch(iKeyCode)
    {
#if defined(VBOX_WS_MAC)

        case controlKey:                        return 0x1D;
        case rightControlKey:                   return 0x11D;
        case shiftKey:                          return 0x2A;
        case rightShiftKey:                     return 0x36;
        case optionKey:                         return 0x38;
        case rightOptionKey:                    return 0x138;
        case cmdKey:                            return 0x15B;
        case kEventKeyModifierRightCmdKeyMask:  return 0x15C;
        default:                                return 0;

#elif defined(VBOX_WS_WIN)

        case VK_CONTROL:
        case VK_LCONTROL:  return 0x1D;
        case VK_RCONTROL:  return 0x11D;
        case VK_SHIFT:
        case VK_LSHIFT:    return 0x2A;
        case VK_RSHIFT:    return 0x36;
        case VK_MENU:
        case VK_LMENU:     return 0x38;
        case VK_RMENU:     return 0x138;
        case VK_LWIN:      return 0x15B;
        case VK_RWIN:      return 0x15C;
        case VK_APPS:      return 0x15D;
        default:           return 0;

#elif defined(VBOX_WS_X11)

        case XK_Control_L:         return 0x1D;
        case XK_Control_R:         return 0x11D;
        case XK_Shift_L:           return 0x2A;
        case XK_Shift_R:           return 0x36;
        case XK_Alt_L:             return 0x38;
        case XK_ISO_Level3_Shift:
        case XK_Alt_R:             return 0x138;
        case XK_Meta_L:
        case XK_Super_L:           return 0x15B;
        case XK_Meta_R:
        case XK_Super_R:           return 0x15C;
        case XK_Menu:              return 0x15D;
        default:                   return 0;

#else

# warning "port me!"

        default:  return 0;

#endif
    }
}

#if defined(VBOX_WS_WIN)

int UINativeHotKey::distinguishModifierVKey(int wParam, int lParam)
{
    int iKeyCode = wParam;
    switch (iKeyCode)
    {
        case VK_SHIFT:
        {
            UINT uCurrentScanCode = (lParam & 0x01FF0000) >> 16;
            UINT uLeftScanCode = ::MapVirtualKey(iKeyCode, 0);
            if (uCurrentScanCode == uLeftScanCode)
                iKeyCode = VK_LSHIFT;
            else
                iKeyCode = VK_RSHIFT;
            break;
        }
        case VK_CONTROL:
        {
            UINT uCurrentScanCode = (lParam & 0x01FF0000) >> 16;
            UINT uLeftScanCode = ::MapVirtualKey(iKeyCode, 0);
            if (uCurrentScanCode == uLeftScanCode)
                iKeyCode = VK_LCONTROL;
            else
                iKeyCode = VK_RCONTROL;
            break;
        }
        case VK_MENU:
        {
            UINT uCurrentScanCode = (lParam & 0x01FF0000) >> 16;
            UINT uLeftScanCode = ::MapVirtualKey(iKeyCode, 0);
            if (uCurrentScanCode == uLeftScanCode)
                iKeyCode = VK_LMENU;
            else
                iKeyCode = VK_RMENU;
            break;
        }
    }
    return iKeyCode;
}

#elif defined(VBOX_WS_X11)

void UINativeHotKey::retranslateKeyNames()
{
    m_keyNames["Shift_L"]          = UIHostComboEditor::tr("Left Shift");
    m_keyNames["Shift_R"]          = UIHostComboEditor::tr("Right Shift");
    m_keyNames["Control_L"]        = UIHostComboEditor::tr("Left Ctrl");
    m_keyNames["Control_R"]        = UIHostComboEditor::tr("Right Ctrl");
    m_keyNames["Alt_L"]            = UIHostComboEditor::tr("Left Alt");
    m_keyNames["Alt_R"]            = UIHostComboEditor::tr("Right Alt");
    m_keyNames["Super_L"]          = UIHostComboEditor::tr("Left WinKey");
    m_keyNames["Super_R"]          = UIHostComboEditor::tr("Right WinKey");
    m_keyNames["Menu"]             = UIHostComboEditor::tr("Menu key");
    m_keyNames["ISO_Level3_Shift"] = UIHostComboEditor::tr("Alt Gr");
    m_keyNames["Caps_Lock"]        = UIHostComboEditor::tr("Caps Lock");
    m_keyNames["Scroll_Lock"]      = UIHostComboEditor::tr("Scroll Lock");
}

#endif /* VBOX_WS_X11 */


/*********************************************************************************************************************************
*   Namespace UIHostCombo implementation.                                                                                        *
*********************************************************************************************************************************/

namespace UIHostCombo
{
    int m_iMaxComboSize = 3;
}

int UIHostCombo::hostComboModifierIndex()
{
    return -1;
}

QString UIHostCombo::hostComboModifierName()
{
    return UIHostComboEditor::tr("Host+");
}

QString UIHostCombo::hostComboCacheKey()
{
    return QString(GUI_Input_MachineShortcuts) + "/" + "HostCombo";
}

QString UIHostCombo::toReadableString(const QString &strKeyCombo)
{
    QStringList encodedKeyList = strKeyCombo.split(',');
    QStringList readableKeyList;
    for (int i = 0; i < encodedKeyList.size(); ++i)
        if (int iKeyCode = encodedKeyList[i].toInt())
            readableKeyList << UINativeHotKey::toString(iKeyCode);
    return readableKeyList.isEmpty() ? UIHostComboEditor::tr("None") : readableKeyList.join(" + ");
}

QList<int> UIHostCombo::toKeyCodeList(const QString &strKeyCombo)
{
    QStringList encodedKeyList = strKeyCombo.split(',');
    QList<int> keyCodeList;
    for (int i = 0; i < encodedKeyList.size(); ++i)
        if (int iKeyCode = encodedKeyList[i].toInt())
            keyCodeList << iKeyCode;
    return keyCodeList;
}

QList<unsigned> UIHostCombo::modifiersToScanCodes(const QString &strKeyCombo)
{
    QStringList encodedKeyList = strKeyCombo.split(',');
    QList<unsigned> scanCodeList;
    for (int i = 0; i < encodedKeyList.size(); ++i)
        if (unsigned idxScanCode = UINativeHotKey::modifierToSet1ScanCode(encodedKeyList[i].toInt()))
            if (idxScanCode != 0)
                scanCodeList << idxScanCode;
    return scanCodeList;
}

bool UIHostCombo::isValidKeyCombo(const QString &strKeyCombo)
{
    QList<int> keyCodeList = toKeyCodeList(strKeyCombo);
    if (keyCodeList.size() > m_iMaxComboSize)
        return false;
    for (int i = 0; i < keyCodeList.size(); ++i)
        if (!UINativeHotKey::isValidKey(keyCodeList[i]))
            return false;
    return true;
}


/*********************************************************************************************************************************
*   Class UIHostComboEditor implementation.                                                                                      *
*********************************************************************************************************************************/

UIHostComboEditor::UIHostComboEditor(QWidget *pParent)
    : QIWithRetranslateUI<QWidget>(pParent)
{
    /* Prepare: */
    prepare();
}

void UIHostComboEditor::retranslateUi()
{
    /* Translate 'clear' tool-button: */
    m_pButtonClear->setToolTip(QApplication::translate("UIHotKeyEditor", "Unset shortcut"));
}

void UIHostComboEditor::sltCommitData()
{
    /* Commit data to the listener: */
    emit sigCommitData(this);
}

void UIHostComboEditor::prepare()
{
    /* Make sure QIStyledDelegate aware of us: */
    setProperty("has_sigCommitData", true);
    /* Configure self: */
    setAutoFillBackground(true);
    /* Create layout: */
    QHBoxLayout *pLayout = new QHBoxLayout(this);
    {
        /* Configure layout: */
#ifdef VBOX_WS_MAC
        pLayout->setSpacing(5);
#else
        pLayout->setSpacing(qApp->style()->pixelMetric(QStyle::PM_LayoutVerticalSpacing) / 2);
#endif
        pLayout->setContentsMargins(0, 0, 0, 0);
        /* Create UIHostComboEditorPrivate instance: */
        m_pEditor = new UIHostComboEditorPrivate;
        {
            /* Configure UIHostComboEditorPrivate instance: */
            setFocusProxy(m_pEditor);
            connect(m_pEditor, &UIHostComboEditorPrivate::sigDataChanged, this, &UIHostComboEditor::sltCommitData);
        }
        /* Create 'clear' tool-button: */
        m_pButtonClear = new QIToolButton;
        {
            /* Configure 'clear' tool-button: */
            m_pButtonClear->removeBorder();
            m_pButtonClear->setIcon(UIIconPool::iconSet(":/eraser_16px.png"));
            connect(m_pButtonClear, &QIToolButton::clicked, m_pEditor, &UIHostComboEditorPrivate::sltClear);
        }
        /* Add widgets to layout: */
        pLayout->addWidget(m_pEditor);
        pLayout->addWidget(m_pButtonClear);
    }
    /* Translate finally: */
    retranslateUi();
}

void UIHostComboEditor::setCombo(const UIHostComboWrapper &strCombo)
{
    /* Pass combo to child: */
    m_pEditor->setCombo(strCombo);
}

UIHostComboWrapper UIHostComboEditor::combo() const
{
    /* Acquire combo from child: */
    return m_pEditor->combo();
}


/*********************************************************************************************************************************
*   Class UIHostComboEditorPrivate implementation.                                                                               *
*********************************************************************************************************************************/

UIHostComboEditorPrivate::UIHostComboEditorPrivate()
    : m_pReleaseTimer(0)
    , m_fStartNewSequence(true)
#if defined(VBOX_WS_MAC) || defined(VBOX_WS_WIN)
    , m_pPrivateEventFilter(0)
#endif
#ifdef VBOX_WS_WIN
    , m_pAltGrMonitor(0)
#endif
{
    /* Configure widget: */
    setAttribute(Qt::WA_NativeWindow);
    setContextMenuPolicy(Qt::NoContextMenu);
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);
    connect(this, &UIHostComboEditorPrivate::selectionChanged, this, &UIHostComboEditorPrivate::sltDeselect);

    /* Setup release-pending-keys timer: */
    m_pReleaseTimer = new QTimer(this);
    m_pReleaseTimer->setInterval(200);
    connect(m_pReleaseTimer, &QTimer::timeout, this, &UIHostComboEditorPrivate::sltReleasePendingKeys);

#if defined(VBOX_WS_MAC) || defined(VBOX_WS_WIN)
    /* Prepare private event filter: */
    m_pPrivateEventFilter = new ComboEditorEventFilter(this);
    qApp->installNativeEventFilter(m_pPrivateEventFilter);
#endif /* VBOX_WS_MAC || VBOX_WS_WIN */

#if defined(VBOX_WS_MAC)
    m_uDarwinKeyModifiers = 0;
#elif defined(VBOX_WS_WIN)
    /* Prepare AltGR monitor: */
    m_pAltGrMonitor = new WinAltGrMonitor;
#elif defined(VBOX_WS_X11)
    /* Initialize the X keyboard subsystem: */
    initMappedX11Keyboard(NativeWindowSubsystem::X11GetDisplay(), gEDataManager->remappedScanCodes());
#endif /* VBOX_WS_X11 */
}

UIHostComboEditorPrivate::~UIHostComboEditorPrivate()
{
#if defined(VBOX_WS_WIN)
    /* Cleanup AltGR monitor: */
    delete m_pAltGrMonitor;
    m_pAltGrMonitor = 0;
#endif /* VBOX_WS_WIN */

#if defined(VBOX_WS_MAC) || defined(VBOX_WS_WIN)
    /* Cleanup private event filter: */
    qApp->removeNativeEventFilter(m_pPrivateEventFilter);
    delete m_pPrivateEventFilter;
    m_pPrivateEventFilter = 0;
#endif /* VBOX_WS_MAC || VBOX_WS_WIN */
}

void UIHostComboEditorPrivate::setCombo(const UIHostComboWrapper &strCombo)
{
    /* Cleanup old combo: */
    m_shownKeys.clear();
    /* Parse newly passed combo: */
    QList<int> keyCodeList = UIHostCombo::toKeyCodeList(strCombo.toString());
    for (int i = 0; i < keyCodeList.size(); ++i)
        if (int iKeyCode = keyCodeList[i])
            m_shownKeys.insert(iKeyCode, UINativeHotKey::toString(iKeyCode));
    /* Update text: */
    updateText();
}

UIHostComboWrapper UIHostComboEditorPrivate::combo() const
{
    /* Compose current combination: */
    QStringList keyCodeStringList;
    QList<int> keyCodeList = m_shownKeys.keys();
    for (int i = 0; i < keyCodeList.size(); ++i)
        keyCodeStringList << QString::number(keyCodeList[i]);
    /* Return current combination or "0" for "None": */
    return keyCodeStringList.isEmpty() ? "0" : keyCodeStringList.join(",");
}

void UIHostComboEditorPrivate::sltDeselect()
{
    deselect();
}

void UIHostComboEditorPrivate::sltClear()
{
    /* Cleanup combo: */
    m_shownKeys.clear();
    /* Update text: */
    updateText();
    /* Move the focus to text-field: */
    setFocus();
    /* Notify data changed: */
    emit sigDataChanged();
}

#ifdef VBOX_IS_QT6_OR_LATER
bool UIHostComboEditorPrivate::nativeEvent(const QByteArray &eventType, void *pMessage, qintptr *pResult)
#else
bool UIHostComboEditorPrivate::nativeEvent(const QByteArray &eventType, void *pMessage, long *pResult)
#endif
{
# if defined(VBOX_WS_MAC)

    /* Make sure it's generic NSEvent: */
    if (eventType != "mac_generic_NSEvent")
        return QLineEdit::nativeEvent(eventType, pMessage, pResult);
    EventRef event = static_cast<EventRef>(darwinCocoaToCarbonEvent(pMessage));

    /* Check if some NSEvent should be filtered out: */
    // Returning @c true means filtering-out,
    // Returning @c false means passing event to Qt.
    switch(::GetEventClass(event))
    {
        /* Watch for keyboard-events: */
        case kEventClassKeyboard:
        {
            switch(::GetEventKind(event))
            {
                /* Watch for keyboard-modifier-events: */
                case kEventRawKeyModifiersChanged:
                {
                    /* Get modifier mask: */
                    UInt32 modifierMask = 0;
                    ::GetEventParameter(event, kEventParamKeyModifiers, typeUInt32,
                                        NULL, sizeof(modifierMask), NULL, &modifierMask);
                    modifierMask = ::DarwinAdjustModifierMask(modifierMask, pMessage);

                    /* Do not handle unchanged masks: */
                    UInt32 uChanged = m_uDarwinKeyModifiers ^ modifierMask;
                    if (!uChanged)
                        break;

                    /* Convert to keycode: */
                    unsigned uKeyCode = ::DarwinModifierMaskToDarwinKeycode(uChanged);

                    /* Do not handle empty and multiple modifier changes: */
                    if (!uKeyCode || uKeyCode == ~0U)
                        break;

                    /* Handle key-event: */
                    if (processKeyEvent(uKeyCode, uChanged & modifierMask))
                    {
                        /* Save the new modifier mask state: */
                        m_uDarwinKeyModifiers = modifierMask;
                        return true;
                    }
                    break;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }

# elif defined(VBOX_WS_WIN)

    /* Make sure it's generic MSG event: */
    if (eventType != "windows_generic_MSG")
        return QLineEdit::nativeEvent(eventType, pMessage, pResult);
    MSG *pEvent = static_cast<MSG*>(pMessage);

    /* Check if some MSG event should be filtered out: */
    // Returning @c true means filtering-out,
    // Returning @c false means passing event to Qt.
    switch (pEvent->message)
    {
        /* Watch for key-events: */
        case WM_KEYDOWN:
        case WM_SYSKEYDOWN:
        case WM_KEYUP:
        case WM_SYSKEYUP:
        {
            /* Parse key-event: */
            int iKeyCode = UINativeHotKey::distinguishModifierVKey((int)pEvent->wParam, (int)pEvent->lParam);
            unsigned iDownScanCode = (pEvent->lParam >> 16) & 0x7F;
            const bool fPressed = !(pEvent->lParam & 0x80000000);
            const bool fExtended = pEvent->lParam & 0x1000000;

            /* If present - why not just assert this? */
            if (m_pAltGrMonitor)
            {
                /* Update AltGR monitor state from key-event: */
                m_pAltGrMonitor->updateStateFromKeyEvent(iDownScanCode, fPressed, fExtended);
                /* And release left Ctrl key early (if required): */
                if (m_pAltGrMonitor->isLeftControlReleaseNeeded())
                {
                    m_pressedKeys.remove(VK_LCONTROL);
                    m_shownKeys.remove(VK_LCONTROL);
                }
                // WORKAROUND:
                // Fake LCtrl release events can also end up in the released
                // key set.  Detect them on the immediately following RAlt up.
                if (!m_pressedKeys.contains(VK_LCONTROL))
                    m_releasedKeys.remove(VK_LCONTROL);
            }

            /* Handle key-event: */
            return processKeyEvent(iKeyCode, (pEvent->message == WM_KEYDOWN || pEvent->message == WM_SYSKEYDOWN));
        }
        default:
            break;
    }

# elif defined(VBOX_WS_X11)

    /* Make sure it's generic XCB event: */
    if (eventType != "xcb_generic_event_t")
        return QLineEdit::nativeEvent(eventType, pMessage, pResult);
    xcb_generic_event_t *pEvent = static_cast<xcb_generic_event_t*>(pMessage);

    /* Check if some XCB event should be filtered out: */
    // Returning @c true means filtering-out,
    // Returning @c false means passing event to Qt.
    switch (pEvent->response_type & ~0x80)
    {
        /* Watch for key-events: */
        case XCB_KEY_PRESS:
        case XCB_KEY_RELEASE:
        {
            /* Parse key-event: */
            xcb_key_press_event_t *pKeyEvent = static_cast<xcb_key_press_event_t*>(pMessage);
            RT_GCC_NO_WARN_DEPRECATED_BEGIN
            const KeySym ks = ::XKeycodeToKeysym(NativeWindowSubsystem::X11GetDisplay(), pKeyEvent->detail, 0);
            RT_GCC_NO_WARN_DEPRECATED_END
            const int iKeySym = static_cast<int>(ks);

            /* Handle key-event: */
            return processKeyEvent(iKeySym, (pEvent->response_type & ~0x80) == XCB_KEY_PRESS);
        }
        default:
            break;
    }

# else

#  warning "port me!"

# endif

    /* Call to base-class: */
    return QLineEdit::nativeEvent(eventType, pMessage, pResult);
}

void UIHostComboEditorPrivate::keyPressEvent(QKeyEvent *pEvent)
{
    /* Ignore most of key presses... */
    switch (pEvent->key())
    {
        case Qt::Key_Enter:
        case Qt::Key_Return:
        case Qt::Key_Tab:
        case Qt::Key_Backtab:
        case Qt::Key_Escape:
            return QLineEdit::keyPressEvent(pEvent);
        case Qt::Key_Up:
        case Qt::Key_Down:
        case Qt::Key_Left:
        case Qt::Key_Right:
            pEvent->ignore();
            return;
        default:
            break;
    }
}

void UIHostComboEditorPrivate::keyReleaseEvent(QKeyEvent *pEvent)
{
    /* Ignore most of key presses... */
    switch (pEvent->key())
    {
        case Qt::Key_Tab:
        case Qt::Key_Backtab:
        case Qt::Key_Escape:
            return QLineEdit::keyReleaseEvent(pEvent);
        case Qt::Key_Up:
        case Qt::Key_Down:
        case Qt::Key_Left:
        case Qt::Key_Right:
            pEvent->ignore();
            return;
        default:
            break;
    }
}

void UIHostComboEditorPrivate::mousePressEvent(QMouseEvent *pEvent)
{
    /* Handle like for usual QWidget: */
    QWidget::mousePressEvent(pEvent);
}

void UIHostComboEditorPrivate::mouseReleaseEvent(QMouseEvent *pEvent)
{
    /* Handle like for usual QWidget: */
    QWidget::mouseReleaseEvent(pEvent);
}

void UIHostComboEditorPrivate::sltReleasePendingKeys()
{
    /* Stop the timer, we process all pending keys at once: */
    m_pReleaseTimer->stop();
    /* Something to do? */
    if (!m_releasedKeys.isEmpty())
    {
        /* Remove every key: */
        QSetIterator<int> iterator(m_releasedKeys);
        while (iterator.hasNext())
        {
            int iKeyCode = iterator.next();
            m_pressedKeys.remove(iKeyCode);
            m_shownKeys.remove(iKeyCode);
        }
        m_releasedKeys.clear();
        if (m_pressedKeys.isEmpty())
            m_fStartNewSequence = true;
        /* Notify data changed: */
        emit sigDataChanged();
    }
    /* Make sure the user see what happens: */
    updateText();
}

bool UIHostComboEditorPrivate::processKeyEvent(int iKeyCode, bool fKeyPress)
{
    /* Check if symbol is valid else pass it to Qt: */
    if (!UINativeHotKey::isValidKey(iKeyCode))
        return false;

    /* Stop the release-pending-keys timer: */
    m_pReleaseTimer->stop();

    /* Key press: */
    if (fKeyPress)
    {
        /* Clear reflected symbols if new sequence started: */
        if (m_fStartNewSequence)
            m_shownKeys.clear();
        /* Make sure any keys pending for releasing are processed: */
        sltReleasePendingKeys();
        /* Check maximum combo size: */
        if (m_shownKeys.size() < UIHostCombo::m_iMaxComboSize)
        {
            /* Remember pressed symbol: */
            m_pressedKeys << iKeyCode;
            m_shownKeys.insert(iKeyCode, UINativeHotKey::toString(iKeyCode));
            /* Remember what we already started a sequence: */
            m_fStartNewSequence = false;
            /* Notify data changed: */
            emit sigDataChanged();
        }
    }
    /* Key release: */
    else
    {
        /* Queue released symbol for processing: */
        m_releasedKeys << iKeyCode;

        /* If all pressed keys are now pending for releasing we should stop further handling.
         * Now we have the status the user want: */
        if (m_pressedKeys == m_releasedKeys)
        {
            m_pressedKeys.clear();
            m_releasedKeys.clear();
            m_fStartNewSequence = true;
        }
        else
            m_pReleaseTimer->start();
    }

    /* Update text: */
    updateText();

    /* Prevent passing to Qt: */
    return true;
}

void UIHostComboEditorPrivate::updateText()
{
    QStringList shownKeyNames(m_shownKeys.values());
    setText(shownKeyNames.isEmpty() ? UIHostComboEditor::tr("None") : shownKeyNames.join(" + "));
}