File: solid-hardware.cpp

package info (click to toggle)
solid 5.78.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,100 kB
  • sloc: cpp: 21,549; xml: 464; lex: 111; yacc: 83; sh: 14; makefile: 5
file content (446 lines) | stat: -rw-r--r-- 15,166 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
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
/*  This file is part of the KDE project
    SPDX-FileCopyrightText: 2006 Kevin Ottens <ervin@kde.org>
    SPDX-FileCopyrightText: 2014 Alejandro Fiestas Olivares <afiestas@kde.org>

    SPDX-License-Identifier: LGPL-2.0-only
*/

#include "solid-hardware.h"


#include <QString>
#include <QStringList>
#include <QMetaProperty>
#include <QMetaEnum>
#include <QTextStream>

#include <QCommandLineParser>

#include <solid/device.h>
#include <solid/genericinterface.h>
#include <solid/opticaldrive.h>

#include <iostream>
#include <solid/devicenotifier.h>
using namespace std;

static const char appName[] = "solid-hardware";

static const char version[] = "0.1a";

std::ostream &operator<<(std::ostream &out, const QString &msg)
{
    return (out << msg.toLocal8Bit().constData());
}

std::ostream &operator<<(std::ostream &out, const QVariant &value)
{
    switch (value.type())
    {
    case QVariant::StringList:
    {
        out << "{";

        const QStringList list = value.toStringList();

        QStringList::ConstIterator it = list.constBegin();
        QStringList::ConstIterator end = list.constEnd();

        for (; it!=end; ++it)
        {
            out << "'" << *it << "'";

            if (it+1!=end)
            {
                out << ", ";
            }
        }

        out << "}  (string list)";
        break;
    }
    case QVariant::Bool:
        out << (value.toBool()?"true":"false") << "  (bool)";
        break;
    case QVariant::Int:
    case QVariant::LongLong:
        out << value.toString()
            << "  (0x" << QString::number(value.toLongLong(), 16) << ")  (" << QVariant::typeToName(value.type()) << ")";
        break;
    case QVariant::UInt:
    case QVariant::ULongLong:
        out << value.toString()
            << "  (0x" << QString::number(value.toULongLong(), 16) << ")  (" << QVariant::typeToName(value.type()) << ")";
        break;
    case QVariant::Double:
        out << value.toString() << " (double)";
        break;
    case QVariant::UserType:
    {
        //qDebug() << "got variant type:" << value.typeName();
        if (value.canConvert<QList<int> >())
        {
            const QList<int> intlist = value.value<QList<int>>();
            QStringList tmp;
            for (const int val : intlist) {
                tmp.append(QString::number(val));
            }
            out << "{" << tmp.join(",") << "} (int list)";
        }
        break;
    }
    default:
        out << "'" << value.toString() << "'  (string)";
        break;
    }

    return out;
}

std::ostream &operator<<(std::ostream &out, const Solid::Device &device)
{
    out << "  parent = " << QVariant(device.parentUdi()) << endl;
    out << "  vendor = " << QVariant(device.vendor()) << endl;
    out << "  product = " << QVariant(device.product()) << endl;
    out << "  description = " << QVariant(device.description()) << endl;
    out << "  icon = " << QVariant(device.icon()) << endl;

    int index = Solid::DeviceInterface::staticMetaObject.indexOfEnumerator("Type");
    QMetaEnum typeEnum = Solid::DeviceInterface::staticMetaObject.enumerator(index);

    for (int i=0; i<typeEnum.keyCount(); i++)
    {
        Solid::DeviceInterface::Type type = (Solid::DeviceInterface::Type)typeEnum.value(i);
        const Solid::DeviceInterface *interface = device.asDeviceInterface(type);

        if (interface)
        {
            const QMetaObject *meta = interface->metaObject();

            for (int i=meta->propertyOffset(); i<meta->propertyCount(); i++)
            {
                QMetaProperty property = meta->property(i);
                out << "  " << QString(meta->className()).mid(7) << "." << property.name()
                    << " = ";

                QVariant value = property.read(interface);

                if (property.isEnumType()) {
                    QMetaEnum metaEnum = property.enumerator();
                    if (metaEnum.isFlag()) {
                        out << "'" << metaEnum.valueToKeys(value.toInt()).constData() << "'"
                            << "  (0x" << QString::number(value.toInt(), 16) << ")  (flag)";
                    } else {
                        out << "'" << metaEnum.valueToKey(value.toInt()) << "'"
                            << "  (0x" << QString::number(value.toInt(), 16) << ")  (enum)";
                    }
                    out << endl;
                } else {
                    out << value << endl;
                }
            }
        }
    }

    return out;
}

std::ostream &operator<<(std::ostream &out, const QMap<QString,QVariant> &properties)
{
    for (auto it = properties.cbegin(); it != properties.cend(); ++it) {
        out << "  " << it.key() << " = " << it.value() << endl;
    }

    return out;
}

