File: lxqtpanel.cpp

package info (click to toggle)
lxqt-panel 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 15,748 kB
  • sloc: cpp: 27,548; xml: 798; makefile: 19
file content (1795 lines) | stat: -rw-r--r-- 60,069 bytes parent folder | download
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * https://lxqt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */


#include "lxqtpanel.h"
#include "lxqtpanellimits.h"
#include "ilxqtpanelplugin.h"
#include "lxqtpanelapplication.h"
#include "lxqtpanellayout.h"
#include "config/configpaneldialog.h"
#include "popupmenu.h"
#include "plugin.h"
#include "panelpluginsmodel.h"
#include "windownotifier.h"
#include <LXQt/PluginInfo>

#include <QScreen>
#include <QWindow>
#include <QDebug>
#include <QString>
#include <QMenu>
#include <QMessageBox>
#include <QDropEvent>
#include <QPainter>
#include <XdgIcon>
#include <XdgDirs>

#include <KWindowSystem>
#include <KX11Extras>
#include <NETWM>

#include "backends/ilxqtabstractwmiface.h"


#include <LayerShellQt/Window>

// Turn on this to show the time required to load each plugin during startup
// #define DEBUG_PLUGIN_LOADTIME
#ifdef DEBUG_PLUGIN_LOADTIME
#include <QElapsedTimer>
#endif

// Config keys and groups
#define CFG_KEY_SCREENNUM          "desktop"
#define CFG_KEY_POSITION           "position"
#define CFG_KEY_PANELSIZE          "panelSize"
#define CFG_KEY_ICONSIZE           "iconSize"
#define CFG_KEY_LINECNT            "lineCount"
#define CFG_KEY_LENGTH             "width"
#define CFG_KEY_PERCENT            "width-percent"
#define CFG_KEY_ALIGNMENT          "alignment"
#define CFG_KEY_FONTCOLOR          "font-color"
#define CFG_KEY_BACKGROUNDCOLOR    "background-color"
#define CFG_KEY_BACKGROUNDIMAGE    "background-image"
#define CFG_KEY_OPACITY            "opacity"
#define CFG_KEY_RESERVESPACE       "reserve-space"
#define CFG_KEY_PLUGINS            "plugins"
#define CFG_KEY_HIDABLE            "hidable"
#define CFG_KEY_VISIBLE_MARGIN     "visible-margin"
#define CFG_KEY_HIDE_ON_OVERLAP    "hide-on-overlap"
#define CFG_KEY_ANIMATION          "animation-duration"
#define CFG_KEY_SHOW_DELAY         "show-delay"
#define CFG_KEY_LOCKPANEL          "lockPanel"

/************************************************
 Returns the Position by the string.
 String is one of "Top", "Left", "Bottom", "Right", string is not case sensitive.
 If the string is not correct, returns defaultValue.
 ************************************************/
ILXQtPanel::Position LXQtPanel::strToPosition(const QString& str, ILXQtPanel::Position defaultValue)
{
    if (str.toUpper() == QLatin1String("TOP"))    return LXQtPanel::PositionTop;
    if (str.toUpper() == QLatin1String("LEFT"))   return LXQtPanel::PositionLeft;
    if (str.toUpper() == QLatin1String("RIGHT"))  return LXQtPanel::PositionRight;
    if (str.toUpper() == QLatin1String("BOTTOM")) return LXQtPanel::PositionBottom;
    return defaultValue;
}


/************************************************
 Return  string representation of the position
 ************************************************/
QString LXQtPanel::positionToStr(ILXQtPanel::Position position)
{
    switch (position)
    {
    case LXQtPanel::PositionTop:
        return QStringLiteral("Top");
    case LXQtPanel::PositionLeft:
        return QStringLiteral("Left");
    case LXQtPanel::PositionRight:
        return QStringLiteral("Right");
    case LXQtPanel::PositionBottom:
        return QStringLiteral("Bottom");
    }

    return QString();
}


/************************************************

 ************************************************/
