summaryrefslogtreecommitdiffstats
path: root/vcl/qt5/QtMenu.cxx
blob: 83ca58ad40922f7f39ba2de381301b9f8ba69edc (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <QtMenu.hxx>
#include <QtMenu.moc>

#include <QtFrame.hxx>
#include <QtInstance.hxx>
#include <QtMainWindow.hxx>

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QtWidgets/QActionGroup>
#else
#include <QtGui/QActionGroup>
#endif

#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStyle>

#include <o3tl/safeint.hxx>
#include <vcl/svapp.hxx>
#include <sal/log.hxx>

#include <strings.hrc>
#include <bitmaps.hlst>

#include <vcl/toolkit/floatwin.hxx>
#include <window.h>

// LO SalMenuButtonItem::mnId is sal_uInt16, so we go with -2, as -1 has a special meaning as automatic id
constexpr int CLOSE_BUTTON_ID = -2;
const QString gButtonGroupKey("QtMenu::ButtonGroup");

static inline void lcl_force_menubar_layout_update(QMenuBar& rMenuBar)
{
    // just exists as a function to not comment it everywhere: forces reposition of the
    // corner widget after its layout changes, which will otherwise just happen on resize.
    // it unfortunatly has additional side effects; see QtMenu::GetMenuBarButtonRectPixel.
    rMenuBar.adjustSize();
}

QtMenu::QtMenu(bool bMenuBar)
    : mpVCLMenu(nullptr)
    , mpParentSalMenu(nullptr)
    , mpFrame(nullptr)
    , mbMenuBar(bMenuBar)
    , mpQMenuBar(nullptr)
    , mpQMenu(nullptr)
    , m_pButtonGroup(nullptr)
{
}

bool QtMenu::VisibleMenuBar() { return true; }

void QtMenu::InsertMenuItem(QtMenuItem* pSalMenuItem, unsigned nPos)
{
    sal_uInt16 nId = pSalMenuItem->mnId;
    OUString aText = mpVCLMenu->GetItemText(nId);
    NativeItemText(aText);
    vcl::KeyCode nAccelKey = mpVCLMenu->GetAccelKey(nId);

    pSalMenuItem->mpAction.reset();
    pSalMenuItem->mpMenu.reset();

    if (mbMenuBar)
    {
        // top-level menu
        if (validateQMenuBar())
        {
            QMenu* pQMenu = new QMenu(toQString(aText), nullptr);
            pSalMenuItem->mpMenu.reset(pQMenu);

            if ((nPos != MENU_APPEND)
                && (static_cast<size_t>(nPos) < o3tl::make_unsigned(mpQMenuBar->actions().size())))
            {
                mpQMenuBar->insertMenu(mpQMenuBar->actions()[nPos], pQMenu);
            }
            else
            {
                mpQMenuBar->addMenu(pQMenu);
            }

            // correct parent menu for generated menu
            if (pSalMenuItem->mpSubMenu)
            {
                pSalMenuItem->mpSubMenu->mpQMenu = pQMenu;
            }

            connect(pQMenu, &QMenu::aboutToShow, this,
                    [pSalMenuItem] { slotMenuAboutToShow(pSalMenuItem); });
            connect(pQMenu, &QMenu::aboutToHide, this,
                    [pSalMenuItem] { slotMenuAboutToHide(pSalMenuItem); });
        }
    }
    else
    {
        if (!mpQMenu)
        {
            // no QMenu set, instantiate own one
            mpOwnedQMenu.reset(new QMenu);
            mpQMenu = mpOwnedQMenu.get();
        }

        if (pSalMenuItem->mpSubMenu)
        {
            // submenu
            QMenu* pQMenu = new QMenu(toQString(aText), nullptr);
            pSalMenuItem->mpMenu.reset(pQMenu);

            if ((nPos != MENU_APPEND)
                && (static_cast<size_t>(nPos) < o3tl::make_unsigned(mpQMenu->actions().size())))
            {
                mpQMenu->insertMenu(mpQMenu->actions()[nPos], pQMenu);
            }
            else
            {
                mpQMenu->addMenu(pQMenu);
            }

            // correct parent menu for generated menu
            pSalMenuItem->mpSubMenu->mpQMenu = pQMenu;

            ReinitializeActionGroup(nPos);

            // clear all action groups since menu is recreated
            pSalMenuItem->mpSubMenu->ResetAllActionGroups();

            connect(pQMenu, &QMenu::aboutToShow, this,
                    [pSalMenuItem] { slotMenuAboutToShow(pSalMenuItem); });
            connect(pQMenu, &QMenu::aboutToHide, this,
                    [pSalMenuItem] { slotMenuAboutToHide(pSalMenuItem); });
        }
        else
        {
            if (pSalMenuItem->mnType == MenuItemType::SEPARATOR)
            {
                QAction* pAction = new QAction(nullptr);
                pSalMenuItem->mpAction.reset(pAction);
                pAction->setSeparator(true);

                if ((nPos != MENU_APPEND)
                    && (static_cast<size_t>(nPos) < o3tl::make_unsigned(mpQMenu->actions().size())))
                {
                    mpQMenu->insertAction(mpQMenu->actions()[nPos], pAction);
                }
                else
                {
                    mpQMenu->addAction(pAction);
                }

                ReinitializeActionGroup(nPos);
            }
            else
            {
                // leaf menu
                QAction* pAction = new QAction(toQString(aText), nullptr);
                pSalMenuItem->mpAction.reset(pAction);

                if ((nPos != MENU_APPEND)
                    && (static_cast<size_t>(nPos) < o3tl::make_unsigned(mpQMenu->actions().size())))
                {
                    mpQMenu->insertAction(mpQMenu->actions()[nPos], pAction);
                }
                else
                {
                    mpQMenu->addAction(pAction);
                }

                ReinitializeActionGroup(nPos);

                UpdateActionGroupItem(pSalMenuItem);

                pAction->setShortcut(toQString(nAccelKey.GetName()));

                connect(pAction, &QAction::triggered, this,
                        [pSalMenuItem] { slotMenuTriggered(pSalMenuItem); });
            }
        }
    }

    QAction* pAction = pSalMenuItem->getAction();
    if (pAction)
    {
        pAction->setEnabled(pSalMenuItem->mbEnabled);
        pAction->setVisible(pSalMenuItem->mbVisible);
    }
}

void QtMenu::ReinitializeActionGroup(unsigned nPos)
{
    const unsigned nCount = GetItemCount();

    if (nCount == 0)
    {
        return;
    }

    if (nPos == MENU_APPEND)
    {
        nPos = nCount - 1;
    }
    else if (nPos >= nCount)
    {
        return;
    }

    QtMenuItem* pPrevItem = (nPos > 0) ? GetItemAtPos(nPos - 1) : nullptr;
    QtMenuItem* pCurrentItem = GetItemAtPos(nPos);
    QtMenuItem* pNextItem = (nPos < nCount - 1) ? GetItemAtPos(nPos + 1) : nullptr;

    if (pCurrentItem->mnType == MenuItemType::SEPARATOR)
    {
        pCurrentItem->mpActionGroup.reset();

        // if it's inserted into middle of existing group, split it into two groups:
        // first goes original group, after separator goes new group
        if (pPrevItem && pPrevItem->mpActionGroup && pNextItem && pNextItem->mpActionGroup
            && (pPrevItem->mpActionGroup == pNextItem->mpActionGroup))
        {
            std::shared_ptr<QActionGroup> pFirstActionGroup = pPrevItem->mpActionGroup;
            auto pSecondActionGroup = std::make_shared<QActionGroup>(nullptr);
            pSecondActionGroup->setExclusive(true);

            auto actions = pFirstActionGroup->actions();

            for (unsigned idx = nPos + 1; idx < nCount; ++idx)
            {
                QtMenuItem* pModifiedItem = GetItemAtPos(idx);

                if ((!pModifiedItem) || (!pModifiedItem->mpActionGroup))
                {
                    break;
                }

                pModifiedItem->mpActionGroup = pSecondActionGroup;
                auto action = pModifiedItem->getAction();

                if (actions.contains(action))
                {
                    pFirstActionGroup->removeAction(action);
                    pSecondActionGroup->addAction(action);
                }
            }
        }
    }
    else
    {
        if (!pCurrentItem->mpActionGroup)
        {
            // unless element is inserted between two separators, or a separator and an end of vector, use neighbouring group since it's shared
            if (pPrevItem && pPrevItem->mpActionGroup)
            {
                pCurrentItem->mpActionGroup = pPrevItem->mpActionGroup;
            }
            else if (pNextItem && pNextItem->mpActionGroup)
            {
                pCurrentItem->mpActionGroup = pNextItem->mpActionGroup;
            }
            else
            {
                pCurrentItem->mpActionGroup = std::make_shared<QActionGroup>(nullptr);
                pCurrentItem->mpActionGroup->setExclusive(true);
            }
        }

        // if there's also a different group after this element, merge it
        if (pNextItem && pNextItem->mpActionGroup
            && (pCurrentItem->mpActionGroup != pNextItem->mpActionGroup))
        {
            auto pFirstCheckedAction = pCurrentItem->mpActionGroup->checkedAction();
            auto pSecondCheckedAction = pNextItem->mpActionGroup->checkedAction();
            auto actions = pNextItem->mpActionGroup->actions();

            // first move all actions from second group to first one, and if first group already has checked action,
            // and second group also has a checked action, uncheck action from second group
            for (auto action : actions)
            {
                pNextItem->mpActionGroup->removeAction(action);

                if (pFirstCheckedAction && pSecondCheckedAction && (action == pSecondCheckedAction))
                {
                    action->setChecked(false);
                }

                pCurrentItem->mpActionGroup->addAction(action);
            }

            // now replace all pointers to second group with pointers to first group
            for (unsigned idx = nPos + 1; idx < nCount; ++idx)
            {
                QtMenuItem* pModifiedItem = GetItemAtPos(idx);

                if ((!pModifiedItem) || (!pModifiedItem->mpActionGroup))
                {
                    break;
                }

                pModifiedItem->mpActionGroup = pCurrentItem->mpActionGroup;
            }
        }
    }
}

void QtMenu::ResetAllActionGroups()
{
    for (unsigned nItem = 0; nItem < GetItemCount(); ++nItem)
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nItem);
        pSalMenuItem->mpActionGroup.reset();
    }
}

