File: actionview.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 (355 lines) | stat: -rw-r--r-- 10,664 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
/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * https://lxqt.org
 *
 * Copyright: 2016 LXQt team
 * Authors:
 *   Palo Kisa <palo.kisa@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 "actionview.h"
#ifdef HAVE_MENU_CACHE
    #include "xdgcachedmenu.h"
#else
    #include <XdgAction>
#endif

#include <QAction>
#include <QWidgetAction>
#include <QMenu>
#include <QStandardItemModel>
#include <QScrollBar>
#include <QProxyStyle>
#include <QStyledItemDelegate>
#include <QApplication>
#include <QDrag>
#include <QMouseEvent>
#include <QMimeData>
#include <QUrl>

//==============================
#ifdef HAVE_MENU_CACHE
#include <QSortFilterProxyModel>
#else
FilterProxyModel::FilterProxyModel(QObject* parent) :
    QSortFilterProxyModel(parent) {
}

FilterProxyModel::~FilterProxyModel() = default;

bool FilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const {
    if (filterStr_.isEmpty())
        return true;
    if (QStandardItemModel* srcModel = static_cast<QStandardItemModel*>(sourceModel())) {
        QModelIndex index = srcModel->index(source_row, 0, source_parent);
        if (QStandardItem * item = srcModel->itemFromIndex(index)) {
            XdgAction * action = qobject_cast<XdgAction *>(qvariant_cast<QAction *>(item->data(ActionView::ActionRole)));
            if (action) {
                const XdgDesktopFile& df = action->desktopFile();
                if (df.name().contains(filterStr_, filterCaseSensitivity()))
                    return true;
                QStringList list = df.expandExecString();
                if (!list.isEmpty()) {
                    if (list.at(0).contains(filterStr_, filterCaseSensitivity()))
                        return true;
                }
            }
        }
    }
    return false;
}
#endif
//==============================
namespace
{
    class SingleActivateStyle : public QProxyStyle
    {
    public:
        using QProxyStyle::QProxyStyle;
        int styleHint(StyleHint hint, const QStyleOption * option = nullptr, const QWidget * widget = nullptr, QStyleHintReturn * returnData = nullptr) const override
        {
            if(hint == QStyle::SH_ItemView_ActivateItemOnSingleClick)
                return 1;
            return QProxyStyle::styleHint(hint, option, widget, returnData);

        }
    };

    class DelayedIconDelegate : public QStyledItemDelegate
    {
    public:
        DelayedIconDelegate(QObject * parent = nullptr)
            : QStyledItemDelegate(parent)
        {
        }

        void setMaxItemWidth(int max)
        {
            mMaxItemWidth = max;
        }

        QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override
        {
            QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
            //the XdgCachedMenuAction/XdgAction does load the icon upon showing its menu
#ifdef HAVE_MENU_CACHE
            if (icon.isNull())
            {
                XdgCachedMenuAction * cached_action = qobject_cast<XdgCachedMenuAction *>(qvariant_cast<QAction *>(index.data(ActionView::ActionRole)));
                Q_ASSERT(nullptr != cached_action);
                cached_action->updateIcon();
                const_cast<QAbstractItemModel *>(index.model())->setData(index, cached_action->icon(), Qt::DecorationRole);
            }
#else
            if (icon.isNull())
            {
                XdgAction * action = qobject_cast<XdgAction *>(qvariant_cast<QAction *>(index.data(ActionView::ActionRole)));
                if (action != nullptr)
                {
                  action->updateIcon();
                  const_cast<QAbstractItemModel *>(index.model())->setData(index, action->icon(), Qt::DecorationRole);
                }
            }
#endif
            QSize s = QStyledItemDelegate::sizeHint(option, index);
            s.setWidth(qMin(mMaxItemWidth, s.width()));
            return s;
        }
    private:
        int mMaxItemWidth{300};
    };

}
//==============================
ActionView::ActionView(QWidget * parent /*= nullptr*/)
    : QListView(parent)
    , mModel{new QStandardItemModel{this}}
#ifdef HAVE_MENU_CACHE
    , mProxy{new QSortFilterProxyModel{this}}
#else
    , mProxy{new FilterProxyModel{this}}
#endif
    , mMaxItemsToShow(10)
{
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setSizeAdjustPolicy(AdjustToContents);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setSelectionBehavior(SelectRows);
    setSelectionMode(SingleSelection);

    SingleActivateStyle * s = new SingleActivateStyle;
    s->setParent(this);
    setStyle(s);
    mProxy->setSourceModel(mModel);
    mProxy->setDynamicSortFilter(true);
    mProxy->setFilterRole(FilterRole);
    mProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
    mProxy->sort(0);
    {
        std::unique_ptr<QItemSelectionModel> guard{selectionModel()};
        setModel(mProxy);
    }
    {
        std::unique_ptr<QAbstractItemDelegate> guard{itemDelegate()};
        setItemDelegate(new DelayedIconDelegate{this});
    }
    connect(this, &QAbstractItemView::activated, this, &ActionView::onActivated);
}