LXQtPanel::LXQtPanel(const QString &configGroup, LXQt::Settings *settings, QWidget *parent) :
    QFrame(parent),
    mSettings(settings),
    mConfigGroup(configGroup),
    mPlugins{nullptr},
    mStandaloneWindows{new WindowNotifier},
    mPanelSize(0),
    mIconSize(0),
    mLineCount(0),
    mLength(0),
    mAlignment(AlignmentLeft),
    mPosition(ILXQtPanel::PositionBottom),
    mScreenNum(0), //whatever (avoid conditional on uninitialized value)
    mActualScreenNum(0),
    mHidable(false),
    mVisibleMargin(true),
    mHideOnOverlap(false),
    mHidden(false),
    mAnimationTime(0),
    mReserveSpace(true),
    mAnimation(nullptr),
    mWAnimation(nullptr),
    mLayerWindow(nullptr),
    mLockPanel(false)
{
    //You can find information about the flags and widget attributes in your
    //Qt documentation or at https://doc.qt.io/qt-5/qt.html
    //Qt::FramelessWindowHint = Produces a borderless window. The user cannot
    //move or resize a borderless window via the window system. On X11, ...
    Qt::WindowFlags flags = Qt::FramelessWindowHint;

    // NOTE: by PCMan:
    // In Qt 4, the window is not activated if it has Qt::WA_X11NetWmWindowTypeDock.
    // Since Qt 5, the default behaviour is changed. A window is always activated on mouse click.
    // Please see the source code of Qt5: src/plugins/platforms/xcb/qxcbwindow.cpp.
    // void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
    // This new behaviour caused lxqt bug #161 - Cannot minimize windows from panel 1 when two task managers are open
    // Besides, this breaks minimizing or restoring windows when clicking on the taskbar buttons.
    // To workaround this regression bug, we need to add this window flag here.
    // However, since the panel gets no keyboard focus, this may decrease accessibility since
    // it's not possible to use the panel with keyboards. We need to find a better solution later.
    flags |= Qt::WindowDoesNotAcceptFocus;

    setWindowFlags(flags);
    //Adds _NET_WM_WINDOW_TYPE_DOCK to the window's _NET_WM_WINDOW_TYPE X11 window property. See https://standards.freedesktop.org/wm-spec/ for more details.
    setAttribute(Qt::WA_X11NetWmWindowTypeDock);
    //Enables tooltips for inactive windows.
    setAttribute(Qt::WA_AlwaysShowToolTips);
    //Indicates that the widget should have a translucent background, i.e., any non-opaque regions of the widgets will be translucent because the widget will have an alpha channel. Setting this ...
    setAttribute(Qt::WA_TranslucentBackground);
    //Allows data from drag and drop operations to be dropped onto the widget (see QWidget::setAcceptDrops()).
    setAttribute(Qt::WA_AcceptDrops);

    setWindowTitle(QStringLiteral("LXQt Panel"));
    setObjectName(QStringLiteral("LXQtPanel %1").arg(configGroup));

    //LXQtPanel (inherits QFrame) -> lav (QGridLayout) -> LXQtPanelWidget (QFrame) -> LXQtPanelLayout
    LXQtPanelWidget = new QFrame(this);
    LXQtPanelWidget->setObjectName(QStringLiteral("BackgroundWidget"));
    QGridLayout* lav = new QGridLayout();
    lav->setContentsMargins(0, 0, 0, 0);
    setLayout(lav);
    this->layout()->addWidget(LXQtPanelWidget);

    mLayout = new LXQtPanelLayout(LXQtPanelWidget);
    connect(mLayout, &LXQtPanelLayout::pluginMoved, this, &LXQtPanel::pluginMoved);
    LXQtPanelWidget->setLayout(mLayout);
    mLayout->setLineCount(mLineCount);

    mDelaySave.setSingleShot(true);
    mDelaySave.setInterval(SETTINGS_SAVE_DELAY);
    connect(&mDelaySave, &QTimer::timeout, this, [this] { saveSettings(); } );

    mHideTimer.setSingleShot(true);
    mHideTimer.setInterval(PANEL_HIDE_DELAY);
    connect(&mHideTimer, &QTimer::timeout, this, &LXQtPanel::hidePanelWork);

    mShowDelayTimer.setSingleShot(true);
    mShowDelayTimer.setInterval(PANEL_SHOW_DELAY);
    connect(&mShowDelayTimer, &QTimer::timeout, this, [this] { showPanel(mAnimationTime > 0); });

    // screen updates
    connect(qApp, &QApplication::screenAdded, this, [this] (QScreen* newScreen) {
        connect(newScreen, &QScreen::virtualGeometryChanged, this, &LXQtPanel::ensureVisible);
        connect(newScreen, &QScreen::geometryChanged, this, &LXQtPanel::ensureVisible);
        ensureVisible();
    });
    connect(qApp, &QApplication::screenRemoved, this, [this] (QScreen* oldScreen) {
        disconnect(oldScreen, &QScreen::virtualGeometryChanged, this, &LXQtPanel::ensureVisible);
        disconnect(oldScreen, &QScreen::geometryChanged, this, &LXQtPanel::ensureVisible);
        // wait until the screen is really removed because it may contain the panel
        QTimer::singleShot(0, this, &LXQtPanel::ensureVisible);
    });
    const auto screens = QApplication::screens();
    for(const auto& screen : screens)
    {
        connect(screen, &QScreen::virtualGeometryChanged, this, &LXQtPanel::ensureVisible);
        connect(screen, &QScreen::geometryChanged, this, &LXQtPanel::ensureVisible);
    }

    connect(LXQt::Settings::globalSettings(), &LXQt::GlobalSettings::settingsChanged, this, [this] { update(); } );
    connect(lxqtApp,                          &LXQt::Application::themeChanged,       this, &LXQtPanel::realign);

    connect(mStandaloneWindows.get(), &WindowNotifier::firstShown, this, [this] { showPanel(true); });
    connect(mStandaloneWindows.get(), &WindowNotifier::lastHidden, this, &LXQtPanel::hidePanel);

    readSettings();

    ensureVisible();

    loadPlugins();

    if(qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>())
    {
        // Create backing QWindow for LayerShellQt integration
        create();

        if(!windowHandle())
        {
            qWarning() << "LXQtPanel: could not create QWindow for LayerShellQt integration.";
        }
        else
        {
            // Init Layer Shell (Must be done before showing widget)
            mLayerWindow = LayerShellQt::Window::get(windowHandle());
            mLayerWindow->setLayer(LayerShellQt::Window::LayerTop);

            mLayerWindow->setScope(QStringLiteral("dock"));

            LayerShellQt::Window::Anchors anchors;
            anchors.setFlag(LayerShellQt::Window::AnchorLeft);
            anchors.setFlag(LayerShellQt::Window::AnchorBottom);
            anchors.setFlag(LayerShellQt::Window::AnchorRight);
            mLayerWindow->setAnchors(anchors);

#if (QT_VERSION >= QT_VERSION_CHECK(6,8,0))
            // WARNING: Only the following desktops are known to give the focus to child popups
            // when the panel does not accept focus.
            const QRegularExpression desktops(QStringLiteral("(?i)(kde|kwin|wayfire|hyprland)"));

            if (desktops.match(qEnvironmentVariable("XDG_CURRENT_DESKTOP")).hasMatch())
                mLayerWindow->setKeyboardInteractivity(LayerShellQt::Window::KeyboardInteractivityNone);
            else
#endif
                mLayerWindow->setKeyboardInteractivity(LayerShellQt::Window::KeyboardInteractivityOnDemand);

            mLayerWindow->setCloseOnDismissed(false);

            mLayerWindow->setExclusiveEdge(LayerShellQt::Window::AnchorBottom);
            mLayerWindow->setExclusiveZone(height());
        }
    }

    // NOTE: Some (X11) WMs may need the geometry to be set before QWidget::show().
    setPanelGeometry();

    show();

    // show it the first time, despite setting
    if (mHidable)
    {
        showPanel(false);
        QTimer::singleShot(PANEL_HIDE_FIRST_TIME, this, SLOT(hidePanel()));
    }

    LXQtPanelApplication *a = reinterpret_cast<LXQtPanelApplication*>(qApp);
    auto wmBackend = a->getWMBackend();

    connect(wmBackend, &ILXQtAbstractWMInterface::windowAdded, this, [this] {
        if (mHidable && mHideOnOverlap && !mHidden)
        {
            mShowDelayTimer.stop();
            hidePanel();
        }
    });
    connect(wmBackend, &ILXQtAbstractWMInterface::windowRemoved, this, [this] {
        if (mHidable && mHideOnOverlap && mHidden && !isPanelOverlapped())
            mShowDelayTimer.start();
    });
    connect(wmBackend, &ILXQtAbstractWMInterface::currentWorkspaceChanged, this, [this] {
       if (mHidable && mHideOnOverlap)
       {
            if (!mHidden)
            {
                mShowDelayTimer.stop();
                hidePanel();
            }
            else if (!isPanelOverlapped())
                mShowDelayTimer.start();
            else
                mShowDelayTimer.stop(); // workspace may be changed and restored quickly
       }
    });
    connect(wmBackend, &ILXQtAbstractWMInterface::windowPropertyChanged,
            this, [this] (WId /* id */, int prop)
    {
        if (mHidable && mHideOnOverlap
            // when a window is moved, resized, shaded, or minimized
            && (prop == int(LXQtTaskBarWindowProperty::Geometry)
                || prop == int(LXQtTaskBarWindowProperty::State)
                // on Wayland, workspace change is not seen as geometry change
                || (mLayerWindow && prop == int(LXQtTaskBarWindowProperty::Workspace))))
        {
            if (!mHidden)
            {
                mShowDelayTimer.stop();
                hidePanel();
            }
            else if (!isPanelOverlapped())
                mShowDelayTimer.start();
            else
                mShowDelayTimer.stop(); // geometry or state may be changed and restored quickly
        }
    });
}

/************************************************

 ************************************************/