void QtMenu::UpdateActionGroupItem(const QtMenuItem* pSalMenuItem)
{
    QAction* pAction = pSalMenuItem->getAction();
    if (!pAction)
        return;

    bool bChecked = mpVCLMenu->IsItemChecked(pSalMenuItem->mnId);
    MenuItemBits itemBits = mpVCLMenu->GetItemBits(pSalMenuItem->mnId);

    if (itemBits & MenuItemBits::RADIOCHECK)
    {
        pAction->setCheckable(true);

        if (pSalMenuItem->mpActionGroup)
        {
            pSalMenuItem->mpActionGroup->addAction(pAction);
        }

        pAction->setChecked(bChecked);
    }
    else
    {
        pAction->setActionGroup(nullptr);

        if (itemBits & MenuItemBits::CHECKABLE)
        {
            pAction->setCheckable(true);
            pAction->setChecked(bChecked);
        }
        else
        {
            pAction->setChecked(false);
            pAction->setCheckable(false);
        }
    }
}

void QtMenu::InsertItem(SalMenuItem* pSalMenuItem, unsigned nPos)
{
    SolarMutexGuard aGuard;
    QtMenuItem* pItem = static_cast<QtMenuItem*>(pSalMenuItem);

    if (nPos == MENU_APPEND)
        maItems.push_back(pItem);
    else
        maItems.insert(maItems.begin() + nPos, pItem);

    pItem->mpParentMenu = this;

    InsertMenuItem(pItem, nPos);
}

