File: lxqtfancymenu.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 (402 lines) | stat: -rw-r--r-- 13,004 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
/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * https://lxqt.org
 *
 * Copyright: 2023 LXQt team
 * Authors:
 *  Filippo Gentile <filippogentile@disroot.org>
 *
 * 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 "lxqtfancymenu.h"
#include "lxqtfancymenuconfiguration.h"
#include "lxqtfancymenuwindow.h"
#include "../panel/lxqtpanel.h"
#include <QTimer>
#include <QMessageBox>
#include <QEvent>
#include <QKeyEvent>
#include <QResizeEvent>
#include <lxqt-globalkeys.h>
#include <QApplication>
#include <QMetaEnum>
#include <QStringBuilder>

#include <XdgMenuWidget>
#include <XdgIcon>

#include <QStandardPaths>
#include <QClipboard>
#include <QMimeData>
#include <XdgAction>

#include <QDir>

#define DEFAULT_SHORTCUT "Alt+F1"

LXQtFancyMenu::LXQtFancyMenu(const ILXQtPanelPluginStartupInfo &startupInfo):
    QObject(),
    ILXQtPanelPlugin(startupInfo),
    mWindow(nullptr),
    mShortcut(nullptr),
    mFilterClear(false)
{
    mWindow = new LXQtFancyMenuWindow(&mButton);
    mWindow->setObjectName(QStringLiteral("TopLevelFancyMenu"));
    mWindow->installEventFilter(this);
    connect(mWindow, &LXQtFancyMenuWindow::aboutToHide, &mHideTimer, QOverload<>::of(&QTimer::start));
    connect(mWindow, &LXQtFancyMenuWindow::aboutToShow, &mHideTimer, &QTimer::stop);
    connect(mWindow, &LXQtFancyMenuWindow::favoritesChanged, this, &LXQtFancyMenu::saveFavorites);

    mDelayedPopup.setSingleShot(true);
    mDelayedPopup.setInterval(200);
    connect(&mDelayedPopup, &QTimer::timeout, this, &LXQtFancyMenu::showHideMenu);
    mHideTimer.setSingleShot(true);
    mHideTimer.setInterval(250);

    mButton.setAutoRaise(true);
    mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    //Notes:
    //1. installing event filter to parent widget to avoid infinite loop
    //   (while setting icon we also need to set the style)
    //2. delaying of installEventFilter because in c-tor mButton has no parent widget
    //   (parent is assigned in panel's logic after widget() call)
    QTimer::singleShot(0, mButton.parentWidget(), [this] {
        Q_ASSERT(mButton.parentWidget());
        mButton.parentWidget()->installEventFilter(this);
    });

    connect(&mButton, &QToolButton::clicked, this, &LXQtFancyMenu::showHideMenu);

    QTimer::singleShot(0, this, [this] {
        settingsChanged();
    });

    mShortcut = GlobalKeyShortcut::Client::instance()->addAction(QString{}, QStringLiteral("/panel/%1/show_hide").arg(settings()->group()), LXQtFancyMenu::tr("Show/hide main menu"), this);
    if (mShortcut)
    {
        connect(mShortcut, &GlobalKeyShortcut::Action::shortcutChanged, this, [this](const QString &, const QString & shortcut) {
                mShortcutSeq = shortcut;
        });
        connect(mShortcut, &GlobalKeyShortcut::Action::registrationFinished, this, [this] {
            if (mShortcut->shortcut().isEmpty())
                mShortcut->changeShortcut(QStringLiteral(DEFAULT_SHORTCUT));
            else
                mShortcutSeq = mShortcut->shortcut();
        });
        connect(mShortcut, &GlobalKeyShortcut::Action::activated, this, [this] {
            if (!mHideTimer.isActive())
                // Delay this a little -- if we don't do this, search field
                // won't be able to capture focus
                // See <https://github.com/lxqt/lxqt-panel/pull/131> and
                // <https://github.com/lxqt/lxqt-panel/pull/312>
                mDelayedPopup.start();
        });
    }
}


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

 ************************************************/
LXQtFancyMenu::~LXQtFancyMenu()
{
    mButton.parentWidget()->removeEventFilter(this);

    delete mWindow;
}


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

 ************************************************/