void LXQtPanel::readSettings()
{
    // Read settings ......................................
    mSettings->beginGroup(mConfigGroup);

    // Let Hidability be the first thing we read
    // so that every call to realign() is without side-effect
    mHidable = mSettings->value(QStringLiteral(CFG_KEY_HIDABLE), mHidable).toBool();
    mHidden = mHidable;

    mVisibleMargin = mSettings->value(QStringLiteral(CFG_KEY_VISIBLE_MARGIN), mVisibleMargin).toBool();

    mHideOnOverlap = mSettings->value(QStringLiteral(CFG_KEY_HIDE_ON_OVERLAP), mHideOnOverlap).toBool();

    mAnimationTime = mSettings->value(QStringLiteral(CFG_KEY_ANIMATION), mAnimationTime).toInt();
    mShowDelayTimer.setInterval(mSettings->value(QStringLiteral(CFG_KEY_SHOW_DELAY), mShowDelayTimer.interval()).toInt());

    // By default we are using size & count from theme.
    setPanelSize(mSettings->value(QStringLiteral(CFG_KEY_PANELSIZE), PANEL_DEFAULT_SIZE).toInt(), false);
    setIconSize(mSettings->value(QStringLiteral(CFG_KEY_ICONSIZE), PANEL_DEFAULT_ICON_SIZE).toInt(), false);
    setLineCount(mSettings->value(QStringLiteral(CFG_KEY_LINECNT), PANEL_DEFAULT_LINE_COUNT).toInt(), false);

    setLength(mSettings->value(QStringLiteral(CFG_KEY_LENGTH), 100).toInt(),
              mSettings->value(QStringLiteral(CFG_KEY_PERCENT), true).toBool(),
              false);

    mScreenNum = mSettings->value(QStringLiteral(CFG_KEY_SCREENNUM), 0).toInt();
    setPosition(mScreenNum,
                strToPosition(mSettings->value(QStringLiteral(CFG_KEY_POSITION)).toString(), PositionBottom),
                false);

    setAlignment(Alignment(mSettings->value(QStringLiteral(CFG_KEY_ALIGNMENT), mAlignment).toInt()), false);

    QColor color = mSettings->value(QStringLiteral(CFG_KEY_FONTCOLOR), QString()).value<QColor>();
    if (color.isValid())
        setFontColor(color, true);

    setOpacity(mSettings->value(QStringLiteral(CFG_KEY_OPACITY), 100).toInt(), true);
    mReserveSpace = mSettings->value(QStringLiteral(CFG_KEY_RESERVESPACE), true).toBool();
    color = mSettings->value(QStringLiteral(CFG_KEY_BACKGROUNDCOLOR), QString()).value<QColor>();
    if (color.isValid())
        setBackgroundColor(color, true);

    QString image = mSettings->value(QStringLiteral(CFG_KEY_BACKGROUNDIMAGE), QString()).toString();
    if (!image.isEmpty())
        setBackgroundImage(image, false);

    mLockPanel = mSettings->value(QStringLiteral(CFG_KEY_LOCKPANEL), false).toBool();

    mSettings->endGroup();
}


/************************************************

 ************************************************/
void LXQtPanel::saveSettings(bool later)
{
    mDelaySave.stop();
    if (later)
    {
        mDelaySave.start();
        return;
    }

    mSettings->beginGroup(mConfigGroup);

    //Note: save/load of plugin names is completely handled by mPlugins object
    //mSettings->setValue(CFG_KEY_PLUGINS, mPlugins->pluginNames());

    mSettings->setValue(QStringLiteral(CFG_KEY_PANELSIZE), mPanelSize);
    mSettings->setValue(QStringLiteral(CFG_KEY_ICONSIZE), mIconSize);
    mSettings->setValue(QStringLiteral(CFG_KEY_LINECNT), mLineCount);

    mSettings->setValue(QStringLiteral(CFG_KEY_LENGTH), mLength);
    mSettings->setValue(QStringLiteral(CFG_KEY_PERCENT), mLengthInPercents);

    mSettings->setValue(QStringLiteral(CFG_KEY_SCREENNUM), mScreenNum);
    mSettings->setValue(QStringLiteral(CFG_KEY_POSITION), positionToStr(mPosition));

    mSettings->setValue(QStringLiteral(CFG_KEY_ALIGNMENT), mAlignment);

    mSettings->setValue(QStringLiteral(CFG_KEY_FONTCOLOR), mFontColor.isValid() ? mFontColor : QColor());
    mSettings->setValue(QStringLiteral(CFG_KEY_BACKGROUNDCOLOR), mBackgroundColor.isValid() ? mBackgroundColor : QColor());
    mSettings->setValue(QStringLiteral(CFG_KEY_BACKGROUNDIMAGE), QFileInfo::exists(mBackgroundImage) ? mBackgroundImage : QString());
    mSettings->setValue(QStringLiteral(CFG_KEY_OPACITY), mOpacity);
    mSettings->setValue(QStringLiteral(CFG_KEY_RESERVESPACE), mReserveSpace);

    mSettings->setValue(QStringLiteral(CFG_KEY_HIDABLE), mHidable);
    mSettings->setValue(QStringLiteral(CFG_KEY_VISIBLE_MARGIN), mVisibleMargin);
    mSettings->setValue(QStringLiteral(CFG_KEY_HIDE_ON_OVERLAP), mHideOnOverlap);
    mSettings->setValue(QStringLiteral(CFG_KEY_ANIMATION), mAnimationTime);
    mSettings->setValue(QStringLiteral(CFG_KEY_SHOW_DELAY), mShowDelayTimer.interval());

    mSettings->setValue(QStringLiteral(CFG_KEY_LOCKPANEL), mLockPanel);

    mSettings->endGroup();
}


/************************************************

 ************************************************/
void LXQtPanel::ensureVisible()
{
    if (!canPlacedOn(mScreenNum, mPosition))
        setPosition(findAvailableScreen(mPosition), mPosition, false);
    else
        mActualScreenNum = mScreenNum;

    // the screen size might be changed
    realign();
}


/************************************************

 ************************************************/
LXQtPanel::~LXQtPanel()
{
    mLayout->setEnabled(false);
    delete mAnimation;
    delete mWAnimation;
    delete mConfigDialog.data();
    // do not save settings because of "user deleted panel" functionality saveSettings();
}


/************************************************

 ************************************************/
void LXQtPanel::show()
{
    QWidget::show();
    if(qGuiApp->nativeInterface<QNativeInterface::QX11Application>()) //TODO: cache in bool isPlatformX11
        KX11Extras::setOnDesktop(effectiveWinId(), NET::OnAllDesktops);
}


/************************************************

 ************************************************/
QStringList pluginDesktopDirs()
{
    QStringList dirs;
    dirs << QString::fromLocal8Bit(qgetenv("LXQT_PANEL_PLUGINS_DIR")).split(QLatin1Char(':'), Qt::SkipEmptyParts);
    dirs << QStringLiteral("%1/%2").arg(XdgDirs::dataHome(), QStringLiteral("/lxqt/lxqt-panel"));
    dirs << QStringLiteral(PLUGIN_DESKTOPS_DIR);
    return dirs;
}


/************************************************

 ************************************************/
void LXQtPanel::loadPlugins()
{
    QString names_key(mConfigGroup);
    names_key += QLatin1Char('/');
    names_key += QLatin1String(CFG_KEY_PLUGINS);
    mPlugins.reset(new PanelPluginsModel(this, names_key, pluginDesktopDirs()));

    connect(mPlugins.get(), &PanelPluginsModel::pluginAdded, mLayout, &LXQtPanelLayout::addPlugin);
    connect(mPlugins.get(), &PanelPluginsModel::pluginMovedUp, mLayout, &LXQtPanelLayout::moveUpPlugin);
    //reemit signals
    connect(mPlugins.get(), &PanelPluginsModel::pluginAdded, this, &LXQtPanel::pluginAdded);
    connect(mPlugins.get(), &PanelPluginsModel::pluginRemoved, this, &LXQtPanel::pluginRemoved);

    const auto plugins = mPlugins->plugins();
    for (auto const & plugin : plugins)
    {
        mLayout->addPlugin(plugin);
        connect(plugin, &Plugin::dragLeft, this, [this] {
            mShowDelayTimer.stop();
            hidePanel();
        });
    }
}