void QtMenu::RemoveItem(unsigned nPos)
{
    SolarMutexGuard aGuard;

    if (nPos >= maItems.size())
        return;

    QtMenuItem* pItem = maItems[nPos];
    pItem->mpAction.reset();
    pItem->mpMenu.reset();

    maItems.erase(maItems.begin() + nPos);

    // Recalculate action groups if necessary:
    // if separator between two QActionGroups was removed,
    // it may be needed to merge them
    if (nPos > 0)
    {
        ReinitializeActionGroup(nPos - 1);
    }
}

void QtMenu::SetSubMenu(SalMenuItem* pSalMenuItem, SalMenu* pSubMenu, unsigned nPos)
{
    SolarMutexGuard aGuard;
    QtMenuItem* pItem = static_cast<QtMenuItem*>(pSalMenuItem);
    QtMenu* pQSubMenu = static_cast<QtMenu*>(pSubMenu);

    pItem->mpSubMenu = pQSubMenu;
    // at this point the pointer to parent menu may be outdated, update it too
    pItem->mpParentMenu = this;

    if (pQSubMenu != nullptr)
    {
        pQSubMenu->mpParentSalMenu = this;
        pQSubMenu->mpQMenu = pItem->mpMenu.get();
    }

    // if it's not a menu bar item, then convert it to corresponding item if type if necessary.
    // If submenu is present and it's an action, convert it to menu.
    // If submenu is not present and it's a menu, convert it to action.
    // It may be fine to proceed in any case, but by skipping other cases
    // amount of unneeded actions taken should be reduced.
    if (pItem->mpParentMenu->mbMenuBar || (pQSubMenu && pItem->mpMenu)
        || ((!pQSubMenu) && pItem->mpAction))
    {
        return;
    }

    InsertMenuItem(pItem, nPos);
}