void LXQtFancyMenu::showHideMenu()
{
    if(mWindow && mWindow->isVisible())
        mWindow->hide();
    else
        showMenu();
}

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

 ************************************************/
void LXQtFancyMenu::showMenu()
{
    if (!mWindow)
        return;

    willShowWindow(mWindow);
    // Just using Qt`s activateWindow() won't work on some WMs like Kwin.
    // Solution is to execute menu 1ms later using timer
    mWindow->move(calculatePopupWindowPos(mWindow->sizeHint()).topLeft());

    emit mWindow->aboutToShow();
    mWindow->show();
    mWindow->setSearchEditFocus();
}

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

 ************************************************/
void LXQtFancyMenu::settingsChanged()
{
    setButtonIcon();
    if (settings()->value(QStringLiteral("showText"), false).toBool())
    {
        mButton.setText(settings()->value(QStringLiteral("text"), QStringLiteral("Start")).toString());
        mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    }
    else
    {
        mButton.setText(QLatin1String(""));
        mButton.setToolButtonStyle(Qt::ToolButtonIconOnly);
    }

    mLogDir = settings()->value(QStringLiteral("log_dir"), QString()).toString();

    QString menu_file = settings()->value(QStringLiteral("menu_file"), QString()).toString();
    if (menu_file.isEmpty())
        menu_file = XdgMenu::getMenuFileName();

    if (mMenuFile != menu_file)
    {
        mMenuFile = menu_file;
        mXdgMenu.setEnvironments(QStringList() << QStringLiteral("X-LXQT") << QStringLiteral("LXQt"));
        mXdgMenu.setLogDir(mLogDir);

        bool res = mXdgMenu.read(mMenuFile);
        connect(&mXdgMenu, &XdgMenu::changed, this, &LXQtFancyMenu::buildMenu);
        if (res)
        {
            QTimer::singleShot(1000, this, &LXQtFancyMenu::buildMenu);
        }
        else
        {
            QMessageBox::warning(nullptr, QStringLiteral("Parse error"), mXdgMenu.errorString());
            return;
        }
    }

    loadFavorites();
    setMenuFontSize();

    //clear the search to not leaving the menu in wrong state
    mFilterClear = settings()->value(QStringLiteral("filterClear"), true).toBool();
    mWindow->setFilterClear(mFilterClear);

    bool buttonsAtTop = settings()->value(QStringLiteral("buttonsAtTop"), false).toBool();
    mWindow->setButtonPosition(buttonsAtTop ? LXQtFancyMenuButtonPosition::Top : LXQtFancyMenuButtonPosition::Bottom);

    bool categoriesAtRight = settings()->value(QStringLiteral("categoriesAtRight"), true).toBool();
    mWindow->setCategoryPosition(categoriesAtRight ? LXQtFancyMenuCategoryPosition::Right : LXQtFancyMenuCategoryPosition::Left);

    mWindow->setAutoSelection(settings()->value(QStringLiteral("autoSel"), false).toBool());
    int delay = qBound(50, settings()->value(QStringLiteral("autoSelDelay"), 250).toInt(), 1000);
    mWindow->setAutoSelectionDelay(delay);

    realign();
}

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

 ************************************************/
void LXQtFancyMenu::buildMenu()
{
    mWindow->rebuildMenu(mXdgMenu);

    mWindow->doSearch();
    setMenuFontSize();
}

void LXQtFancyMenu::loadFavorites()
{
    bool listChanged = false;

    const QList<QMap<QString, QVariant> > list = settings()->readArray(QStringLiteral("favorites"));
    QStringList fileList;
    for(const QMap<QString, QVariant>& item : list)
    {
        QString file = item.value(QStringLiteral("desktopFile")).toString();
        if(file.isEmpty())
        {
            listChanged = true;
            continue;
        }

        QString canonicalPath = QDir(file).canonicalPath();
        if(canonicalPath != file)
            listChanged = true;

        if(canonicalPath.isEmpty())
            continue;

        if(fileList.contains(canonicalPath))
        {
            // Don't add duplicates
            listChanged = true;
            continue;
        }

        fileList.append(canonicalPath);
    }

    mWindow->setFavorites(fileList);

    if(listChanged)
        saveFavorites();
}