/************************************************

 ************************************************/
int LXQtPanel::getReserveDimension()
{
    return mHidable ? PANEL_HIDE_SIZE : qMax(PANEL_MINIMUM_SIZE, mPanelSize);
}

QMargins LXQtPanel::layerWindowMargins()
{
    QMargins margins;
    if (!mHidden)
        return margins;
    int offset = PANEL_HIDE_SIZE - qMax(PANEL_MINIMUM_SIZE, mPanelSize); // negative
    if (isHorizontal())
    {
        if (mPosition == ILXQtPanel::PositionTop)
            margins = QMargins(0, offset, 0, 0);
        else
            margins = QMargins(0, 0, 0, offset);
    }
    else
    {
        if (mPosition == ILXQtPanel::PositionLeft)
            margins = QMargins(offset, 0, 0, 0);
        else
            margins = QMargins(0, 0, offset, 0);
    }
    return margins;
}

void LXQtPanel::setPanelGeometry(bool animate)
{
    const auto screens = QApplication::screens();
    if (mActualScreenNum >= screens.size())
        return;
    const QRect currentScreen = screens.at(mActualScreenNum)->geometry();

    QRect rect;
    LayerShellQt::Window::Anchors anchors;

    if (isHorizontal())
    {
        // Horiz panel ***************************
        rect.setHeight(qMax(PANEL_MINIMUM_SIZE, mPanelSize));
        if (mLengthInPercents)
            rect.setWidth(currentScreen.width() * mLength / 100.0);
        else
        {
            if (mLength <= 0)
                rect.setWidth(currentScreen.width() + mLength);
            else
                rect.setWidth(mLength);
        }

        rect.setWidth(qMax(rect.size().width(), mLayout->minimumSize().width()));

        // Horiz ......................
        switch (mAlignment)
        {
        case LXQtPanel::AlignmentLeft:
            anchors.setFlag(LayerShellQt::Window::AnchorLeft);
            rect.moveLeft(currentScreen.left());
            break;

        case LXQtPanel::AlignmentCenter:
            rect.moveCenter(currentScreen.center());
            break;

        case LXQtPanel::AlignmentRight:
            anchors.setFlag(LayerShellQt::Window::AnchorRight);
            rect.moveRight(currentScreen.right());
            break;
        }

        if(lengthInPercents() && mLength == 100)
        {
            //Fill all available width
            anchors.setFlag(LayerShellQt::Window::AnchorLeft);
            anchors.setFlag(LayerShellQt::Window::AnchorRight);
        }

        // Vert .......................
        if (mPosition == ILXQtPanel::PositionTop)
        {
            anchors.setFlag(LayerShellQt::Window::AnchorTop);

            if (mHidden)
                rect.moveBottom(currentScreen.top() + PANEL_HIDE_SIZE - 1);
            else
                rect.moveTop(currentScreen.top());
        }
        else
        {
            anchors.setFlag(LayerShellQt::Window::AnchorBottom);

            if (mHidden)
                rect.moveTop(currentScreen.bottom() - PANEL_HIDE_SIZE + 1);
            else
                rect.moveBottom(currentScreen.bottom());
        }
    }
    else
    {
        // Vert panel ***************************
        rect.setWidth(qMax(PANEL_MINIMUM_SIZE, mPanelSize));
        if (mLengthInPercents)
            rect.setHeight(currentScreen.height() * mLength / 100.0);
        else
        {
            if (mLength <= 0)
                rect.setHeight(currentScreen.height() + mLength);
            else
                rect.setHeight(mLength);
        }

        rect.setHeight(qMax(rect.size().height(), mLayout->minimumSize().height()));

        // Vert .......................
        switch (mAlignment)
        {
        case LXQtPanel::AlignmentLeft:
            anchors.setFlag(LayerShellQt::Window::AnchorTop);
            rect.moveTop(currentScreen.top());
            break;

        case LXQtPanel::AlignmentCenter:
            rect.moveCenter(currentScreen.center());
            break;

        case LXQtPanel::AlignmentRight:
            anchors.setFlag(LayerShellQt::Window::AnchorBottom);
            rect.moveBottom(currentScreen.bottom());
            break;
        }

        if(lengthInPercents() && mLength == 100)
        {
            //Fill all available width
            anchors.setFlag(LayerShellQt::Window::AnchorTop);
            anchors.setFlag(LayerShellQt::Window::AnchorBottom);
        }

        // Horiz ......................
        if (mPosition == ILXQtPanel::PositionLeft)
        {
            anchors.setFlag(LayerShellQt::Window::AnchorLeft);

            if (mHidden)
                rect.moveRight(currentScreen.left() + PANEL_HIDE_SIZE - 1);
            else
                rect.moveLeft(currentScreen.left());
        }
        else
        {
            anchors.setFlag(LayerShellQt::Window::AnchorRight);

            if (mHidden)
                rect.moveLeft(currentScreen.right() - PANEL_HIDE_SIZE + 1);
            else
                rect.moveRight(currentScreen.right());
        }
    }

    if (!mHidden || !mGeometry.isValid()) mGeometry = rect;
    if (mLayerWindow)
    {
        // NOTE: On Wayland, QVariantAnimation is used to set appropriate negative margins.
        auto screen = screens.at(mActualScreenNum);
        if (screen != windowHandle()->screen())
        {
            // WARNING: An already visible window is not shown on a new screen under Wayland.
            if (isVisible())
            {
                hide();
                QTimer::singleShot(0, this, &QWidget::show);
            }
            windowHandle()->setScreen(screen);
        }
        mLayerWindow->setAnchors(anchors);
        setFixedSize(rect.size());
        if (animate)
        {
            if (mWAnimation == nullptr)
            {
                mWAnimation = new QVariantAnimation(this);
                mWAnimation->setEasingCurve(QEasingCurve::Linear);
                mWAnimation->setStartValue(static_cast<qreal>(0));
                mWAnimation->setEndValue(static_cast<qreal>(1));
                connect(mWAnimation, &QVariantAnimation::finished, this, [this] {
                    if (mHidden)
                    {
                        setMargins();
                        // "setWindowOpacity()" does not work on Wayland
                        if (!mVisibleMargin)
                            LXQtPanelWidget->setVisible(false);
                    }
                });
                connect(mWAnimation, &QVariantAnimation::valueChanged, this,
                        [this] (const QVariant &value) {
                    QMargins margins = layerWindowMargins();
                    QMarginsF m((mWAnimation->endValue().toReal() - value.toReal())
                                * mLayerWindow->margins().toMarginsF()
                                + value.toReal() * margins.toMarginsF());
                    mLayerWindow->setMargins(m.toMargins());
                    windowHandle()->requestUpdate();
                });
            }
            mWAnimation->setDuration(mAnimationTime);
            if (!mHidden)
            {
                setMargins();
                if (!mVisibleMargin)
                    LXQtPanelWidget->setVisible(true);
            }
            mWAnimation->start();
        }
        else
        {
            if (!mVisibleMargin)
                LXQtPanelWidget->setVisible(!mHidden);
            setMargins();
            mLayerWindow->setMargins(layerWindowMargins());
            windowHandle()->requestUpdate();
        }
    }
    else if (rect != geometry())
    {
        setFixedSize(rect.size());
        if (animate)
        {
            if (mAnimation == nullptr)
            {
                mAnimation = new QPropertyAnimation(this, "geometry");
                mAnimation->setEasingCurve(QEasingCurve::Linear);
                //Note: for hiding, the margins are set after animation is finished
                connect(mAnimation, &QAbstractAnimation::finished, this, [this] { if (mHidden) setMargins(); });
            }
            mAnimation->setDuration(mAnimationTime);
            mAnimation->setStartValue(geometry());
            mAnimation->setEndValue(rect);
            //Note: for showing-up, the margins are removed instantly
            if (!mHidden)
                setMargins();
            mAnimation->start();
        }
        else
        {
            setMargins();
            setGeometry(rect);
        }
    }
}