void ActionView::ActionView::clear()
{
    for (int i = mModel->rowCount() - 1; i >= 0; --i)
    {
        mModel->removeRow(i);
    }
}

void ActionView::addAction(QAction * action)
{
    QStandardItem * item = new QStandardItem;
    item->setData(QVariant::fromValue<QAction *>(action), ActionRole);
    item->setFont(action->font());
    //Note: XdgCachedMenuAction has delayed icon loading... we are loading the icon
    //in QStyledItemDelegate:sizeHint if necessary
    item->setIcon(action->icon());
    item->setText(action->text());
    item->setToolTip(action->toolTip());
    QString all = action->text();
    all += QLatin1Char('\n');
    all += action->toolTip();
    item->setData(all, FilterRole);

    mModel->appendRow(item);
    connect(action, &QObject::destroyed, this, &ActionView::onActionDestroyed);
}

bool ActionView::existsAction(QAction const * action) const
{
    bool exists = false;
    for (int row = mModel->rowCount() - 1; 0 <= row; --row)
    {
        const QModelIndex index = mModel->index(row, 0);
        if (action->text() == mModel->data(index, Qt::DisplayRole)
                && action->toolTip() == mModel->data(index, Qt::ToolTipRole)
                )
        {
            exists = true;
            break;
        }

    }
    return exists;
}

void ActionView::fillActions(QMenu * menu)
{
    clear();
    fillActionsRecursive(menu);
}

void ActionView::setFilter(QString const & filter)
{
#ifdef HAVE_MENU_CACHE
    mProxy->setFilterFixedString(filter);
#else
    mProxy->setfilerString(filter);
#endif
    const int count = mProxy->rowCount();
    if (0 < count)
    {
        if (count > mMaxItemsToShow)
        {
            setCurrentIndex(mProxy->index(mMaxItemsToShow - 1, 0));
            verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
        } else
        {
            setCurrentIndex(mProxy->index(count - 1, 0));
        }
    }
}

void ActionView::setMaxItemsToShow(int max)
{
    mMaxItemsToShow = max;
}

void ActionView::setMaxItemWidth(int max)
{
    dynamic_cast<DelayedIconDelegate *>(itemDelegate())->setMaxItemWidth(max);
}

void ActionView::activateCurrent()
{
    QModelIndex const index = currentIndex();
    if (index.isValid())
        emit activated(index);
}

QSize ActionView::viewportSizeHint() const
{
    const int count = mProxy->rowCount();
    QSize s{0, 0};
    if (0 < count)
    {
        const bool scrollable = mMaxItemsToShow < count;
        s.setWidth(sizeHintForColumn(0) + (scrollable ? verticalScrollBar()->sizeHint().width() : 0));
        s.setHeight(sizeHintForRow(0) * (scrollable ? mMaxItemsToShow  : count));
    }
    return s;
}

QSize ActionView::minimumSizeHint() const
{
    return QSize{0, 0};
}

void ActionView::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
        mDragStartPosition = event->position().toPoint();

    QListView::mousePressEvent(event);
}

void ActionView::mouseMoveEvent(QMouseEvent *event)
{
    if (!(event->buttons() & Qt::LeftButton))
        return;

    if ((event->position().toPoint() - mDragStartPosition).manhattanLength() < QApplication::startDragDistance())
        return;

    XdgAction *a = qobject_cast<XdgAction*>(indexAt(mDragStartPosition).data(ActionView::ActionRole).value<QAction*>());
    if (!a)
        return;

    QList<QUrl> urls;
    urls << QUrl::fromLocalFile(a->desktopFile().fileName());

    QMimeData *mimeData = new QMimeData();
    mimeData->setUrls(urls);

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->exec(Qt::CopyAction | Qt::LinkAction);
    emit requestShowHideMenu();
}

void ActionView::onActivated(QModelIndex const & index)
{
    QAction * action = qvariant_cast<QAction *>(model()->data(index, ActionRole));
    Q_ASSERT(nullptr != action);
    action->trigger();
}

void ActionView::onActionDestroyed()
{
    QObject * const action = sender();
    Q_ASSERT(nullptr != action);
    for (int i = mModel->rowCount() - 1; 0 <= i; --i)
    {
        QStandardItem * item = mModel->item(i);
        if (action == item->data(ActionRole).value<QObject *>())
        {
            mModel->removeRow(i);
            break;
        }
    }
}

void ActionView::fillActionsRecursive(QMenu * menu)
{
    const auto actions = menu->actions();
    for (auto const & action : actions)
    {
        if (QMenu * sub_menu = action->menu())
        {
            fillActionsRecursive(sub_menu); //recursion
        } else if (nullptr == qobject_cast<QWidgetAction* >(action)
                && !action->isSeparator())
        {
            //real menu action -> app
            if (!existsAction(action))
                addAction(action);
        }
    }
}