void LXQtFancyMenu::saveFavorites()
{
    const QStringList fileList = mWindow->favorites();

    QList<QMap<QString, QVariant> > list;
    list.reserve(fileList.size());

    for(const QString& file : fileList)
    {
        QMap<QString, QVariant> item;
        item.insert(QStringLiteral("desktopFile"), file);
        list.append(item);
    }

    // HACK: force Qt to clear old array and rewrite it
    // Otherwise it would leave garbage values inside it.
    settings()->remove(QStringLiteral("favorites"));
    settings()->setArray(QStringLiteral("favorites"), list);
}

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

 ************************************************/
void LXQtFancyMenu::setMenuFontSize()
{
    if (!mWindow)
        return;

    QFont menuFont = mButton.font();
    bool customFont = settings()->value(QStringLiteral("customFont"), false).toBool();
    int customFontSize = settings()->value(QStringLiteral("customFontSize")).toInt();

    if(customFont)
    {
        menuFont = mWindow->font();
        menuFont.setPointSize(customFontSize);
    }

    mWindow->setCustomFont(menuFont);
}

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

 ************************************************/
void LXQtFancyMenu::setButtonIcon()
{
    if (settings()->value(QStringLiteral("ownIcon"), false).toBool())
    {
        mButton.setStyleSheet(QStringLiteral("#FancyMenu { qproperty-icon: url(%1); }")
                .arg(settings()->value(QLatin1String("icon"), QLatin1String(LXQT_GRAPHICS_DIR "/helix.svg")).toString()));
    } else
    {
        mButton.setStyleSheet(QString());
    }
}

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

 ************************************************/
QDialog *LXQtFancyMenu::configureDialog()
{
    return new LXQtFancyMenuConfiguration(settings(), mShortcut, QStringLiteral(DEFAULT_SHORTCUT));
}

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

 ************************************************/
bool LXQtFancyMenu::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == mButton.parentWidget())
    {
        // the application is given a new QStyle
        if(event->type() == QEvent::StyleChange)
        {
            setMenuFontSize();
            setButtonIcon();
            mWindow->updateButtonIconSize();
        }
    }
    else if(obj == mWindow)
    {
        if(event->type() == QEvent::KeyRelease)
        {
            if (mShortcutSeq.isEmpty())
            {
                return false;
            }
            static const auto key_meta = QMetaEnum::fromType<Qt::Key>();
            // if our shortcut key is pressed while the menu is open, close the menu
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            QFlags<Qt::KeyboardModifier> mod = keyEvent->modifiers();
            QList<Qt::Key> keys = {static_cast<Qt::Key>(keyEvent->key())};
            switch (keyEvent->key())
            {
            case Qt::Key_Alt:
                mod &= ~Qt::AltModifier;
                break;
            case Qt::Key_Control:
                mod &= ~Qt::ControlModifier;
                break;
            case Qt::Key_Shift:
                mod &= ~Qt::ShiftModifier;
                break;
            case Qt::Key_Meta:
                keys << Qt::Key_Super_L << Qt::Key_Super_R;
                [[fallthrough]];
            case Qt::Key_Super_L:
            case Qt::Key_Super_R:
                mod &= ~Qt::MetaModifier;
                break;
            }
            for (const auto & key : std::as_const(keys))
            {
                const QString press = QKeySequence{static_cast<int>(mod)}.toString() % QString::fromLatin1(key_meta.valueToKey(key)).remove(0, 4);
                if (press == mShortcutSeq)
                {
                    mWindow->hide(); // close the app menu
                    return true;
                }
            }
            //TODO: go to item which starts with pressed letter
        }
        else if (event->type() == QEvent::Resize)
        {
            QResizeEvent *e = static_cast<QResizeEvent *>(event);
            if (e->oldSize().isValid() && e->oldSize() != e->size())
            {
                mWindow->move(calculatePopupWindowPos(e->size()).topLeft());
            }
        }
    }
    return false;
}

#undef DEFAULT_SHORTCUT