void LXQtPanel::setMargins()
{
    if (mHidden)
    {
        if (isHorizontal())
        {
            if (mPosition == ILXQtPanel::PositionTop)
                mLayout->setContentsMargins(0, 0, 0, PANEL_HIDE_SIZE);
            else
                mLayout->setContentsMargins(0, PANEL_HIDE_SIZE, 0, 0);
        }
        else
        {
            if (mPosition == ILXQtPanel::PositionLeft)
                mLayout->setContentsMargins(0, 0, PANEL_HIDE_SIZE, 0);
            else
                mLayout->setContentsMargins(PANEL_HIDE_SIZE, 0, 0, 0);
        }
        if (!mVisibleMargin)
            setWindowOpacity(0.0);
    }
    else {
        mLayout->setContentsMargins(0, 0, 0, 0);
        if (!mVisibleMargin)
            setWindowOpacity(1.0);
    }
}

void LXQtPanel::realign()
{
    if (!isVisible())
        return;
#if 0
    qDebug() << "** Realign *********************";
    qDebug() << "PanelSize:   " << mPanelSize;
    qDebug() << "IconSize:      " << mIconSize;
    qDebug() << "LineCount:     " << mLineCount;
    qDebug() << "Length:        " << mLength << (mLengthInPercents ? "%" : "px");
    qDebug() << "Alignment:     " << (mAlignment == 0 ? "center" : (mAlignment < 0 ? "left" : "right"));
    qDebug() << "Position:      " << positionToStr(mPosition) << "on" << mScreenNum;
    qDebug() << "Plugins count: " << mPlugins.count();
#endif

    setPanelGeometry();

    // Reserve our space on the screen ..........
    // It's possible that our geometry is not changed, but screen resolution is changed,
    // so resetting WM_STRUT is still needed. To make it simple, we always do it.
    updateWmStrut();
}


// Update the _NET_WM_PARTIAL_STRUT and _NET_WM_STRUT properties for the window
void LXQtPanel::updateWmStrut()
{
    WId wid = effectiveWinId();
    if(wid == 0 || !isVisible())
        return;

    if(qGuiApp->nativeInterface<QNativeInterface::QX11Application>())
    {
        if (mReserveSpace && QApplication::primaryScreen())
        {
            const QRect wholeScreen = QApplication::primaryScreen()->virtualGeometry();
            const QRect rect = geometry();
            // NOTE: https://standards.freedesktop.org/wm-spec/wm-spec-latest.html
            // Quote from the EWMH spec: " Note that the strut is relative to the screen edge, and not the edge of the xinerama monitor."
            // So, we use the geometry of the whole screen to calculate the strut rather than using the geometry of individual monitors.
            // Though the spec only mention Xinerama and did not mention XRandR, the rule should still be applied.
            // At least openbox is implemented like this.
            switch (mPosition)
            {
            case LXQtPanel::PositionTop:
                KX11Extras::setExtendedStrut(wid,
                                             /* Left   */  0, 0, 0,
                                             /* Right  */  0, 0, 0,
                                             /* Top    */  rect.top() + getReserveDimension(), rect.left(), rect.right(),
                                             /* Bottom */  0, 0, 0
                                             );
                break;

            case LXQtPanel::PositionBottom:
                KX11Extras::setExtendedStrut(wid,
                                             /* Left   */  0, 0, 0,
                                             /* Right  */  0, 0, 0,
                                             /* Top    */  0, 0, 0,
                                             /* Bottom */  wholeScreen.bottom() - rect.bottom() + getReserveDimension(), rect.left(), rect.right()
                                             );
                break;

            case LXQtPanel::PositionLeft:
                KX11Extras::setExtendedStrut(wid,
                                             /* Left   */  rect.left() + getReserveDimension(), rect.top(), rect.bottom(),
                                             /* Right  */  0, 0, 0,
                                             /* Top    */  0, 0, 0,
                                             /* Bottom */  0, 0, 0
                                             );

                break;

            case LXQtPanel::PositionRight:
                KX11Extras::setExtendedStrut(wid,
                                             /* Left   */  0, 0, 0,
                                             /* Right  */  wholeScreen.right() - rect.right() + getReserveDimension(), rect.top(), rect.bottom(),
                                             /* Top    */  0, 0, 0,
                                             /* Bottom */  0, 0, 0
                                             );
                break;
            }
        } else
        {
            KX11Extras::setExtendedStrut(wid,
                                         /* Left   */  0, 0, 0,
                                         /* Right  */  0, 0, 0,
                                         /* Top    */  0, 0, 0,
                                         /* Bottom */  0, 0, 0
                                         );
        }
    }
    else if(mLayerWindow && qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>())
    {
        if (mReserveSpace
            // NOTE: For some reason, no space is reserved with a negative layer margin.
            // However, there is no reason to reserve space for a hiding panel on Wayland.
            && !mHidable)
        {
            LayerShellQt::Window::Anchor edge = LayerShellQt::Window::AnchorBottom;

            switch (mPosition)
            {
            case LXQtPanel::PositionTop:
                edge = LayerShellQt::Window::AnchorTop;
                break;

            case LXQtPanel::PositionBottom:
                edge = LayerShellQt::Window::AnchorBottom;
                break;

            case LXQtPanel::PositionLeft:
                edge = LayerShellQt::Window::AnchorLeft;
                break;

            case LXQtPanel::PositionRight:
                edge = LayerShellQt::Window::AnchorRight;
                break;
            }

            mLayerWindow->setExclusiveEdge(edge);
            mLayerWindow->setExclusiveZone(getReserveDimension());
        }
        else
        {
            mLayerWindow->setExclusiveEdge(LayerShellQt::Window::AnchorNone);
            mLayerWindow->setExclusiveZone(0);
        }

        // Make LayerShellQt apply changes immediatly
        windowHandle()->requestUpdate();
    }
}


/************************************************
  This function checks if the panel can be placed on
  the display @screenNum at @position.
  NOTE: The panel can be placed only at screen edges
  but no part of it should be between two screens.
 ************************************************/