QString getUdiFromArguments(QCoreApplication &app, QCommandLineParser &parser)
{
    parser.addPositionalArgument("udi", QCoreApplication::translate("solid-hardware", "Device udi"));
    parser.process(app);
    if (parser.positionalArguments().count() < 2) {
        parser.showHelp(1);
    }
    return parser.positionalArguments().at(1);
}

static QString commandsHelp()
{
    QString data;
    QTextStream cout(&data);
    cout << '\n' << QCoreApplication::translate("solid-hardware", "Syntax:") << '\n' << '\n';

    cout << "  solid-hardware list [details|nonportableinfo]" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # List the hardware available in the system.\n"
            "             # - If the 'nonportableinfo' option is specified, the device\n"
            "             # properties are listed (be careful, in this case property names\n"
            "             # are backend dependent),\n"
            "             # - If the 'details' option is specified, the device interfaces\n"
            "             # and the corresponding properties are listed in a platform\n"
            "             # neutral fashion,\n"
            "             # - Otherwise only device UDIs are listed.\n") << '\n';

    cout << "  solid-hardware details 'udi'" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # Display all the interfaces and properties of the device\n"
            "             # corresponding to 'udi' in a platform neutral fashion.\n") << '\n';

    cout << "  solid-hardware nonportableinfo 'udi'" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # Display all the properties of the device corresponding to 'udi'\n"
            "             # (be careful, in this case property names are backend dependent).\n") << '\n';

    cout << "  solid-hardware query 'predicate' ['parentUdi']" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # List the UDI of devices corresponding to 'predicate'.\n"
            "             # - If 'parentUdi' is specified, the search is restricted to the\n"
            "             # branch of the corresponding device,\n"
            "             # - Otherwise the search is done on all the devices.\n") << '\n';

    cout << "  solid-hardware mount 'udi'" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # If applicable, mount the device corresponding to 'udi'.\n") << '\n';

    cout << "  solid-hardware unmount 'udi'" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # If applicable, unmount the device corresponding to 'udi'.\n") << '\n';

    cout << "  solid-hardware eject 'udi'" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # If applicable, eject the device corresponding to 'udi'.\n") << '\n';

    cout << "  solid-hardware listen" << '\n';
    cout << QCoreApplication::translate("solid-hardware",
            "             # Listen to all add/remove events on supported hardware.") << '\n';

    return data;
}

int main(int argc, char **argv)
{
    SolidHardware app(argc, argv);
    app.setApplicationName(appName);
    app.setApplicationVersion(version);

    QCommandLineParser parser;
    parser.setApplicationDescription(QCoreApplication::translate("solid-hardware", "KDE tool for querying your hardware from the command line"));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("command", QCoreApplication::translate("solid-hardware", "Command to execute"), commandsHelp());

    QCommandLineOption commands("commands", QCoreApplication::translate("solid-hardware", "Show available commands"));
    // --commands only for backwards compat, it's now in the "syntax help"
    // of the positional argument.
    commands.setFlags(QCommandLineOption::HiddenFromHelp);
    parser.addOption(commands);

    parser.process(app);
    if (parser.isSet(commands))
    {
        cout << commandsHelp() << endl;
        return 0;
    }

    QStringList args = parser.positionalArguments();
    if (args.count() < 1) {
        parser.showHelp(1);
    }

    parser.clearPositionalArguments();

    QString command(args.at(0));

    if (command == "list")
    {
        parser.addPositionalArgument("details", QCoreApplication::translate("solid-hardware", "Show device details"));
        parser.addPositionalArgument("nonportableinfo", QCoreApplication::translate("solid-hardware", "Show non portable information"));
        parser.process(app);
        args = parser.positionalArguments();
        QByteArray extra(args.count() == 2 ? args.at(1).toLocal8Bit() : "");
        return app.hwList(extra == "details", extra == "nonportableinfo");
    } else if (command == "details") {
        const QString udi = getUdiFromArguments(app, parser);
        return app.hwCapabilities(udi);
    } else if (command == "nonportableinfo") {
        const QString udi = getUdiFromArguments(app, parser);
        return app.hwProperties(udi);
    } else if (command == "query") {
        parser.addPositionalArgument("udi", QCoreApplication::translate("solid-hardware", "Device udi"));
        parser.addPositionalArgument("parent", QCoreApplication::translate("solid-hardware", "Parent device udi"));
        parser.process(app);
        if (parser.positionalArguments().count() < 2 || parser.positionalArguments().count() > 3) {
            parser.showHelp(1);
        }

        QString query = args.at(1);
        QString parent;

        if (args.count() == 3)
        {
            parent = args.at(2);
        }

        return app.hwQuery(parent, query);
    } else if (command == "mount") {
        const QString udi = getUdiFromArguments(app, parser);
        return app.hwVolumeCall(SolidHardware::Mount, udi);
    } else if (command == "unmount") {
        const QString udi = getUdiFromArguments(app, parser);
        return app.hwVolumeCall(SolidHardware::Unmount, udi);
    } else if (command == "eject") {
        const QString udi = getUdiFromArguments(app, parser);
        return app.hwVolumeCall(SolidHardware::Eject, udi);
    } else if (command == "listen") {
        return app.listen();
    }

    cerr << QCoreApplication::translate("solid-hardware", "Syntax Error: Unknown command '%1'").arg(command) << endl;

    return 1;
}

