forked from felixonmars/panda-topbar
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathappmenuwidget.cpp
More file actions
2019 lines (1814 loc) · 84 KB
/
Copy pathappmenuwidget.cpp
File metadata and controls
2019 lines (1814 loc) · 84 KB
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
/*
* Copyright (C) 2020 PandaOS Team.
* Author: rekols <revenmartin@gmail.com>
* Portions Copyright (C) 2020-22 Simon Peter.
* Author: Simon Peter <probono@puredarwin.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "appmenuwidget.h"
#include "appmenu/menuimporteradaptor.h"
#include "mainwidget.h"
#include "menuqcalc.h"
#include <chrono>
#include <QProcess>
#include <QHBoxLayout>
#include <QDebug>
#include <QMenu>
#include <QWidgetAction>
#include <QX11Info>
#include <QApplication>
#include <QAbstractItemView>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QLabel>
#include <QList>
#include <QDBusServiceWatcher>
#include <QLineEdit>
#include <QPushButton>
#include <QStyle>
#include <QDesktopWidget>
#include <QScreen>
#include <QObject>
#include <QSharedPointer>
#include <QStandardPaths>
#include <QCompleter>
#include <QMouseEvent>
#include <QTimer>
#include <QComboBox>
#include <QItemSelectionModel>
#include <QAbstractItemModel>
#include <QListView>
#include <QCryptographicHash>
#include <QWindow>
#include <QTimer>
#include <Baloo/Query>
#include <KF5/KWindowSystem/KWindowSystem>
#include <KF5/KWindowSystem/KWindowInfo>
#include <KF5/KWindowSystem/NETWM>
#include <kglobalaccel.h>
#include <cmath>
#include <QClipboard>
#include <QUrl>
#if defined(Q_OS_FREEBSD)
# include <magic.h>
# include <sys/types.h>
# include <sys/extattr.h>
#endif
#include <QFileSystemModel>
#include <QKeySequence>
#include <signal.h>
#include "mainwindow.h"
#include "thumbnails.h"
// SystemMenu is like QMenu but has a first menu item
// that changes depending on whether modifier keys are pressed
// https://stackoverflow.com/a/52756601
class SystemMenu : public QMenu
{
private:
QAction qCmdAbout;
bool alt;
public:
SystemMenu(QWidget *parent) : QMenu(parent), qCmdAbout(tr("About This Computer")), alt(false)
{
addAction(&qCmdAbout);
}
protected:
virtual void showEvent(QShowEvent *pQEvent) override
{
qDebug() << "SystemMenu::showEvent";
update();
QMenu::showEvent(pQEvent);
}
virtual void keyPressEvent(QKeyEvent *pQEvent) override
{
qDebug() << "SystemMenu::keyPressEvent";
update(pQEvent->modifiers());
QMenu::keyPressEvent(pQEvent);
}
virtual void keyReleaseEvent(QKeyEvent *pQEvent) override
{
qDebug() << "SystemMenu::keyReleaseEvent";
update(pQEvent->modifiers());
QMenu::keyReleaseEvent(pQEvent);
}
private:
void update() { update((QApplication::keyboardModifiers()) != 0); }
void update(bool alt)
{
qDebug() << "alt:" << alt;
if (!alt != !this->alt) {
qCmdAbout.setText(alt ? tr("About helloDesktop") : tr("About This Computer"));
}
this->alt = alt;
}
};
// Put cursor back in search box if user presses backspace while a menu item is highlighted
void AppMenuWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Backspace) {
searchLineEdit->setFocus();
// FIXME: Wait until searchLineEdit has focus before continuing
}
QCoreApplication::sendEvent(parent(), event);
}
void SearchLineEdit::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up) {
emit editingFinished();
QCoreApplication::sendEvent(parent(), event);
} else {
QCoreApplication::sendEvent(parent(), event);
}
QLineEdit::keyPressEvent(event);
}
class MyLineEditEventFilter : public QObject
{
public:
explicit MyLineEditEventFilter(QLineEdit *parent) : QObject(parent) { }
bool eventFilter(QObject *obj, QEvent *e)
{
// qDebug() << "probono: e->type()" << e->type();
switch (e->type()) {
case QEvent::WindowActivate: {
// Whenever this window becomes active, then set the focus on the search box
if (reinterpret_cast<QLineEdit *>(parent())->hasFocus() == false) {
reinterpret_cast<QLineEdit *>(parent())->setFocus();
}
break;
}
case QEvent::KeyPress: {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
// qDebug() << "probono: keyEvent->key()" << keyEvent->key();
if (keyEvent->key() == Qt::Key_Escape) {
// When esc key is pressed while cursor is in QLineEdit, empty the QLineEdit
// https://stackoverflow.com/a/38066410
reinterpret_cast<QLineEdit *>(parent())->clear();
reinterpret_cast<QLineEdit *>(parent())->setText("");
}
if (keyEvent->key() == (Qt::Key_Tab | Qt::Key_Alt)) {
// When esc Tab is pressed while cursor is in QLineEdit, also empty the QLineEdit
// and prevent the focus from going elsewhere in the menu. This effectively prevents
// the menu from being operated by cursor keys. If we want that functionality back,
// we might remove the handling of Qt::Key_Tab but instead we would have to ensure
// that we put the focus back on the search box whenever this application is
// launched (again) and re-invoked by QSingleApplication
reinterpret_cast<QLineEdit *>(parent())->clear();
reinterpret_cast<QLineEdit *>(parent())->setText("");
}
break;
}
case QEvent::FocusOut: // QEvent::FocusOut:
{
// When the focus goes not of the QLineEdit, empty the QLineEdit and restore the
// placeholder text reinterpret_cast<QLineEdit
// *>(parent())->setPlaceholderText("Alt+Space"); reinterpret_cast<QLineEdit
// *>(parent())->setPlaceholderText(tr("Search")); Note that we write Alt-Space here but
// in fact this is not a feature of this application but is a feature of
// lxqt-config-globalkeyshortcuts in our case, where we set up a shortcut that simply
// launches this application (again). Since we are using
// searchLineEdit->setStyleSheet("background: white"); // Do this in stylesheet.qss
// instead reinterpret_cast<QLineEdit
// *>(parent())->setAlignment(Qt::AlignmentFlag::AlignRight);
reinterpret_cast<QLineEdit *>(parent())->clear();
reinterpret_cast<QLineEdit *>(parent())->setText("");
break;
}
case QEvent::FocusIn: {
// When the focus goes into the QLineEdit, empty the QLineEdit
// reinterpret_cast<QLineEdit *>(parent())->setPlaceholderText("");
// reinterpret_cast<QLineEdit *>(parent())->setAlignment(Qt::AlignmentFlag::AlignLeft);
break;
}
default:
return QObject::eventFilter(obj, e);
}
return QObject::eventFilter(obj, e);
}
};
// Select the first result of the completer if there is only one result left
// https://github.com/helloSystem/Menu/issues/14
class AutoSelectFirstFilter : public QObject
{
public:
explicit AutoSelectFirstFilter(QLineEdit *parent) : QObject(parent) { }
bool eventFilter(QObject *obj, QEvent *e) override
{
QCompleter *completer = reinterpret_cast<QLineEdit *>(parent())->completer();
// Automatically select the first match of the completer if there is only one result left
if (e->type() == QEvent::KeyRelease) {
if (completer->completionCount() == 1) {
// completer->setCurrentRow(0); // This is not changing the current row selection,
// but the following does
QListView *l = static_cast<QListView *>(completer->popup());
QModelIndex idx = completer->completionModel()->index(0, 0, QModelIndex());
l->setCurrentIndex(idx);
}
}
return QObject::eventFilter(obj, e);
}
};
void AppMenuWidget::addAppToMenu(QString candidate, QMenu *submenu)
{
// qDebug() << "probono: Processing" << candidate;
QString nameWithoutSuffix =
QFileInfo(QDir(candidate).canonicalPath())
.completeBaseName(); // baseName() gets it wrong e.g., when there are dots in
// version numbers; dereference symlink to candidate
QFileInfo file(candidate);
if (file.fileName().endsWith(".app")) {
QString AppCand = QDir(candidate).canonicalPath() + "/"
+ nameWithoutSuffix; // Dereference symlink to candidate
// qDebug() << "################### Checking" << AppCand;
if (QFileInfo::exists(AppCand) == true) {
// qDebug() << "# Found" << AppCand;
QFileInfo fi(file.fileName());
QString base = fi.completeBaseName(); // The name of the .app directory without suffix
// // baseName() gets it wrong e.g., when there
// are dots in version numbers
QAction *action = submenu->addAction(base);
connect(action, &QAction::triggered, this, [this, action] {
actionLaunch(action);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
searchResults
<< action; // The items in searchResults get removed when search results change
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
QString IconCand =
QDir(candidate).canonicalPath() + "/Resources/" + nameWithoutSuffix + ".png";
if (QFileInfo::exists(IconCand) == true) {
// qDebug() << "# Found icon" << IconCand;
action->setIcon(QIcon(IconCand));
action->setIconVisibleInMenu(true); // So that an icon is shown even though the
// theme sets Qt::AA_DontShowIconsInMenus
}
}
} else if (file.fileName().endsWith(".AppDir")) {
QString AppCand = QDir(candidate).canonicalPath() + "/" + "AppRun";
// qDebug() << "################### Checking" << AppCand;
if (QFileInfo::exists(AppCand) == true) {
// qDebug() << "# Found" << AppCand;
QFileInfo fi(file.fileName());
QString base = fi.completeBaseName(); // baseName() gets it wrong e.g., when there are
// dots in version numbers
QStringList executableAndArgs = { AppCand };
QAction *action = submenu->addAction(base);
connect(action, &QAction::triggered, this, [this, action] {
actionLaunch(action);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
searchResults
<< action; // The items in searchResults get removed when search results change
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
QString IconCand = QDir(candidate).canonicalPath() + "/.DirIcon";
if (QFileInfo::exists(IconCand) == true) {
// qDebug() << "# Found icon" << IconCand;
action->setIcon(QIcon(IconCand));
action->setIconVisibleInMenu(true); // So that an icon is shown even though the
// theme sets Qt::AA_DontShowIconsInMenus
}
}
} else if (file.fileName().endsWith(".desktop")) {
// .desktop file
// qDebug() << "# Found" << file.fileName();
QFileInfo fi(file.fileName());
QString base = fi.completeBaseName(); // baseName() gets it wrong e.g., when there are dots
// in version numbers
QStringList executableAndArgs = { fi.absoluteFilePath() };
QSettings desktopFile(file.absoluteFilePath(), QSettings::IniFormat);
QString noDisplayCand = desktopFile.value("Desktop Entry/NoDisplay").toString();
if (noDisplayCand != "true") {
QString name = desktopFile.value("Desktop Entry/Name").toString();
QString IconCand = desktopFile.value("Desktop Entry/Icon").toString();
if (name.isEmpty())
name = base;
QAction *action = submenu->addAction(name);
connect(action, &QAction::triggered, this, [this, action] {
actionLaunch(action);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
searchResults
<< action; // The items in searchResults get removed when search results change
// Finding the icon file is way too involved with XDG, but we are not implementing all
// edge cases If you were doubting that XDG standards are overly complex, here is the
// proof...
action->setIcon(QIcon::fromTheme(IconCand));
QStringList iconSuffixes = { "", ".png", ".xpm", ".jpg", ".svg", ".icns" };
if (IconCand.contains("/")) {
if (QFileInfo::exists(IconCand)) {
action->setIcon(QIcon(IconCand));
}
} else if (QFileInfo("/usr/local/share/" + IconCand + "/icons/" + IconCand + ".png")
.exists()) {
for (const QString iconSuffix : iconSuffixes) {
action->setIcon(QIcon("/usr/local/share/" + IconCand + "/icons/" + IconCand
+ iconSuffix));
}
} else {
for (const QString iconSuffix : iconSuffixes) {
for (QString pixmapsPath :
QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation)) {
QString iconCandFile = pixmapsPath + "/pixmaps/" + IconCand + iconSuffix;
// qDebug() << "iconCandFile" << iconCandFile;
if (QFileInfo::exists(iconCandFile)) {
// qDebug() << "Found icon" << iconCandFile;
action->setIcon(QIcon(iconCandFile));
}
}
}
}
action->setIconVisibleInMenu(true); // So that an icon is shown even though the theme
// sets Qt::AA_DontShowIconsInMenus
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
// action->setDisabled(true); // As a reminder that we consider those legacy and
// encourage people to switch
}
} else if (file.fileName().endsWith(".AppImage") || file.fileName().endsWith(".appimage")) {
// .desktop file
// qDebug() << "# Found" << file.fileName();
QFileInfo fi(file.fileName());
QString base = fi.completeBaseName(); // baseName() gets it wrong e.g., when there are dots
// in version numbers
QStringList executableAndArgs = { fi.absoluteFilePath() };
QAction *action = submenu->addAction(base);
connect(action, &QAction::triggered, this, [this, action] {
actionLaunch(action);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
searchResults
<< action; // The items in searchResults get removed when search results change
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
QString IconCand = Thumbnail(QDir(candidate).absolutePath(), QCryptographicHash::Md5,
Thumbnail::ThumbnailSizeNormal, nullptr)
.getIconPath();
// qDebug() << "# ############################### thumbnail for" <<
// QDir(candidate).absolutePath();
if (QFileInfo::exists(IconCand) == true) {
// qDebug() << "# Found thumbnail" << IconCand;
action->setIcon(QIcon(IconCand));
action->setIconVisibleInMenu(true); // So that an icon is shown even though the theme
// sets Qt::AA_DontShowIconsInMenus
} else {
// TODO: Request thumbnail;
// https://github.com/KDE/kio-extras/blob/master/thumbnail/thumbnail.cpp qDebug() << "#
// Did not find thumbnail" << IconCand << "TODO: Request it from thumbnailer";
}
} else if (file.isExecutable() && !file.isDir()) {
// qDebug() << "# Found" << file.fileName();
QFileInfo fi(file.fileName());
QString base = fi.completeBaseName(); // baseName() gets it wrong e.g., when there are dots
// in version numbers
QStringList executableAndArgs = { fi.absoluteFilePath() };
QAction *action = submenu->addAction(base);
connect(action, &QAction::triggered, this, [this, action] {
actionLaunch(action);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
searchResults
<< action; // The items in searchResults get removed when search results change
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
action->setToolTip(file.absoluteFilePath());
action->setProperty("path", file.absoluteFilePath());
action->setIcon(QIcon::fromTheme("application-x-executable"));
action->setIconVisibleInMenu(true); // So that an icon is shown even though the theme sets
// Qt::AA_DontShowIconsInMenus
}
}
void AppMenuWidget::findAppsInside(QStringList locationsContainingApps)
// probono: Check locationsContainingApps for applications and add them to the m_systemMenu.
// TODO: Nested submenus rather than flat ones with '▸'
// This code is similar to the code in the 'launch' command
{
QStringList nameFilter({ "*.app", "*.AppDir", "*.desktop", "*.AppImage", "*.appimage" });
foreach (QString directory, locationsContainingApps) {
// Shall we process this directory? Only if it contains at least one application, to
// optimize for speed by not descending into directory trees that do not contain any
// applications at all. Can make a big difference.
QDir dir(directory);
int numberOfAppsInDirectory = dir.entryList(nameFilter).length();
QMenu *submenu;
if (directory.toLower().endsWith(".app") == false
&& directory.toLower().endsWith(".AppDir") == false && numberOfAppsInDirectory > 0) {
// qDebug() << "# Descending into" << directory;
QStringList locationsToBeChecked = { directory };
// submenu = m_systemMenu->addMenu(base); // TODO: Use this once we have nested submenus
// rather than flat ones with '→'
submenu = m_systemMenu->addMenu(directory);
submenu->setProperty("path", directory);
// https://github.com/helloSystem/Menu/issues/15
// probono: Watch this directory for changes and if we detect any, rebuild the menu
if (!watchedLocations.contains(directory) && QFileInfo(directory).isDir()) {
watchedLocations.append(directory);
if (watcher->addPath(directory) == false) {
qDebug() << "Failed to watch" << directory;
qDebug() << "Now a crash is imminent?";
} else {
qDebug() << "Now watching" << directory;
}
} else if (!watchedLocations.contains(directory) && !QFileInfo(directory).exists()) {
qDebug() << "Directory" << directory << "does not exist anymore";
watchedLocations.removeAll(directory);
if (watcher->removePath(directory) == false) {
qDebug() << "Failed to unwatch" << directory;
qDebug() << "Now a crash is imminent?";
} else {
qDebug() << "No longer watching" << directory;
}
}
submenu->setToolTip(directory);
submenu->setTitle(directory.remove(0, 1).replace("/", " ▸ "));
submenu->setToolTipsVisible(true); // Seems to be needed here, too, so that the submenu
// items show their correct tooltips?
// Make it possible to open the directory that contains the app by clicking on the
// submenu itself
submenu->installEventFilter(this);
} else {
continue;
}
// Use QDir::entryList() instead of QDirIterator because it supports sorting
QStringList candidates = dir.entryList();
QString candidate;
foreach (candidate, candidates) {
candidate = dir.path() + "/" + candidate;
// Do not show Autostart directories (or should we?)
if (candidate.endsWith("/Autostart") == true) {
continue;
}
QFileInfo file(candidate);
if (locationsContainingApps.contains(candidate) == false && file.isDir()
&& candidate.endsWith("/..") == false && candidate.endsWith("/.") == false
&& candidate.endsWith(".app") == false && candidate.endsWith(".AppDir") == false) {
// qDebug() << "# Found" << file.fileName() << ", a directory that is not an .app
// bundle nor an .AppDir";
QStringList locationsToBeChecked({ candidate });
findAppsInside(locationsToBeChecked);
} else {
addAppToMenu(candidate, submenu);
}
}
}
}
void iterate(const QModelIndex &index, const QAbstractItemModel *model,
const std::function<int(const QModelIndex &, int depth)> &fun, int depth = 0)
{
if (index.isValid())
if (fun(index, depth) > 0) {
return;
}
if ((index.flags() & Qt::ItemNeverHasChildren) || !model->hasChildren(index))
return;
auto rows = model->rowCount(index);
auto cols = model->columnCount(index);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
iterate(model->index(i, j, index), model, fun, depth + 1);
}
AppMenuWidget::AppMenuWidget(QWidget *parent)
: QWidget(parent), watcher(new QFileSystemWatcher(this)), m_typingTimer(new QTimer(this))
{
// probono: Reload menu when something changed in a watched directory
// https://github.com/helloSystem/Menu/issues/15
connect(watcher, SIGNAL(directoryChanged(QString)), SLOT(rebuildMenu()));
m_menuQCalc = new MenuQCalc();
QHBoxLayout *layout = new QHBoxLayout;
layout->setAlignment(Qt::AlignCenter); // Center QHBoxLayout vertically
setLayout(layout);
layout->setContentsMargins(0, 0, 0, 0);
// Add search box to menu
searchLineEdit = new SearchLineEdit(this);
// Make sure the search box gets cleared when this application loses focus
searchLineEdit->setObjectName(
"actionSearch"); // probono: This name can be used in qss to style it specifically
searchLineEdit->setFixedHeight(
22); // FIXME: Dynamically get the height of a QMenuItem and use that
searchLineEdit->setWindowFlag(Qt::WindowDoesNotAcceptFocus, false);
searchLineEdit->setFocus();
m_searchMenu = new QMenu();
m_searchMenu->setIcon(QIcon::fromTheme("search-symbolic"));
std::function<int(QModelIndex idx, int depth)> traverse = [this](QModelIndex idx, int depth) {
QAction *action = idx.data().value<QAction *>();
action->setShortcutContext(Qt::ApplicationShortcut);
if (action->isVisible() && idx.parent().isValid()) {
m_wasVisible.push_back(
cmpAction({ idx.parent().data().value<QAction *>()->text().toStdString(),
idx.data().value<QAction *>()->text().toStdString(), idx.row() }));
}
if (action->menu()) {
emit action->menu()->aboutToShow();
}
return 0;
};
std::function<int(QModelIndex idx, int depth)> traverse1 = [this](QModelIndex idx, int depth) {
QAction *action = idx.data().value<QAction *>();
if (action->menu()) {
emit action->menu()->aboutToShow();
}
return 0;
};
connect(m_searchMenu, &QMenu::aboutToShow, [this, traverse1]() {
iterate(QModelIndex(), m_appMenuModel, traverse1);
searchLineEdit->setFocus();
});
connect(qApp, &QApplication::focusWindowChanged, this, [this](QWindow *a) {
// https://github.co m/helloSystem/Menu/issues/95
});
connect(qApp, &QApplication::applicationStateChanged, this, [this](Qt::ApplicationState state) {
if (state == Qt::ApplicationActive) {
m_searchMenuOpened = searchLineEdit->isActiveWindow();
}
if (state == Qt::ApplicationInactive && m_searchMenuOpened) {
searchLineEdit->clear();
emit searchLineEdit->textChanged("");
m_searchMenuOpened = false;
}
});
setFocusPolicy(Qt::NoFocus);
m_systemMenu = new SystemMenu(this); // Using our SystemMenu subclass instead of a QMenu to be
// able to toggle "About..." when modifier key is pressed
m_systemMenu->setTitle(tr("System"));
QWidgetAction *widgetAction = new QWidgetAction(this);
widgetAction->setDefaultWidget(searchLineEdit);
m_searchMenu->addAction(widgetAction);
connect(searchLineEdit, &QLineEdit::editingFinished, this, &AppMenuWidget::searchEditingDone);
// connect(searchLineEdit,&QLineEdit::textChanged,this,&AppMenuWidget::searchMenu);
// Do not do this immediately, but rather delayed
// https://wiki.qt.io/Delay_action_to_wait_for_user_interaction
m_typingTimer->setSingleShot(true); // Ensure the timer will fire only once after it was started
connect(m_typingTimer, &QTimer::timeout, this, &AppMenuWidget::searchMenu);
connect(searchLineEdit, &QLineEdit::textChanged, this, &AppMenuWidget::refreshTimer);
m_systemMenu->setToolTipsVisible(true); // Works; shows the full path
// Populate the contents of the search menu
populateSystemMenu(parent);
// Add main menu
m_menuBar = new QMenuBar(this);
m_menuBar->setContentsMargins(0, 0, 0, 0);
integrateSystemMenu(m_menuBar); // Add System menu to main menu
layout->addWidget(m_menuBar, 0, Qt::AlignLeft);
layout->insertStretch(2); // Stretch after the main menu, which is the 2nd item in the layout
m_appMenuModel = new AppMenuModel(m_menuBar);
connect(m_appMenuModel, &AppMenuModel::menuAboutToBeImported, this,
&AppMenuWidget::menuAboutToBeImported);
connect(m_appMenuModel, &AppMenuModel::menuImported, this,
[this, traverse](QString serviceName) {
m_wasVisible.clear();
if (m_appMenuModel->menuAvailable()) {
QTimer::singleShot(100, this, [this, traverse] {
iterate(QModelIndex(), m_appMenuModel, traverse);
});
}
m_appMenuModel->m_pending_service[serviceName] = false;
});
connect(m_appMenuModel, &AppMenuModel::menuAvailableChanged, this, &AppMenuWidget::updateMenu);
connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, this,
&AppMenuWidget::delayUpdateActiveWindow);
connect(KWindowSystem::self(),
static_cast<void (KWindowSystem::*)(WId, NET::Properties, NET::Properties2)>(
&KWindowSystem::windowChanged),
this, &AppMenuWidget::onWindowChanged);
// Load action search
actionCompleter = nullptr;
MenuImporter *menuImporter = new MenuImporter(this);
menuImporter->connectToBus();
}
void AppMenuWidget::populateSystemMenu(QWidget *parent) {
qDebug() << "populateSystemMenu";
// Empty the menu
if (m_systemMenu->actions().size() > 1) {
QList<QAction *> actions = m_systemMenu->actions();
for (int i = 1; i < actions.size(); i++) {
m_systemMenu->removeAction(actions.at(i));
}
}
// If we were using a QMenu, we would do:
// QAction *aboutAction = m_systemMenu->addAction(tr("About This Computer"));
// connect(aboutAction, SIGNAL(triggered()), this, SLOT(actionAbout()));
// Since we are using our SystemMenu subclass instead which already contains the first menu
// item, we do:
// Remove existing connection from m_systemMenu->actions().constFirst(),
m_systemMenu->actions().constFirst()->disconnect();
// and connect it to our new slot
connect(m_systemMenu->actions().constFirst(), SIGNAL(triggered()), this, SLOT(actionAbout()));
m_systemMenu->addSeparator();
// Search menu item, so that we have a place to show the shortcut in the menu (discoverability!)
QAction *searchAction = m_systemMenu->addAction(tr("Search"));
searchAction->setObjectName("Search"); // Needed for KGlobalAccel global shortcut; becomes
// visible in kglobalshortcutsrc
KGlobalAccel::self()->setShortcut(
searchAction, { QKeySequence("Ctrl+Space") },
KGlobalAccel::NoAutoloading); // Set global shortcut; this also becomes editable in
// kglobalshortcutsrc
connect(searchAction, &QAction::triggered, this, [searchAction, parent, this]() {
qobject_cast<MainWidget *>(parent)->triggerFocusMenu();
emit menuAboutToBeImported(); // Stop showing application name upon Command+Space; this gets
// stopShowingApplicationName called
});
searchAction->setShortcut(QKeySequence(
KGlobalAccel::self()
->globalShortcut(qApp->applicationName(), searchAction->objectName())
.value(0))); // Show the shortcut on the menu item
m_systemMenu->addSeparator();
// Add submenus with applications to the System menu
QStringList locationsContainingApps = {};
locationsContainingApps.append(QDir::homePath());
locationsContainingApps.append(
QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
locationsContainingApps.append(QDir::homePath() + "/Applications");
locationsContainingApps.append(QDir::homePath() + "/bin");
locationsContainingApps.append(QDir::homePath() + "/.bin");
locationsContainingApps.append("/Applications");
locationsContainingApps.removeDuplicates(); // Make unique
findAppsInside(locationsContainingApps);
m_systemMenu->addSeparator();
QAction *forceQuitAction = m_systemMenu->addAction(tr("Force Quit Application"));
connect(forceQuitAction, SIGNAL(triggered()), this, SLOT(actionForceQuit()));
forceQuitAction->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Escape));
m_systemMenu->addSeparator();
/*
// Sleep
QAction *sleepAction = m_systemMenu->addAction(tr("Sleep"));
sleepAction->setObjectName("Sleep"); // Needed for KGlobalAccel global shortcut; becomes visible
in kglobalshortcutsrc
// KGlobalAccel::self()->setShortcut(sleepAction, {QKeySequence("...")},
KGlobalAccel::NoAutoloading); // Set global shortcut; this also becomes editable in
kglobalshortcutsrc connect(sleepAction, &QAction::triggered, this, [sleepAction, this]() {
qDebug() << __func__;
QProcess *p = new QProcess();
p->setProgram("zzz");
p->setArguments({});
p->startDetached();
});
m_systemMenu->addSeparator();
*/
QAction *restartAction = m_systemMenu->addAction(tr("Restart"));
connect(restartAction, SIGNAL(triggered()), this, SLOT(actionLogout()));
QAction *logoutAction = m_systemMenu->addAction(tr("Log Out"));
connect(logoutAction, SIGNAL(triggered()), this, SLOT(actionLogout()));
QAction *shutdownAction = m_systemMenu->addAction(tr("Shut Down"));
connect(shutdownAction, SIGNAL(triggered()), this, SLOT(actionLogout()));
}
void AppMenuWidget::searchEditingDone()
{
if (m_searchMenu && m_searchMenu->actions().count() > 1) {
searchLineEdit->clearFocus();
for (QAction *findCandidateAction : m_searchMenu->actions())
if (!findCandidateAction->isSeparator()) {
m_searchMenu->setActiveAction(findCandidateAction);
break;
}
}
}
void AppMenuWidget::refreshTimer()
{
m_typingTimer->start(300); // https://wiki.qt.io/Delay_action_to_wait_for_user_interaction
}
void AppMenuWidget::focusMenu()
{
QMouseEvent event(QEvent::MouseButtonPress, QPoint(20, 0), m_menuBar->mapToGlobal(QPoint(0, 0)),
Qt::LeftButton, 0, 0);
QApplication::sendEvent(m_menuBar, &event);
searchLineEdit->setFocus();
}
AppMenuWidget::~AppMenuWidget() { }
void AppMenuWidget::integrateSystemMenu(QMenuBar *menuBar)
{
if (!menuBar || !m_systemMenu)
return;
m_searchMenu->setToolTipsVisible(true);
menuBar->addMenu(m_searchMenu);
menuBar->addMenu(m_systemMenu);
}
/*
void AppMenuWidget::handleActivated(const QString &name) {
m_appMenuModel->execute(name);
searchLineEdit->clear();
m_searchMenu->close();
}*/
void AppMenuWidget::updateActionSearch()
{
/*
/// Update the action search.
actionSearch->clear();
actionSearch->update(menuBar);
/// Update completer
if(actionCompleter) {
actionCompleter->deleteLater();
}
actionCompleter = new QCompleter(m_appMenuModel,this);
connect(actionCompleter,
QOverload<const QString &>::of(&QCompleter::activated),
this,
&AppMenuWidget::handleActivated);
actionCompleter->setCompletionColumn(0);
actionCompleter->setCompletionRole(Qt::UserRole+2);
actionCompleter->setCompletionMode(QCompleter::PopupCompletion);
// TODO: https://stackoverflow.com/a/33790639
// We could customize more aspects of the list view of the completer by
//setting the CompletionMode to InlineCompletion, so there will be no popup.
// Then make your QListView independent of the QLineEdit;
// just react to signals that indicate when a view types some text,...
KWindowSystem::setType(actionCompleter->popup()->winId(), NET::DropdownMenu);
//actionCompleter->popup()->setObjectName("actionCompleterPopup");
// static_cast<QListView *>(actionCompleter->popup())->setSpacing(10);
// static_cast<QListView *>(actionCompleter->popup())->setUniformItemSizes(true);
// static_cast<QListView *>(actionCompleter->popup())->setContentsMargins(10,10,0,10); // FIXME:
Does not seem to work, why?
// Empty search field on selection of an item, https://stackoverflow.com/a/11905995
//QObject::connect(actionCompleter, SIGNAL(activated(const QString&)),
// searchLineEdit, SLOT(clear()),
// Qt::QueuedConnection);
*/
// Make more than 7 items visible at once
// actionCompleter->setMaxVisibleItems(35);
// compute needed width
// const QAbstractItemView * popup = actionCompleter->popup();
// actionCompleter->popup()->setMinimumWidth(350);
// actionCompleter->popup()->setMinimumWidth(600);
// actionCompleter->popup()->setContentsMargins(100,100,100,100);
// Make the completer match search terms in the middle rather than just those at the beginning
// of the menu
// actionCompleter->setCaseSensitivity(Qt::CaseInsensitive);
// actionCompleter->setFilterMode(Qt::MatchContains);
// Set first result active; https://stackoverflow.com/q/17782277. FIXME: This does not work yet.
// Why?
// QItemSelectionModel* sm = new QItemSelectionModel(actionCompleter->completionModel());
// actionCompleter->popup()->setSelectionModel(sm);
// sm->select(actionCompleter->completionModel()->index(0,0), QItemSelectionModel::Select);
// auto* flt = new AutoSelectFirstFilter(searchLineEdit);
// actionCompleter->popup()->installEventFilter(flt);
// actionCompleter->popup()->setAlternatingRowColors(false);
// actionCompleter->popup()->setStyleSheet("QListView::item { color: green; }"); // FIXME: Does
// not work. Why?
// searchLineEdit->setCompleter(actionCompleter);
// Sort results of the Action Search
// actionCompleter->completionModel()->sort(0,Qt::SortOrder::AscendingOrder);
}
void AppMenuWidget::searchMenu()
{
QString searchString = searchLineEdit->text();
for (QAction *sr : qAsConst(searchResults)) {
if (m_searchMenu->actions().contains(sr)) {
m_searchMenu->removeAction(sr);
CloneAction *ca = qobject_cast<CloneAction *>(sr);
if (ca) {
ca->resetOrigShortcutContext();
ca->disconnectOnClear();
}
}
}
QMimeDatabase mimeDatabase;
if (searchString.startsWith("= ")) {
QString result = m_menuQCalc->getResult(searchString.remove(0, 1).trimmed(), true);
QIcon icon = QIcon::fromTheme("accessories-calculator");
QAction *res = new QAction(result);
res->setIcon(icon);
res->setIconVisibleInMenu(true);
m_searchMenu->addAction(res);
searchResults << res;
qDebug() << result;
return;
}
// Only initialize fscompleter if searchstring hints a path;
if (searchString.startsWith("/") || searchString == "~") {
if (searchString == "~") {
searchLineEdit->setText(QDir::homePath() + "/");
searchLineEdit->textChanged(QDir::homePath() + "/");
return;
}
QString dirPath = searchString.mid(0, searchString.lastIndexOf("/") + 1);
qDebug() << dirPath << __LINE__;
if (QFileInfo(dirPath).isDir()) {
QFileInfo fInfo = QFileInfo(dirPath);
if (fInfo.exists() && fInfo.isDir()) {
QDir dir(dirPath);
m_searchMenu->addSeparator();
foreach (QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllDirs)) {
if (info.isDir()) {
if (info.fileName().startsWith(
searchString.mid(searchString.lastIndexOf("/"), -1)
.remove(0, 1))) {
QAction *res = new QAction(info.fileName());
// Folder icon
QIcon icon = QIcon::fromTheme("folder");
res->setIcon(icon);
res->setIconVisibleInMenu(true);
res->setProperty("path", info.filePath());
connect(res, &QAction::triggered, this, [this, res] {
openPath(res);
searchLineEdit->setText("");
emit searchLineEdit->textChanged("");
m_searchMenu->close();
});
m_searchMenu->addAction(res);
searchResults << res;
}
}
}
}
}
return;
}
// If the search first word is found on the $PATH, use it like a launcher does
// TODO: Only do this if we have NOT found applications with the same name
// Check whether it is on the $PATH and is executable
if (searchString != "") {
QString mathRes = m_menuQCalc->getResult(searchString, false);
if (mathRes != "") {
QIcon icon = QIcon::fromTheme("accessories-calculator");
QAction *res = new QAction(mathRes);
res->setIcon(icon);
res->setIconVisibleInMenu(true);
m_searchMenu->addAction(res);
searchResults << res;
}
QString command = searchString.split(" ").first();
QString pathEnv = getenv("PATH");
QStringList directories = pathEnv.split(":");
bool found = false;
for (const QString &directory : directories) {
QFile file(directory + "/" + command);
if (file.exists() && (file.permissions() & QFileDevice::ExeUser)) {
found = true;
break;
}
}
if (found) {
qDebug() << command << "found on the $PATH";
m_searchMenu->addSeparator();
QAction *res = new QAction();
res->setText(searchString);
res->setToolTip(searchString);
QIcon icon = QIcon::fromTheme("terminal");
res->setIcon(icon);
res->setIconVisibleInMenu(true);
res->setProperty("path", searchString);
connect(res, &QAction::triggered, this, [this, res] {
QProcess p;
p.setProgram("launch");
QString path = res->property("path").toString();
QStringList arguments = QProcess::splitCommand(path);
bool isGraphical = false;
// With ldd, check whether the first argument is a graphical application
if (arguments.size() > 0) {
QProcess ldd;
ldd.setProcessChannelMode(QProcess::MergedChannels);
ldd.setProgram("ldd");
// Find arguments.first() on the $PATH
QString pathEnv = getenv("PATH");
QStringList directories = pathEnv.split(":");
bool found = false;
for (const QString &directory : directories) {
QFile file(directory + "/" + arguments.first());
if (file.exists() && (file.permissions() & QFileDevice::ExeUser)) {
found = true;
arguments[0] = file.fileName();
break;
}
}
ldd.setArguments({arguments.first()});
ldd.start();
ldd.waitForFinished();
QString lddOutput = ldd.readAllStandardOutput();
if (lddOutput.contains("libxcb.so.1") || lddOutput.contains("libfontconfig.so.1")) {
qDebug() << "Graphical application";
isGraphical = true;
} else {
qDebug() << "Not a graphical application";
}
}
// If it is not a graphical application, then run it in a terminal
if (!isGraphical) {
arguments.prepend("-e");
arguments.prepend("QTerminal"); // FIXME: Would be nice to keep it open;
// https://github.com/lxqt/qterminal/issues/1030
}
qDebug() << "Executing:" << p.program(), p.arguments();
p.setArguments(arguments);