bool LXQtPanel::canPlacedOn(int screenNum, LXQtPanel::Position position)
{
    const auto screens = QApplication::screens();
    if (screens.size() > screenNum)
    {
        const QRect screenGeometry = screens.at(screenNum)->geometry();
        switch (position)
        {
        case LXQtPanel::PositionTop:
            for (const auto& screen : screens)
            {
                if (screen->geometry().top() < screenGeometry.top())
                {
                    QRect r = screenGeometry.adjusted(0, screen->geometry().top() - screenGeometry.top(), 0, 0);
                    if (screen->geometry().intersects(r))
                        return false;
                }
            }
            return true;

        case LXQtPanel::PositionBottom:
            for (const auto& screen : screens)
            {
                if (screen->geometry().bottom() > screenGeometry.bottom())
                {
                    QRect r = screenGeometry.adjusted(0, 0, 0, screen->geometry().bottom() - screenGeometry.bottom());
                    if (screen->geometry().intersects(r))
                        return false;
                }
            }
            return true;

        case LXQtPanel::PositionLeft:
            for (const auto& screen : screens)
            {
                if (screen->geometry().left() < screenGeometry.left())
                {
                    QRect r = screenGeometry.adjusted(screen->geometry().left() - screenGeometry.left(), 0, 0, 0);
                    if (screen->geometry().intersects(r))
                        return false;
                }
            }
            return true;

        case LXQtPanel::PositionRight:
            for (const auto& screen : screens)
            {
                if (screen->geometry().right() > screenGeometry.right())
                {
                    QRect r = screenGeometry.adjusted(0, 0, screen->geometry().right() - screenGeometry.right(), 0);
                    if (screen->geometry().intersects(r))
                        return false;
                }
            }
            return true;
        }
    }

    return false;
}


/************************************************

 ************************************************/
int LXQtPanel::findAvailableScreen(LXQtPanel::Position position)
{
    int current = mScreenNum;

    for (int i = current; i < QApplication::screens().size(); ++i)
        if (canPlacedOn(i, position))
            return i;

    for (int i = 0; i < current; ++i)
        if (canPlacedOn(i, position))
            return i;

    return 0;
}


/************************************************

 ************************************************/
void LXQtPanel::showConfigDialog()
{
    if (mConfigDialog.isNull())
        mConfigDialog = new ConfigPanelDialog(this, nullptr /*make it top level window*/);

    mConfigDialog->showConfigPlacementPage();
    mStandaloneWindows->observeWindow(mConfigDialog.data());
    mConfigDialog->show();
    mConfigDialog->raise();
    mConfigDialog->activateWindow();
    WId wid = mConfigDialog->windowHandle()->winId();

    KX11Extras::activateWindow(wid);
    KX11Extras::setOnDesktop(wid, KX11Extras::currentDesktop());
}


/************************************************

 ************************************************/
void LXQtPanel::showAddPluginDialog()
{
    if (mConfigDialog.isNull())
        mConfigDialog = new ConfigPanelDialog(this, nullptr /*make it top level window*/);

    mConfigDialog->showConfigPluginsPage();
    mStandaloneWindows->observeWindow(mConfigDialog.data());
    mConfigDialog->show();
    mConfigDialog->raise();
    mConfigDialog->activateWindow();
    WId wid = mConfigDialog->windowHandle()->winId();

    KX11Extras::activateWindow(wid);
    KX11Extras::setOnDesktop(wid, KX11Extras::currentDesktop());
}


/************************************************

 ************************************************/
void LXQtPanel::updateStyleSheet()
{
    // NOTE: This is a workaround for Qt >= 5.13, which might not completely
    // update the style sheet (especially positioned backgrounds of plugins
    // with NeedsHandle="true") if it is not reset first.
    setStyleSheet(QString());

    QStringList sheet;
    sheet << QStringLiteral("Plugin > QAbstractButton, LXQtTray { qproperty-iconSize: %1px %1px; }").arg(mIconSize);
    sheet << QStringLiteral("Plugin > * > QAbstractButton, TrayIcon { qproperty-iconSize: %1px %1px; }").arg(mIconSize);

    if (mFontColor.isValid())
        sheet << QString(QStringLiteral("Plugin * { color: ") + mFontColor.name() + QStringLiteral("; }"));

    if (mBackgroundColor.isValid())
    {
        QString color = QStringLiteral("%1, %2, %3, %4")
            .arg(mBackgroundColor.red())
            .arg(mBackgroundColor.green())
            .arg(mBackgroundColor.blue())
            .arg((float) mOpacity / 100);
        sheet << QString(QStringLiteral("LXQtPanel #BackgroundWidget { background-color: rgba(") + color + QStringLiteral("); }"));
    }

    if (QFileInfo::exists(mBackgroundImage))
        sheet << QString(QStringLiteral("LXQtPanel #BackgroundWidget { background-image: url('") + mBackgroundImage + QStringLiteral("');}"));

    setStyleSheet(sheet.join(QStringLiteral("\n")));
}



/************************************************

 ************************************************/
void LXQtPanel::setPanelSize(int value, bool save)
{
    if (mPanelSize != value)
    {
        mPanelSize = value;
        realign();

        if (save)
            saveSettings(true);
    }
}



/************************************************

 ************************************************/
void LXQtPanel::setIconSize(int value, bool save)
{
    if (mIconSize != value)
    {
        mIconSize = value;
        updateStyleSheet();
        mLayout->setLineSize(mIconSize);

        if (save)
            saveSettings(true);

        realign();
    }
}


/************************************************

 ************************************************/
void LXQtPanel::setLineCount(int value, bool save)
{
    if (mLineCount != value)
    {
        mLineCount = value;
        mLayout->setEnabled(false);
        mLayout->setLineCount(mLineCount);
        mLayout->setEnabled(true);

        if (save)
            saveSettings(true);

        realign();
    }
}


/************************************************

 ************************************************/
void LXQtPanel::setLength(int length, bool inPercents, bool save)
{
    if (mLength == length &&
            mLengthInPercents == inPercents)
        return;

    mLength = length;
    mLengthInPercents = inPercents;

    if (save)
        saveSettings(true);

    realign();
}


/************************************************

 ************************************************/
void LXQtPanel::setPosition(int screen, ILXQtPanel::Position position, bool save)
{
    if (mScreenNum == screen &&
            mPosition == position)
        return;

    mActualScreenNum = screen;
    mPosition = position;
    mLayout->setPosition(mPosition);

    if (save)
    {
        mScreenNum = screen;
        saveSettings(true);
    }

    // Qt 5 adds a new class QScreen and add API for setting the screen of a QWindow.
    // so we had better use it. However, without this, our program should still work
    // as long as XRandR is used. Since XRandR combined all screens into a large virtual desktop
    // every screen and their virtual siblings are actually on the same virtual desktop.
    // So things still work if we don't set the screen correctly, but this is not the case
    // for other backends, such as the upcoming wayland support. Hence it's better to set it.
    if(windowHandle())
    {
        // QScreen* newScreen = qApp->screens().at(screen);
        // QScreen* oldScreen = windowHandle()->screen();
        // const bool shouldRecreate = windowHandle()->handle() && !(oldScreen && oldScreen->virtualSiblings().contains(newScreen));
        // Q_ASSERT(shouldRecreate == false);

        // NOTE: When you move a window to another screen, Qt 5 might recreate the window as needed
        // But luckily, this never happen in XRandR, so Qt bug #40681 is not triggered here.
        // (The only exception is when the old screen is destroyed, Qt always re-create the window and
        // this corner case triggers #40681.)
        // When using other kind of multihead settings, such as Xinerama, this might be different and
        // unless Qt developers can fix their bug, we have no way to workaround that.
        if (mLayerWindow)
        {
            // WARNING: An already visible window is not shown on a new screen under Wayland.
            if (isVisible())
            {
                hide();
                QTimer::singleShot(0, this, &QWidget::show);
            }
        }
        windowHandle()->setScreen(qApp->screens().at(screen));
    }

    realign();
}

/************************************************
 *
 ************************************************/