void QtMenu::SetFrame(const SalFrame* pFrame)
{
    auto* pSalInst(GetQtInstance());
    assert(pSalInst);
    if (!pSalInst->IsMainThread())
    {
        pSalInst->RunInMainThread([this, pFrame]() { SetFrame(pFrame); });
        return;
    }

    SolarMutexGuard aGuard;
    assert(mbMenuBar);
    mpFrame = const_cast<QtFrame*>(static_cast<const QtFrame*>(pFrame));

    mpFrame->SetMenu(this);

    QtMainWindow* pMainWindow = mpFrame->GetTopLevelWindow();
    if (!pMainWindow)
        return;

    mpQMenuBar = new QMenuBar();
    pMainWindow->setMenuBar(mpQMenuBar);

    QWidget* pWidget = mpQMenuBar->cornerWidget(Qt::TopRightCorner);
    if (pWidget)
    {
        m_pButtonGroup = pWidget->findChild<QButtonGroup*>(gButtonGroupKey);
        assert(m_pButtonGroup);
        connect(m_pButtonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked), this,
                &QtMenu::slotMenuBarButtonClicked);
        QPushButton* pButton = static_cast<QPushButton*>(m_pButtonGroup->button(CLOSE_BUTTON_ID));
        if (pButton)
            connect(pButton, &QPushButton::clicked, this, &QtMenu::slotCloseDocument);
    }
    else
        m_pButtonGroup = nullptr;
    mpQMenu = nullptr;

    DoFullMenuUpdate(mpVCLMenu);
}

void QtMenu::DoFullMenuUpdate(Menu* pMenuBar)
{
    // clear action groups since menu is rebuilt
    ResetAllActionGroups();
    ShowCloseButton(false);

    for (sal_Int32 nItem = 0; nItem < static_cast<sal_Int32>(GetItemCount()); nItem++)
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nItem);
        InsertMenuItem(pSalMenuItem, nItem);
        SetItemImage(nItem, pSalMenuItem, pSalMenuItem->maImage);
        const bool bShowDisabled
            = bool(pMenuBar->GetMenuFlags() & MenuFlags::AlwaysShowDisabledEntries)
              || !bool(pMenuBar->GetMenuFlags() & MenuFlags::HideDisabledEntries);
        const bool bVisible = bShowDisabled || mpVCLMenu->IsItemEnabled(pSalMenuItem->mnId);
        pSalMenuItem->getAction()->setVisible(bVisible);

        if (pSalMenuItem->mpSubMenu != nullptr)
        {
            pMenuBar->HandleMenuActivateEvent(pSalMenuItem->mpSubMenu->GetMenu());
            pSalMenuItem->mpSubMenu->DoFullMenuUpdate(pMenuBar);
            pMenuBar->HandleMenuDeActivateEvent(pSalMenuItem->mpSubMenu->GetMenu());
        }
    }
}

void QtMenu::ShowItem(unsigned nPos, bool bShow)
{
    if (nPos < maItems.size())
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nPos);
        QAction* pAction = pSalMenuItem->getAction();
        if (pAction)
            pAction->setVisible(bShow);
        pSalMenuItem->mbVisible = bShow;
    }
}

void QtMenu::SetItemBits(unsigned nPos, MenuItemBits)
{
    if (nPos < maItems.size())
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nPos);
        UpdateActionGroupItem(pSalMenuItem);
    }
}

void QtMenu::CheckItem(unsigned nPos, bool bChecked)
{
    if (nPos < maItems.size())
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nPos);
        QAction* pAction = pSalMenuItem->getAction();
        if (pAction)
        {
            pAction->setCheckable(true);
            pAction->setChecked(bChecked);
        }
    }
}

