File: lxqtfancymenuappmap.cpp

package info (click to toggle)
lxqt-panel 2.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 16,680 kB
  • sloc: cpp: 30,052; xml: 1,152; makefile: 19
file content (412 lines) | stat: -rw-r--r-- 11,400 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
/* 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 "lxqtfancymenuappmap.h"

#include <XdgMenu>
#include <XdgIcon>

#include <QCoreApplication>
#include <QCollator>

class LXQtFancyMenuAppMapStrings
{
    Q_DECLARE_TR_FUNCTIONS(LXQtFancyMenuAppMapStrings)
};


LXQtFancyMenuAppMap::LXQtFancyMenuAppMap()
{
    mCachedIndex = -1;
    mCachedIterator = mAppSortedByName.constEnd();

    //Add Favorites category
    Category favorites;
    favorites.menuTitle = LXQtFancyMenuAppMapStrings::tr("Favorites");
    favorites.icon = XdgIcon::fromTheme(QLatin1String("bookmarks"));
    favorites.type = LXQtFancyMenuItemType::CategoryItem;
    mCategories.append(favorites);

    //Add All Apps category
    Category allAppsCategory;
    allAppsCategory.menuTitle = LXQtFancyMenuAppMapStrings::tr("All Applications");
    allAppsCategory.icon = XdgIcon::fromTheme(QLatin1String("folder"));
    allAppsCategory.type = LXQtFancyMenuItemType::CategoryItem;
    mCategories.append(allAppsCategory);

    //Add separator
    Category sepatorCategory;
    sepatorCategory.type = LXQtFancyMenuItemType::SeparatorItem;
    mCategories.append(sepatorCategory);
}

LXQtFancyMenuAppMap::~LXQtFancyMenuAppMap()
{
    clear();
    clearFavorites();
}

void LXQtFancyMenuAppMap::clear()
{
    // Keep Favorites, All Applications and separator
    mCategories.erase(mCategories.begin() + 3, mCategories.end());

    mAppSortedByName.clear();
    qDeleteAll(mAppSortedByDesktopFile);
    mAppSortedByDesktopFile.clear();

    mCachedIndex = -1;
    mCachedIterator = mAppSortedByName.constEnd();
}

void LXQtFancyMenuAppMap::clearFavorites()
{
    Category& favoritesCatRef = mCategories[0];
    for(Category::Item& item : favoritesCatRef.apps)
    {
        if(item.appItem)
        {
            delete item.appItem;
            item.appItem = nullptr;
        }
    }
    favoritesCatRef.apps.clear();
}

bool LXQtFancyMenuAppMap::rebuildModel(const XdgMenu &menu)
{
    clear();

    QDomElement rootMenu = menu.xml().documentElement();
    parseMenu(rootMenu, QString());

    mCategories.squeeze();

    return true;
}

void LXQtFancyMenuAppMap::setFavorites(const QStringList &favorites)
{
    clearFavorites();

    Category& favoritesCatRef = mCategories[0];
    favoritesCatRef.apps.reserve(favorites.size());

    for(const QString& desktopFile : favorites)
    {
        Category::Item item;
        item.type = LXQtFancyMenuItemType::AppItem;
        item.appItem = loadAppItem(desktopFile);
        if(!item.appItem)
            continue;
        favoritesCatRef.apps.append(item);
    }

    favoritesCatRef.apps.squeeze();
}

QStringList LXQtFancyMenuAppMap::getFavorites() const
{
    const Category& favoritesCatRef = mCategories[0];

    QStringList favorites;
    favorites.reserve(favoritesCatRef.apps.size());

    for(const Category::Item& item : favoritesCatRef.apps)
    {
        if(item.appItem)
        {
            favorites.append(item.appItem->desktopFile);
        }
    }

    return favorites;
}

int LXQtFancyMenuAppMap::getFavoriteIndex(const QString &desktopFile) const
{
    const Category& favoritesCatRef = mCategories.at(0);
    for(int i = 0; i < favoritesCatRef.apps.size(); i++)
    {
        const Category::Item& item = favoritesCatRef.apps.at(i);
        if(item.appItem && item.appItem->desktopFile == desktopFile)
            return i;
    }

    return -1;
}

void LXQtFancyMenuAppMap::addToFavorites(const QString &desktopFile)
{
    if(isFavorite(desktopFile))
        return;

    Category::Item item;
    item.type = LXQtFancyMenuItemType::AppItem;
    item.appItem = loadAppItem(desktopFile);
    if(!item.appItem)
        return;

    Category& favoritesCatRef = mCategories[0];
    favoritesCatRef.apps.append(item);
}

void LXQtFancyMenuAppMap::removeFromFavorites(const QString &desktopFile)
{
    if(!isFavorite(desktopFile))
        return;

    Category& favoritesCatRef = mCategories[0];
    for(auto it = favoritesCatRef.apps.begin(); it != favoritesCatRef.apps.end(); it++)
    {
        AppItem *appItem = (*it).appItem;
        if(appItem && appItem->desktopFile == desktopFile)
        {
            favoritesCatRef.apps.erase(it);
            delete appItem;
            return;
        }
    }
}

void LXQtFancyMenuAppMap::moveFavoriteItem(int oldPos, int newPos)
{
    Category& favoritesCatRef = mCategories[0];
    favoritesCatRef.apps.move(oldPos, newPos);
}

LXQtFancyMenuAppMap::AppItem *LXQtFancyMenuAppMap::getAppAt(int index)
{
    if(index < 0 || index >= getTotalAppCount())
        return nullptr;

    if(mCachedIndex != -1)
    {
        if(index == mCachedIndex + 1)
        {
            //Fast case, go to next row
            mCachedIndex++;
            mCachedIterator++;
        }

        if(index == mCachedIndex)
            return *mCachedIterator;

        int dist1 = qAbs(mCachedIndex - index);
        if(dist1 < index)
        {
            std::advance(mCachedIterator, index - mCachedIndex);
            mCachedIndex = index;
            return *mCachedIterator;
        }
    }

    // Recalculate cached iterator
    mCachedIterator = mAppSortedByName.constBegin();
    std::advance(mCachedIterator, index);
    mCachedIndex = index;
    return *mCachedIterator;
}

QList<const LXQtFancyMenuAppMap::AppItem *> LXQtFancyMenuAppMap::getMatchingApps(const QString &query) const
{
    QList<const AppItem *> byName;
    QList<const AppItem *> byKeyword;
    QList<const AppItem *> exec;

    //TODO: implement some kind of score to get better matches on top

    for(const AppItem *app : std::as_const(mAppSortedByName))
    {
        if(app->title.contains(query, Qt::CaseInsensitive))
        {
            byName.append(app);
            continue;
        }

        if(app->comment.contains(query, Qt::CaseInsensitive))
        {
            byKeyword.append(app);
            continue;
        }

        for(const QString& key : app->keywords)
        {
            if(key.startsWith(query, Qt::CaseInsensitive))
            {
                byKeyword.append(app);
                break;
            }
        }

        for(const QString& key : app->exec)
        {
            if(key.contains(query, Qt::CaseInsensitive))
            {
                exec.append(app);
                break;
            }
        }
    }

    // Give priority to title matches
    byName += byKeyword + exec;

    return byName;
}

void LXQtFancyMenuAppMap::parseMenu(const QDomElement &menu, const QString& topLevelCategory)
{
    bool catAdded = false;
    QDomElement e = menu.firstChildElement();
    while(!e.isNull())
    {
        if(e.tagName() == QLatin1String("Menu"))
        {
            if(topLevelCategory.isEmpty())
            {
                //This is a top level menu
                Category item;
                item.type = LXQtFancyMenuItemType::CategoryItem;
                item.menuName = e.attribute(QLatin1String("name"));
                item.menuTitle = e.attribute(QLatin1String("title"), item.menuName);
                QString iconName = e.attribute(QLatin1String("icon"));
                item.icon = XdgIcon::fromTheme(iconName);
                mCategories.append(item);
                catAdded = true;

                //Merge sub menu to parent
                parseMenu(e, item.menuName);
            }
            else
            {
                //Merge sub menu to parent
                parseMenu(e, topLevelCategory);
            }
        }
        else if(!topLevelCategory.isEmpty())
        {
            if(e.tagName() == QLatin1String("AppLink"))
                parseAppLink(e, topLevelCategory);
            else if(e.tagName() == QLatin1String("Separator"))
                parseSeparator(e, topLevelCategory);
        }
        else if(catAdded && e.tagName() == QLatin1String("Separator"))
        {
            Category item;
            item.type = LXQtFancyMenuItemType::SeparatorItem;
            mCategories.append(item);
            catAdded = false;
        }

        e = e.nextSiblingElement();
    }

    // Build sorted list of all apps
    mAppSortedByName = mAppSortedByDesktopFile.values();

    QCollator collator;
    collator.setCaseSensitivity(Qt::CaseInsensitive);

    std::sort(mAppSortedByName.begin(), mAppSortedByName.end(),
              [&](AppItem* a, AppItem* b) {
                  return collator.compare(a->title, b->title) < 0;
              });
}

void LXQtFancyMenuAppMap::parseAppLink(const QDomElement &app, const QString& topLevelCategory)
{
    QString desktopFile = app.attribute(QLatin1String("desktopFile"));

    // Check if already added
    AppItem *appItem = mAppSortedByDesktopFile.value(desktopFile, nullptr);
    if(!appItem)
    {
        // Add new app
        appItem = loadAppItem(desktopFile);
        if(!appItem)
            return; // Invalid app

        mAppSortedByDesktopFile.insert(appItem->desktopFile, appItem);
    }

    // Now add app to category
    for(Category &category : mCategories)
    {
        if(category.menuName == topLevelCategory)
        {
            Category::Item item;
            item.appItem = appItem;
            item.type = LXQtFancyMenuItemType::AppItem;
            category.apps.append(item);
            break;
        }
    }
}

void LXQtFancyMenuAppMap::parseSeparator(const QDomElement &sep, const QString& topLevelCategory)
{
    Q_UNUSED(sep)

    // Find category
    for(Category &category : mCategories)
    {
        if(category.menuName != topLevelCategory)
            continue;

        // XdgMenu already cares of removing consecutive separators
        // Or separators put as first or last items
        Category::Item item;
        item.type = LXQtFancyMenuItemType::SeparatorItem;
        category.apps.append(item);

        break;
    }
}

LXQtFancyMenuAppMap::AppItem *LXQtFancyMenuAppMap::loadAppItem(const QString &desktopFile)
{
    XdgDesktopFile f;
    if(!f.load(desktopFile))
        return nullptr; // Invalid App

    AppItem *item = new AppItem;
    item->desktopFile = desktopFile;
    item->title = f.name();
    item->comment = f.comment();
    if(item->comment.isEmpty())
        item->comment = f.localizedValue(QLatin1String("GenericName")).toString();
    item->icon = f.icon();
    item->desktopFileCache = f;

    item->keywords << f.localizedValue(QLatin1String("Keywords")).toString().split(QLatin1Char(';'));

    item->exec = f.expandExecString();

    return item;
}