void LXQtPanel::setAlignment(Alignment value, bool save)
{
    if (mAlignment == value)
        return;

    mAlignment = value;

    if (save)
        saveSettings(true);

    realign();
}

/************************************************
 *
 ************************************************/
void LXQtPanel::setFontColor(QColor color, bool save)
{
    mFontColor = color;
    updateStyleSheet();

    if (save)
        saveSettings(true);
}

/************************************************

 ************************************************/
void LXQtPanel::setBackgroundColor(QColor color, bool save)
{
    mBackgroundColor = color;
    updateStyleSheet();

    if (save)
        saveSettings(true);
}

/************************************************

 ************************************************/
void LXQtPanel::setBackgroundImage(QString path, bool save)
{
    mBackgroundImage = path;
    updateStyleSheet();

    if (save)
        saveSettings(true);
}


/************************************************
 *
 ************************************************/
void LXQtPanel::setOpacity(int opacity, bool save)
{
    mOpacity = opacity;
    updateStyleSheet();

    if (save)
        saveSettings(true);
}


/************************************************
 *
 ************************************************/
void LXQtPanel::setReserveSpace(bool reserveSpace, bool save)
{
    if (mReserveSpace == reserveSpace)
        return;

    mReserveSpace = reserveSpace;

    if (save)
        saveSettings(true);

    updateWmStrut();
}


/************************************************

 ************************************************/
QRect LXQtPanel::globalGeometry() const
{
    // panel is the the top-most widget/window, no calculation needed
    return geometry();
}


/************************************************

 ************************************************/
bool LXQtPanel::event(QEvent *event)
{
    switch (event->type())
    {
    case QEvent::ContextMenu:
        showPopupMenu(static_cast<QContextMenuEvent *>(event)->globalPos());
        break;

    case QEvent::LayoutRequest:
        emit realigned();
        break;

    case QEvent::WinIdChange:
    {
        if(qGuiApp->nativeInterface<QNativeInterface::QX11Application>())
        {
            // qDebug() << "WinIdChange" << hex << effectiveWinId();
            if(effectiveWinId() == 0)
                break;

            // Sometimes Qt needs to re-create the underlying window of the widget and
            // the winId() may be changed at runtime. So we need to reset all X11 properties
            // when this happens.
            qDebug() << "WinIdChange" << Qt::hex << effectiveWinId() << "handle" << windowHandle() << windowHandle()->screen();

            // Qt::WA_X11NetWmWindowTypeDock becomes ineffective in Qt 5
            // See QTBUG-39887: https://bugreports.qt-project.org/browse/QTBUG-39887
            // Let's use KWindowSystem for that
            KX11Extras::setType(effectiveWinId(), NET::Dock);

            updateWmStrut(); // reserve screen space for the panel
            KX11Extras::setOnAllDesktops(effectiveWinId(), true);
        }
        break;
    }
    case QEvent::DragEnter:
        dynamic_cast<QDropEvent *>(event)->setDropAction(Qt::IgnoreAction);
        event->accept();
#if __cplusplus >= 201703L
        [[fallthrough]];
#endif
        // fall through
    case QEvent::Enter:
        mShowDelayTimer.start();
        break;

    case QEvent::Leave:
    case QEvent::DragLeave:
        mShowDelayTimer.stop();
        hidePanel();
        break;

#if (QT_VERSION >= QT_VERSION_CHECK(6,8,0))
    case QEvent::Paint:
    // NOTE: Starting from Qt 6.8.0, random artifacts are possible in
    // translucent windows under Wayland. This a workaround.
    if (QGuiApplication::platformName() == QStringLiteral("wayland"))
    {
        QPainter p(this);
        p.setClipRegion(static_cast<QPaintEvent*>(event)->region());
        auto origMode = p.compositionMode();
        p.setCompositionMode(QPainter::CompositionMode_Clear);
        p.fillRect(rect(), Qt::transparent);
        p.setCompositionMode(origMode);
    }
    break;
#endif

    default:
        break;
    }

    return QFrame::event(event);
}

/************************************************

 ************************************************/

void LXQtPanel::showEvent(QShowEvent *event)
{
    QFrame::showEvent(event);
    realign();
}


/************************************************

 ************************************************/
void LXQtPanel::showPopupMenu(const QPoint& cursorPos, Plugin *plugin)
{
    PopupMenu * menu = new PopupMenu(tr("Panel"), this);
    menu->setAttribute(Qt::WA_DeleteOnClose);

    menu->setIcon(XdgIcon::fromTheme(QStringLiteral("configure-toolbars")));

    // Plugin Menu ..............................
    if (plugin)
    {
        QMenu *m = plugin->popupMenu();

        if (m)
        {
            menu->addTitle(plugin->windowTitle());
            const auto actions = m->actions();
            for (auto const & action : actions)
            {
                action->setParent(menu);
                action->setDisabled(mLockPanel);
                menu->addAction(action);
            }
            delete m;
        }
    }

    // Panel menu ...............................

    menu->addTitle(QIcon(), tr("Panel"));

    menu->addAction(XdgIcon::fromTheme(QLatin1String("configure")),
                   tr("Configure Panel"),
                   this, &LXQtPanel::showConfigDialog
                  )->setDisabled(mLockPanel);

    menu->addAction(XdgIcon::fromTheme(QStringLiteral("preferences-plugin")),
                   tr("Manage Widgets"),
                   this, &LXQtPanel::showAddPluginDialog
                  )->setDisabled(mLockPanel);

    LXQtPanelApplication *a = reinterpret_cast<LXQtPanelApplication*>(qApp);
    menu->addAction(XdgIcon::fromTheme(QLatin1String("list-add")),
                   tr("Add New Panel"),
                   a, &LXQtPanelApplication::addNewPanel
                  );

    if (a->count() > 1)
    {
        menu->addAction(XdgIcon::fromTheme(QLatin1String("list-remove")),
                       tr("Remove Panel", "Menu Item"),
                       this, &LXQtPanel::userRequestForDeletion
                      )->setDisabled(mLockPanel);
    }

    QAction * act_lock = menu->addAction(tr("Lock This Panel"));
    act_lock->setCheckable(true);
    act_lock->setChecked(mLockPanel);
    connect(act_lock, &QAction::triggered, this, [this] { mLockPanel = !mLockPanel; saveSettings(false); });

#ifdef DEBUG
    menu->addSeparator();
    menu->addAction("Exit (debug only)", qApp, &QApplication::quit);
#endif

    /* Note: in multihead & multipanel setup the QMenu::popup/exec places the window
     * sometimes wrongly (it seems that this bug is somehow connected to misinterpretation
     * of QDesktopWidget::availableGeometry)
     */
    menu->setGeometry(calculatePopupWindowPos(cursorPos, menu->sizeHint()));
    willShowWindow(menu);
    menu->show();
}

Plugin* LXQtPanel::findPlugin(const ILXQtPanelPlugin* iPlugin) const
{
    const auto plugins = mPlugins->plugins();
    for (auto const & plug : plugins)
        if (plug->iPlugin() == iPlugin)
            return plug;
    return nullptr;
}

/************************************************

 ************************************************/