bool SolidHardware::hwList(bool interfaces, bool system)
{
    const QList<Solid::Device> all = Solid::Device::allDevices();

    for (const Solid::Device &device : all)
    {
        cout << "udi = '" << device.udi() << "'" << endl;

        if (interfaces)
        {
            cout << device << endl;
        }
        else if (system && device.is<Solid::GenericInterface>())
        {
            QMap<QString,QVariant> properties = device.as<Solid::GenericInterface>()->allProperties();
            cout << properties << endl;
        }
    }

    return true;
}

bool SolidHardware::hwCapabilities(const QString &udi)
{
    const Solid::Device device(udi);

    cout << "udi = '" << device.udi() << "'" << endl;
    cout << device << endl;

    return true;
}

bool SolidHardware::hwProperties(const QString &udi)
{
    const Solid::Device device(udi);

    cout << "udi = '" << device.udi() << "'" << endl;
    if (device.is<Solid::GenericInterface>()) {
        QMap<QString,QVariant> properties = device.as<Solid::GenericInterface>()->allProperties();
        cout << properties << endl;
    }

    return true;
}

bool SolidHardware::hwQuery(const QString &parentUdi, const QString &query)
{
    const QList<Solid::Device> devices
        = Solid::Device::listFromQuery(query, parentUdi);

    for (const Solid::Device &device : devices) {
        cout << "udi = '" << device.udi() << "'" << endl;
    }

    return true;
}

bool SolidHardware::hwVolumeCall(SolidHardware::VolumeCallType type, const QString &udi)
{
    Solid::Device device(udi);

    if (!device.is<Solid::StorageAccess>() && type!=Eject)
    {
        cerr << tr("Error: %1 does not have the interface StorageAccess.").arg(udi) << endl;
        return false;
    }
    else if (!device.is<Solid::OpticalDrive>() && type==Eject)
    {
        cerr << tr("Error: %1 does not have the interface OpticalDrive.").arg(udi) << endl;
        return false;
    }

    switch(type)
    {
    case Mount:
        connect(device.as<Solid::StorageAccess>(),
                SIGNAL(setupDone(Solid::ErrorType,QVariant,QString)),
                this,
                SLOT(slotStorageResult(Solid::ErrorType,QVariant)));
        device.as<Solid::StorageAccess>()->setup();
        break;
    case Unmount:
        connect(device.as<Solid::StorageAccess>(),
                SIGNAL(teardownDone(Solid::ErrorType,QVariant,QString)),
                this,
                SLOT(slotStorageResult(Solid::ErrorType,QVariant)));
        device.as<Solid::StorageAccess>()->teardown();
        break;
    case Eject:
        connect(device.as<Solid::OpticalDrive>(),
                SIGNAL(ejectDone(Solid::ErrorType,QVariant,QString)),
                this,
                SLOT(slotStorageResult(Solid::ErrorType,QVariant)));
        device.as<Solid::OpticalDrive>()->eject();
        break;
    }

    m_loop.exec();

    if (m_error)
    {
        cerr << tr("Error: %1").arg(m_errorString) << endl;
        return false;
    }

    return true;
}

bool SolidHardware::listen()
{
    Solid::DeviceNotifier *notifier = Solid::DeviceNotifier::instance();
    bool a = connect(notifier, SIGNAL(deviceAdded(QString)), this, SLOT(deviceAdded(QString)));
    bool d = connect(notifier, SIGNAL(deviceRemoved(QString)), this, SLOT(deviceRemoved(QString)));

    if (!a || !d) {
        return false;
    }

    cout << "Listening to add/remove events: " << endl;
    m_loop.exec();
    return true;
}

void SolidHardware::deviceAdded(const QString &udi)
{
    cout << "Device Added:" << endl;
    cout << "udi = '" << udi << "'" << endl;
}

void SolidHardware::deviceRemoved(const QString &udi)
{
    cout << "Device Removed:" << endl;
    cout << "udi = '" << udi << "'" << endl;
}

void SolidHardware::slotStorageResult(Solid::ErrorType error, const QVariant &errorData)
{
    if (error) {
        m_error = 1;
        m_errorString = errorData.toString();
    }
    m_loop.exit();
}