void QtMenu::EnableItem(unsigned nPos, bool bEnable)
{
    if (nPos < maItems.size())
    {
        QtMenuItem* pSalMenuItem = GetItemAtPos(nPos);
        QAction* pAction = pSalMenuItem->getAction();
        if (pAction)
            pAction->setEnabled(bEnable);
        pSalMenuItem->mbEnabled = bEnable;
    }
}

void QtMenu::SetItemText(unsigned, SalMenuItem* pItem, const OUString& rText)
{
    QtMenuItem* pSalMenuItem = static_cast<QtMenuItem*>(pItem);
    QAction* pAction = pSalMenuItem->getAction();
    if (pAction)
    {
        OUString aText(rText);
        NativeItemText(aText);
        pAction->setText(toQString(aText));
    }
}

void QtMenu::SetItemImage(unsigned, SalMenuItem* pItem, const Image& rImage)
{
    QtMenuItem* pSalMenuItem = static_cast<QtMenuItem*>(pItem);

    // Save new image to use it in DoFullMenuUpdate
    pSalMenuItem->maImage = rImage;

    QAction* pAction = pSalMenuItem->getAction();
    if (!pAction)
        return;

    pAction->setIcon(QPixmap::fromImage(toQImage(rImage)));
}

void QtMenu::SetAccelerator(unsigned, SalMenuItem* pItem, const vcl::KeyCode&,
                            const OUString& rText)
{
    QtMenuItem* pSalMenuItem = static_cast<QtMenuItem*>(pItem);
    QAction* pAction = pSalMenuItem->getAction();
    if (pAction)
        pAction->setShortcut(QKeySequence(toQString(rText), QKeySequence::PortableText));
}

void QtMenu::GetSystemMenuData(SystemMenuData*) {}

QtMenu* QtMenu::GetTopLevel()
{
    QtMenu* pMenu = this;
    while (pMenu->mpParentSalMenu)
        pMenu = pMenu->mpParentSalMenu;
    return pMenu;
}

bool QtMenu::validateQMenuBar() const
{
    if (!mpQMenuBar)
        return false;
    assert(mpFrame);
    QtMainWindow* pMainWindow = mpFrame->GetTopLevelWindow();
    assert(pMainWindow);
    const bool bValid = mpQMenuBar == pMainWindow->menuBar();
    if (!bValid)
    {
        QtMenu* thisPtr = const_cast<QtMenu*>(this);
        thisPtr->mpQMenuBar = nullptr;
    }
    return bValid;
}

void QtMenu::ShowMenuBar(bool bVisible)
{
    if (!validateQMenuBar())
        return;

    mpQMenuBar->setVisible(bVisible);
    if (bVisible)
        lcl_force_menubar_layout_update(*mpQMenuBar);
}

const QtFrame* QtMenu::GetFrame() const
{
    SolarMutexGuard aGuard;
    const QtMenu* pMenu = this;
    while (pMenu && !pMenu->mpFrame)
        pMenu = pMenu->mpParentSalMenu;
    return pMenu ? pMenu->mpFrame : nullptr;
}

void QtMenu::slotMenuTriggered(QtMenuItem* pQItem)
{
    if (!pQItem)
        return;

    QtMenu* pSalMenu = pQItem->mpParentMenu;
    QtMenu* pTopLevel = pSalMenu->GetTopLevel();

    Menu* pMenu = pSalMenu->GetMenu();
    auto mnId = pQItem->mnId;

    // HACK to allow HandleMenuCommandEvent to "not-set" the checked button
    // LO expects a signal before an item state change, so reset the check item
    if (pQItem->mpAction->isCheckable()
        && (!pQItem->mpActionGroup || pQItem->mpActionGroup->actions().size() <= 1))
        pQItem->mpAction->setChecked(!pQItem->mpAction->isChecked());
    pTopLevel->GetMenu()->HandleMenuCommandEvent(pMenu, mnId);
}

void QtMenu::slotMenuAboutToShow(QtMenuItem* pQItem)
{
    if (pQItem)
    {
        QtMenu* pSalMenu = pQItem->mpSubMenu;
        QtMenu* pTopLevel = pSalMenu->GetTopLevel();

        Menu* pMenu = pSalMenu->GetMenu();

        // following function may update the menu
        pTopLevel->GetMenu()->HandleMenuActivateEvent(pMenu);
    }
}