QRect LXQtPanel::calculatePopupWindowPos(QPoint const & absolutePos, QSize const & windowSize) const
{
    // Using of anchors makes coordinates be absolute under some Wayland compositors.
    // Therefore, to cover both X11 and Wayland, we first use the local coordinates
    // and then map them to the global coordinates.
    QPoint localPos = mapFromGlobal(absolutePos);
    int x = localPos.x(), y = localPos.y();

    switch (position())
    {
    case ILXQtPanel::PositionTop:
        y = mGeometry.height();
        break;

    case ILXQtPanel::PositionBottom:
        y = -windowSize.height();
        break;

    case ILXQtPanel::PositionLeft:
        x = mGeometry.width();
        break;

    case ILXQtPanel::PositionRight:
        x = -windowSize.width();
        break;
    }

    QRect res(mapToGlobal(QPoint(x, y)), windowSize);

    if (qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>())
        return res;

    QRect panelScreen;
    const auto screens = QApplication::screens();
    if (mActualScreenNum < screens.size())
        panelScreen = screens.at(mActualScreenNum)->geometry();
    // NOTE: We cannot use AvailableGeometry() which returns the work area here because when in a
    // multihead setup with different resolutions. In this case, the size of the work area is limited
    // by the smallest monitor and may be much smaller than the current screen and we will place the
    // menu at the wrong place. This is very bad for UX. So let's use the full size of the screen.
    if (res.right() > panelScreen.right())
        res.moveRight(panelScreen.right());

    if (res.bottom() > panelScreen.bottom())
        res.moveBottom(panelScreen.bottom());

    if (res.left() < panelScreen.left())
        res.moveLeft(panelScreen.left());

    if (res.top() < panelScreen.top())
        res.moveTop(panelScreen.top());

    return res;
}

/************************************************

 ************************************************/
QRect LXQtPanel::calculatePopupWindowPos(const ILXQtPanelPlugin *plugin, const QSize &windowSize) const
{
    Plugin *panel_plugin = findPlugin(plugin);
    if (nullptr == panel_plugin)
    {
        qWarning() << Q_FUNC_INFO << "Wrong logic? Unable to find Plugin* for" << plugin << "known plugins follow...";
        const auto plugins = mPlugins->plugins();
        for (auto const & plug : plugins)
            qWarning() << plug->iPlugin() << plug;

        return QRect();
    }

    // Note: assuming there are not contentMargins around the "BackgroundWidget" (LXQtPanelWidget)
    return calculatePopupWindowPos(mapToGlobal(panel_plugin->geometry().topLeft()), windowSize);
}


/************************************************

 ************************************************/
void LXQtPanel::willShowWindow(QWidget * w)
{
    mStandaloneWindows->observeWindow(w);
}

/************************************************

 ************************************************/
void LXQtPanel::pluginFlagsChanged(const ILXQtPanelPlugin * /*plugin*/)
{
    mLayout->rebuild();
}

/************************************************

 ************************************************/
QString LXQtPanel::qssPosition() const
{
    return positionToStr(position());
}

/************************************************

 ************************************************/
void LXQtPanel::pluginMoved(Plugin * plug)
{
    //get new position of the moved plugin
    bool found{false};
    QString plug_is_before;
    for (int i=0; i<mLayout->count(); ++i)
    {
        Plugin *plugin = qobject_cast<Plugin*>(mLayout->itemAt(i)->widget());
        if (plugin)
        {
            if (found)
            {
                //we found our plugin in previous cycle -> is before this (or empty as last)
                plug_is_before = plugin->settingsGroup();
                break;
            } else
                found = (plug == plugin);
        }
    }
    mPlugins->movePlugin(plug, plug_is_before);
}


/************************************************

 ************************************************/
void LXQtPanel::userRequestForDeletion()
{
    const QMessageBox::StandardButton ret
        = QMessageBox::warning(this, tr("Remove Panel", "Dialog Title") ,
            tr("Removing a panel can not be undone.\nDo you want to remove this panel?"),
            QMessageBox::Yes | QMessageBox::No);

    if (ret != QMessageBox::Yes) {
        return;
    }

    mSettings->beginGroup(mConfigGroup);
    const QStringList plugins = mSettings->value(QStringLiteral("plugins")).toStringList();
    mSettings->endGroup();

    for(const QString& i : plugins)
        if (!i.isEmpty())
            mSettings->remove(i);

    mSettings->remove(mConfigGroup);

    emit deletedByUser(this);
}

bool LXQtPanel::isPanelOverlapped() const
{
    LXQtPanelApplication *a = reinterpret_cast<LXQtPanelApplication*>(qApp);

    //TODO: calculate geometry on wayland
    QRect area = mGeometry;
    return a->getWMBackend()->isAreaOverlapped(area);
}

void LXQtPanel::showPanel(bool animate)
{
    if (mHidable)
    {
        mHideTimer.stop();
        if (mHidden)
        {
            mHidden = false;
            setPanelGeometry(mAnimationTime > 0 && animate);
        }
    }
}

void LXQtPanel::hidePanel()
{
    if (mHidable && !mHidden
        && !mStandaloneWindows->isAnyWindowShown())
    {
        mHideTimer.start();
    }
}

void LXQtPanel::hidePanelWork()
{
    if (!testAttribute(Qt::WA_UnderMouse))
    {
        if (!mStandaloneWindows->isAnyWindowShown())
        {
            if (!mHideOnOverlap || isPanelOverlapped())
            {
                mHidden = true;
                setPanelGeometry(mAnimationTime > 0);
            }
        }
        else
        {
            mHideTimer.start();
        }
    }
}

void LXQtPanel::setHidable(bool hidable, bool save)
{
    if (mHidable == hidable)
        return;

    mHidable = hidable;

    if (save)
        saveSettings(true);

    realign();
}

void LXQtPanel::setVisibleMargin(bool visibleMargin, bool save)
{
    if (mVisibleMargin == visibleMargin)
        return;

    mVisibleMargin = visibleMargin;

    if (save)
        saveSettings(true);

    realign();
}

void LXQtPanel::setHideOnOverlap(bool hideOnOverlap, bool save)
{
    if (mHideOnOverlap == hideOnOverlap)
        return;

    mHideOnOverlap = hideOnOverlap;

    if (save)
        saveSettings(true);

    realign();
}

void LXQtPanel::setAnimationTime(int animationTime, bool save)
{
    if (mAnimationTime == animationTime)
        return;

    mAnimationTime = animationTime;

    if (save)
        saveSettings(true);
}

void LXQtPanel::setShowDelay(int showDelay, bool save)
{
    if (mShowDelayTimer.interval() == showDelay)
        return;

    mShowDelayTimer.setInterval(showDelay);

    if (save)
        saveSettings(true);
}

QString LXQtPanel::iconTheme() const
{
    return mSettings->value(QStringLiteral("iconTheme")).toString();
}

void LXQtPanel::setIconTheme(const QString& iconTheme)
{
    LXQtPanelApplication *a = reinterpret_cast<LXQtPanelApplication*>(qApp);
    a->setIconTheme(iconTheme);
}

void LXQtPanel::updateConfigDialog() const
{
    if (!mConfigDialog.isNull() && mConfigDialog->isVisible())
    {
        mConfigDialog->updateIconThemeSettings();
        const QList<QWidget*> widgets = mConfigDialog->findChildren<QWidget*>();
        for (QWidget *widget : widgets)
            widget->update();
    }
}

bool LXQtPanel::isPluginSingletonAndRunning(QString const & pluginId) const
{
    Plugin const * plugin = mPlugins->pluginByID(pluginId);
    if (nullptr == plugin)
        return false;
    else
        return plugin->iPlugin()->flags().testFlag(ILXQtPanelPlugin::SingleInstance);
}