-
Notifications
You must be signed in to change notification settings - Fork 3
/
qmenu_hud.cpp
434 lines (387 loc) · 12.2 KB
/
qmenu_hud.cpp
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
#include <iostream>
#include <cstdio> //perror
#include <QCoreApplication>
#include <QtDebug>
#include <QKeySequence>
#ifndef NDEBUG
#include <QFile>
#include <QTextStream>
#endif
// generated by cmake from projectConfig.h.in
#include "projectConfig.h"
// generated by cmake qt6_add_dbus_interface
#include "app_menu.h"
#include "dbus_menu.h"
typedef com::canonical::AppMenu::Registrar AppMenu;
typedef com::canonical::dbusmenu DBusMenu;
#include "gtk_action.h"
#include "gtk_menu.h"
typedef org::gtk::Actions GtkAction;
typedef org::gtk::Menus GtkMenu;
#define REGISTRAR_SERVICE "com.canonical.AppMenu.Registrar"
#define REGISTRAR_PATH "/com/canonical/AppMenu/Registrar"
#include <X11/Xlib.h>
#include "dbusmenushortcut_p.h"
#if 0
#ifndef NDEBUG
void file_logger(QtMsgType type, const char *msg){
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
abort();
}
QFile outFile("/tmp/qmenu_hud.log"); //FIXME: don't use hardcoded path
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << txt << endl;
}
#else
void devnull_logger(QtMsgType type, const char *msg){
}
#endif
#endif
void inspect(int width, const DBusMenuLayoutItem &topItem, QString &path, QMap<QString,int> &menuMap){
QString label;
for(const DBusMenuLayoutItem &item : topItem.children){
label = item.properties.value("label").toString().remove("_");
if(!item.children.isEmpty()){
QString subPath(path);
subPath.append(label);
subPath.append(" > ");
inspect(width, item, subPath, menuMap);
}else{
// leaf
if(!label.isEmpty()){
//qDebug() << item.properties << '\n';
QString str = QString("%1").arg(path + label, -width);
if(item.properties.contains(QString("toggle-state"))
&& item.properties.contains(QString("toggle-type"))
){
QString toggle_type = item.properties.value("toggle-type").toString();
if(toggle_type == "checkmark"){
if(item.properties.value("toggle-state").toInt() == 1){
str += "[x]";
}else{
str += "[ ]";
}
}else if(toggle_type == "radio"){
if(item.properties.value("toggle-state").toInt() == 1){
str += "(o)";
}else{
str += "( )";
}
}else{
qDebug() << "unknown toggle type: " << toggle_type;
str += "{?}";
}
}else{
str += " ";
}
if(item.properties.contains(QString("shortcut"))){
DBusMenuShortcut s = qdbus_cast<DBusMenuShortcut>(item.properties.value("shortcut").value<QDBusArgument>());
str += " " + s.toKeySequence().toString();
}
//qDebug() << path << label << " ::: " << item.id;
menuMap.insert(str, item.id);
}
}
}
}
void gtk(unsigned char *dbusname, unsigned char *menubarpath, int lines){
// gtk changed its model to something else, doing everything again is always fun...
// even worse: the dbus interface is an implementation detail and can change any minute, fun as hell
GtkMenuTypes_register();
SillyList list;
for(int i=0; i<1024; ++i){
list.append(i);
}
GtkMenu *gtkMenu = new GtkMenu((const char*)dbusname, (const char*)menubarpath, QDBusConnection::sessionBus());
GtkAction *gtkAction = new GtkAction((const char*)dbusname, (const char*)menubarpath, QDBusConnection::sessionBus());
QDBusPendingReply<GtkMenuEntryList> start_reply = gtkMenu->Start(list);
start_reply.waitForFinished();
if(start_reply.isError()){
puts("Start failed");
exit(-1);
}
// start needs to run before
QDBusPendingReply<GtkMenuDescMap> reply_descall = gtkAction->DescribeAll();
reply_descall.waitForFinished();
if(reply_descall.isError()){
puts("DescribeAll failed");
exit(-1);
}
GtkMenuDescMap descs = reply_descall.argumentAt<0>();
QMap<uint64_t,QPair<QString,bool>> submenus; // submenus with their prefix and if enabled
QMap<QString,QString> entries;
GtkMenuEntryList menus = start_reply.argumentAt<0>();
for(const GtkMenuEntry &e : menus){
for(const auto &m : e.entry){
QString prefix;
bool enabled = true;
auto itsub = submenus.find((((uint64_t)e.first)<<32) | e.second);
if(itsub != submenus.end()){
prefix = itsub->first;
enabled = itsub->second;
}
auto itlabel = m.find("label");
if(itlabel != m.end()){
if(!prefix.isEmpty()){
prefix += " > ";
}
prefix += itlabel->toString();
}
auto itsubmenu = m.find(":submenu");
if(itsubmenu == m.end()){// there's also ":section" as silly inner node
itsubmenu = m.find(":section");
}
if(itsubmenu != m.end()){ // has submenu
auto itaction = m.find("action");
if(itaction != m.end()){
QString action = itaction->toString().remove("unity.");
auto itdesc = descs.find(action);
if(itdesc != descs.end()){
if(!itdesc->enabled){
enabled = false;
}
}
}
QDBusArgument dbusarg = itsubmenu->value<QDBusArgument>();
SimplePair sp;
dbusarg >> sp;
submenus.insert((((uint64_t)sp.first)<<32) | sp.second, qMakePair(prefix,enabled));
}else{
// leaf
auto itaction = m.find("action");
if(itaction != m.end()){
QString action = itaction->toString().remove("unity.");
auto itdesc = descs.find(action);
if(itdesc != descs.end()){
if(itdesc->enabled && enabled){
entries.insert(prefix.remove("_"), action);
}
}
}
}
}
}
// call dmenu -i -l 20
QStringList args;
args << "-i" << "-l" << QString::number(lines);
QProcess *proc = new QProcess();
proc->start(DMENU_PATH, args);
proc->waitForStarted();
// write all entries to dmenu's stdin
for(QString &key : entries.keys()){
proc->write(key.toLocal8Bit().data());
proc->write("\n");
}
proc->closeWriteChannel();
proc->waitForFinished(-1);
// read selected entry from dmenu's stdout
QString selected = QString::fromLocal8Bit(proc->readAllStandardOutput()).remove("\n");
proc->close();
delete proc;
if(!selected.isEmpty()){ // empty when canceled with esc
QString action = entries[selected];
QDBusPendingReply<void> reply = gtkAction->Activate(action, {}, {});
reply.waitForFinished();
if (reply.isError()) {
qDebug() << "Activate failed with action: " << action;
}
}
delete gtkMenu;
delete gtkAction;
}
void appmenu(unsigned long int winID, int lines, int width){
DBusMenuTypes_register();
// get dbus service of the application which exports menu
AppMenu *appMenu = new AppMenu(REGISTRAR_SERVICE, REGISTRAR_PATH, QDBusConnection::sessionBus());
QDBusPendingReply<QString, QDBusObjectPath> reply = appMenu->GetMenuForWindow(winID);
reply.waitForFinished();
if (reply.isError()) {
delete appMenu;
if(reply.error().type() == QDBusError::Failed){
// window not registered/unknown to registrar
// let the user know by showing it in dmenu
QProcess *proc = new QProcess();
proc->start(DMENU_PATH, QStringList());
proc->waitForStarted();
proc->write("no menu entries exported\n");
proc->closeWriteChannel();
proc->waitForFinished();
delete proc;
exit(0);
}else{
// something else
qDebug() << reply.error().name();
qDebug() << reply.error().message();
exit(-1);
}
}
QString dbus_service = reply.argumentAt<0>();
QString dbus_path = reply.argumentAt<1>().path();
// get menu
DBusMenu *dbusMenu = new DBusMenu(dbus_service, dbus_path, QDBusConnection::sessionBus());
QDBusPendingReply <uint, DBusMenuLayoutItem> topItems = dbusMenu->GetLayout(0, -1, QStringList());
topItems.waitForFinished();
if (topItems.isError()) {
qDebug() << topItems.error().name();
qDebug() << topItems.error().message();
exit(-1);
}
// traverse through all submenus
QString path;
QMap<QString, int> menuMap;
for(const DBusMenuLayoutItem &topLevel : topItems.argumentAt<1>().children){
path.append(topLevel.properties.value("label").toString().remove("_"));
path.append(" > ");
inspect(width, topLevel, path, menuMap);
path.clear();
}
// call dmenu -i -l 20
QStringList args;
args << "-i" << "-l" << QString::number(lines);
QProcess *proc = new QProcess();
proc->start(DMENU_PATH, args);
proc->waitForStarted();
// write all entries to dmenu's stdin
for(QString &key : menuMap.keys()){
proc->write(key.toLocal8Bit().data());
proc->write("\n");
}
proc->closeWriteChannel();
proc->waitForFinished(-1);
// read selected entry from dmenu's stdout
QString selected = QString::fromLocal8Bit(proc->readAllStandardOutput()).remove("\n");
proc->close();
delete proc;
if(!selected.isEmpty()){ // empty when canceled with esc
int id = menuMap[selected];
// send menu click event
QDBusVariant empty;
empty.setVariant(QVariant::fromValue<QString>(QString()));
QDBusPendingReply<void> clicked_r = dbusMenu->Event(id, "clicked", empty, QDateTime::currentDateTime().toSecsSinceEpoch());
if(clicked_r.isError()){
qDebug() << clicked_r.error().message();
qDebug() << clicked_r.error().name();
}
}
delete dbusMenu;
delete appMenu;
}
int main(int argc, char **argv){
QCoreApplication app(argc, argv);
#if 0
#ifndef NDEBUG
qInstallMsgHandler(file_logger);
#else
//HACK: get rid of QDBusSignature: invalid signature ""
// probably a bad idea
qInstallMsgHandler(devnull_logger);
#endif
#endif
// handle arguments
QCommandLineParser parser;
parser.setApplicationDescription("menu search program");
parser.addHelpOption();
parser.addOptions({
{"l", "number of lines in dmenu, default: 20", "lines"},
{"w", "width of menu entries, default: 150", "width"},
{"i", "window id, default: get currently focused window", "winid"}
});
parser.process(app);
int lines=20, width=150;
if(parser.isSet("l")){
bool ok;
lines = parser.value("l").toInt(&ok);
if(!ok){
qDebug() << "couldn't convert number of lines: " << parser.value("l");
return -1;
}
}
if(parser.isSet("w")){
bool ok;
width = parser.value("w").toInt(&ok);
if(!ok){
qDebug() << "couldn't convert width: " << parser.value("w");
return -1;
}
}
//std::cout << "lines: " << lines << "\nwidth: " << width << '\n';
unsigned long int winID;
Display *display = XOpenDisplay(NULL);
if(parser.isSet("i")){
// got window id as argument
bool ok;
//winID = arg.toULong(&ok, 0);
winID = parser.value("i").toULong(&ok, 0);
if(!ok){
qDebug() << "couldn't convert window id: " << parser.value("i");
return -1;
}
}else{
// get window (id) which has currently the focus
if(!display){
perror("XOpenDisplay failed");
return -1;
}
Window window;
int ret;
// not working for gtk, surprise...
// gtk sets focus on a child window, not the toplevel, for whatever reason
// XGetInputFocus(display, &window, &ret);
// winID = window;
// read active window from root window, assuming wm supports this
// oh so much fun... thx gtk
window = XDefaultRootWindow(display);
Atom property = XInternAtom(display, "_NET_ACTIVE_WINDOW", True);
if(property==None) return -1;
Atom actual_type_return;
int actual_format_return;
unsigned long nitems_return, bytes_after_return;
unsigned char *activewin;
ret = XGetWindowProperty(
display, window, property, 0, 1024, False, AnyPropertyType,
&actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &activewin
);
winID = *(unsigned long *)activewin;
// qDebug() << "winId: " << winID;
}
//FIXME: error check
unsigned char *dbusname=nullptr, *menubarpath=nullptr;
Atom property = XInternAtom(display, "_GTK_UNIQUE_BUS_NAME", True);
if(property != None){
Atom actual_type_return;
int actual_format_return;
unsigned long nitems_return, bytes_after_return;
XGetWindowProperty(
display, winID, property, 0, 1024, False, AnyPropertyType,
&actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &dbusname
);
property = XInternAtom(display, "_GTK_MENUBAR_OBJECT_PATH", True);
XGetWindowProperty(
display, winID, property, 0, 1024, False, AnyPropertyType,
&actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &menubarpath
);
}
if(dbusname && menubarpath){
// qDebug() << "dbusname: " << dbusname << "; path: " << menubarpath;
gtk(dbusname, menubarpath, lines);
XFree(dbusname);
XFree(menubarpath);
}else{
appmenu(winID, lines, width);
}
XCloseDisplay(display);
return 0;
}