void QtMenu::slotMenuAboutToHide(QtMenuItem* pQItem)
{
    if (pQItem)
    {
        QtMenu* pSalMenu = pQItem->mpSubMenu;
        QtMenu* pTopLevel = pSalMenu->GetTopLevel();

        Menu* pMenu = pSalMenu->GetMenu();

        pTopLevel->GetMenu()->HandleMenuDeActivateEvent(pMenu);
    }
}

void QtMenu::NativeItemText(OUString& rItemText)
{
    // preserve literal '&'s in menu texts
    rItemText = rItemText.replaceAll("&", "&&");

    rItemText = rItemText.replace('~', '&');
}

void QtMenu::slotCloseDocument()
{
    MenuBar* pVclMenuBar = static_cast<MenuBar*>(mpVCLMenu.get());
    if (pVclMenuBar)
        Application::PostUserEvent(pVclMenuBar->GetCloseButtonClickHdl());
}

void QtMenu::slotMenuBarButtonClicked(QAbstractButton* pButton)
{
    MenuBar* pVclMenuBar = static_cast<MenuBar*>(mpVCLMenu.get());
    if (pVclMenuBar)
    {
        SolarMutexGuard aGuard;
        pVclMenuBar->HandleMenuButtonEvent(m_pButtonGroup->id(pButton));
    }
}

QPushButton* QtMenu::ImplAddMenuBarButton(const QIcon& rIcon, const QString& rToolTip, int nId)
{
    if (!validateQMenuBar())
        return nullptr;

    QWidget* pWidget = mpQMenuBar->cornerWidget(Qt::TopRightCorner);
    QHBoxLayout* pLayout;
    if (!pWidget)
    {
        assert(!m_pButtonGroup);
        pWidget = new QWidget(mpQMenuBar);
        assert(!pWidget->layout());
        pLayout = new QHBoxLayout();
        pLayout->setContentsMargins(QMargins());
        pLayout->setSpacing(0);
        pWidget->setLayout(pLayout);
        m_pButtonGroup = new QButtonGroup(pLayout);
        m_pButtonGroup->setObjectName(gButtonGroupKey);
        m_pButtonGroup->setExclusive(false);
        connect(m_pButtonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked), this,
                &QtMenu::slotMenuBarButtonClicked);
        pWidget->show();
        mpQMenuBar->setCornerWidget(pWidget, Qt::TopRightCorner);
    }
    else
        pLayout = static_cast<QHBoxLayout*>(pWidget->layout());
    assert(m_pButtonGroup);
    assert(pLayout);

    QPushButton* pButton = static_cast<QPushButton*>(m_pButtonGroup->button(nId));
    if (pButton)
        ImplRemoveMenuBarButton(nId);

    pButton = new QPushButton();
    // we don't want the button to increase the QMenuBar height, so a fixed size square it is
    const int nFixedLength
        = mpQMenuBar->height() - 2 * mpQMenuBar->style()->pixelMetric(QStyle::PM_MenuBarVMargin);
    pButton->setFixedSize(nFixedLength, nFixedLength);
    pButton->setIcon(rIcon);
    pButton->setFlat(true);
    pButton->setFocusPolicy(Qt::NoFocus);
    pButton->setToolTip(rToolTip);

    m_pButtonGroup->addButton(pButton, nId);
    int nPos = pLayout->count();
    if (m_pButtonGroup->button(CLOSE_BUTTON_ID))
        nPos--;
    pLayout->insertWidget(nPos, pButton, 0, Qt::AlignCenter);
    // show must happen after adding the button to the layout, otherwise the button is
    // shown, but not correct in the layout, if at all! Some times the layout ignores it.
    pButton->show();

    lcl_force_menubar_layout_update(*mpQMenuBar);

    return pButton;
}

bool QtMenu::AddMenuBarButton(const SalMenuButtonItem& rItem)
{
    if (!validateQMenuBar())
        return false;
    return !!ImplAddMenuBarButton(QIcon(QPixmap::fromImage(toQImage(rItem.maImage))),
                                  toQString(rItem.maToolTipText), rItem.mnId);
}

void QtMenu::ImplRemoveMenuBarButton(int nId)
{
    if (!validateQMenuBar())
        return;

    assert(m_pButtonGroup);
    auto* pButton = m_pButtonGroup->button(nId);
    assert(pButton);
    QWidget* pWidget = mpQMenuBar->cornerWidget(Qt::TopRightCorner);
    assert(pWidget);
    QLayout* pLayout = pWidget->layout();
    m_pButtonGroup->removeButton(pButton);
    pLayout->removeWidget(pButton);
    delete pButton;

    lcl_force_menubar_layout_update(*mpQMenuBar);
}

void QtMenu::RemoveMenuBarButton(sal_uInt16 nId) { ImplRemoveMenuBarButton(nId); }

tools::Rectangle QtMenu::GetMenuBarButtonRectPixel(sal_uInt16 nId, SalFrame* pFrame)
{
#ifdef NDEBUG
    Q_UNUSED(pFrame);
#endif
    if (!validateQMenuBar())
        return tools::Rectangle();

    assert(mpFrame == static_cast<QtFrame*>(pFrame));
    assert(m_pButtonGroup);
    auto* pButton = static_cast<QPushButton*>(m_pButtonGroup->button(nId));
    assert(pButton);

    // unfortunatly, calling lcl_force_menubar_layout_update results in a temporary wrong menubar size,
    // but it's the correct minimal size AFAIK and the layout seems correct, so just adjust the width.
    QPoint aPos = pButton->mapTo(mpFrame->asChild(), QPoint());
    aPos.rx() += (mpFrame->asChild()->width() - mpQMenuBar->width());
    return tools::Rectangle(toPoint(aPos), toSize(pButton->size()));
}

void QtMenu::ShowCloseButton(bool bShow)
{
    if (!validateQMenuBar())
        return;

    if (!bShow && !m_pButtonGroup)
        return;

    QPushButton* pButton = nullptr;
    if (m_pButtonGroup)
        pButton = static_cast<QPushButton*>(m_pButtonGroup->button(CLOSE_BUTTON_ID));
    if (!bShow && !pButton)
        return;

    if (!pButton)
    {
        QIcon aIcon;
        if (QIcon::hasThemeIcon("window-close-symbolic"))
            aIcon = QIcon::fromTheme("window-close-symbolic");
        else
            aIcon = QIcon(
                QPixmap::fromImage(toQImage(Image(StockImage::Yes, SV_RESID_BITMAP_CLOSEDOC))));
        pButton = ImplAddMenuBarButton(aIcon, toQString(VclResId(SV_HELPTEXT_CLOSEDOCUMENT)),
                                       CLOSE_BUTTON_ID);
        connect(pButton, &QPushButton::clicked, this, &QtMenu::slotCloseDocument);
    }

    if (bShow)
        pButton->show();
    else
        pButton->hide();

    lcl_force_menubar_layout_update(*mpQMenuBar);
}

bool QtMenu::ShowNativePopupMenu(FloatingWindow* pWin, const tools::Rectangle& rRect,
                                 FloatWinPopupFlags nFlags)
{
    assert(mpQMenu);
    DoFullMenuUpdate(mpVCLMenu);
    mpQMenu->setTearOffEnabled(bool(nFlags & FloatWinPopupFlags::AllowTearOff));

    const VclPtr<vcl::Window> xParent = pWin->ImplGetWindowImpl()->mpRealParent;
    const QtFrame* pFrame = static_cast<QtFrame*>(xParent->ImplGetFrame());
    assert(pFrame);
    const tools::Rectangle aFloatRect = FloatingWindow::ImplConvertToAbsPos(xParent, rRect);
    const QRect aRect = toQRect(aFloatRect, 1 / pFrame->devicePixelRatioF());
    mpQMenu->exec(aRect.topLeft());

    return true;
}

int QtMenu::GetMenuBarHeight() const
{
    if (!validateQMenuBar() || !mpQMenuBar->isVisible())
        return 0;

    return mpQMenuBar->height();
}

QtMenuItem::QtMenuItem(const SalItemParams* pItemData)
    : mpParentMenu(nullptr)
    , mpSubMenu(nullptr)
    , mnId(pItemData->nId)
    , mnType(pItemData->eType)
    , mbVisible(true)
    , mbEnabled(true)
    , maImage(pItemData->aImage)
{
}

QAction* QtMenuItem::getAction() const
{
    if (mpMenu)
        return mpMenu->menuAction();
    if (mpAction)
        return mpAction.get();
    return nullptr;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */