summaryrefslogtreecommitdiff
path: root/resourceqt-client/client.cpp
blob: 5f1875b1fb689d5f48e3d70a30d72f5988f087ba (plain)
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
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>

#include "client.h"

using namespace ResourcePolicy;

Client::Client(QString appClass) : QObject()
{
    applicationClass 	= appClass;
    resourceSet			= NULL;

    standardInput = new QTextStream(stdin, QFile::ReadOnly);
    mainTimerID   = startTimer(0);
}

Client::~Client()
{
    killTimer(mainTimerID);

    if (resourceSet != NULL) {
        delete resourceSet;
        resourceSet = NULL;
    }

    if (standardInput != NULL) {
        delete standardInput;
        standardInput = NULL;
    }
}

uint32_t Client::parseResourceList(QString resourceListStr)
{
    struct {
        uint32_t	resourceType;
        const char*	resourceName;
    }
    resourceDef[] = {
        { RES_AUDIO_PLAYBACK ,  "AudioPlayback"  },
        { RES_VIDEO_PLAYBACK ,  "VideoPlayback"  },
        { RES_AUDIO_RECORDING,  "AudioRecording" },
        { RES_VIDEO_RECORDING,  "VideoRecording" },
        { RES_VIBRA          ,  "Vibra"          },
        { RES_LEDS           ,  "Leds"           },
        { RES_BACKLIGHT      ,  "BackLight"      },
        { RES_SYSTEM_BUTTON  ,  "SystemButton"   },
        { RES_LOCK_BUTTON    ,  "LockButton"     },
        { RES_SCALE_BUTTON   ,  "ScaleButton"    },
        { RES_SNAP_BUTTON    ,  "SnapButton"     },
        { RES_LENS_COVER     ,  "LensCover"      },
        { RES_HEADSET_BUTTONS,  "HeadsetButtons" },
        {        0           ,       NULL        }
    };

    uint32_t  resourceList = 0;

    if (resourceListStr.isEmpty() || resourceListStr.isNull()) {
        return 0;
    }
    else {
        QStringList resList = resourceListStr.split(",", QString::SkipEmptyParts);

        for (int i = 0; i < resList.count(); i++) {
            int pos = 0;
            while (resourceDef[pos].resourceName != NULL) {
                if (resList[i] == resourceDef[pos].resourceName)
                    break;

                pos++;
            }

            if (!resourceDef[pos].resourceName) {
                const char* res = qPrintable(resList[i]);
                printf("Ignoring invalid resource name '%s'\n", res);
            }
            else {
                resourceList |= resourceDef[pos].resourceType;
            }
        }
    }

    return resourceList;
}

void Client::showPrompt()
{
    printf("res-client> ");
    fflush(stdout);
}

void Client::updateSet(uint32_t list, uint32_t optional, bool remove)
{
    uint32_t resources[] = {
        RES_AUDIO_PLAYBACK, RES_VIDEO_PLAYBACK, RES_AUDIO_RECORDING, RES_VIDEO_RECORDING,
        RES_VIBRA, RES_LEDS, RES_BACKLIGHT, RES_SYSTEM_BUTTON, RES_LOCK_BUTTON,
        RES_SCALE_BUTTON, RES_SNAP_BUTTON, RES_LENS_COVER, RES_HEADSET_BUTTONS, 0
    };

    int pos = 0;
    while (resources[pos]) {
        if ((list & resources[pos]) == resources[pos]) {
            Resource* resource = NULL;
            ResourceType res = getResourceType(resources[pos]);
            bool opt = (optional & resources[pos]) == resources[pos];

            if (remove) {
                if (!resourceSet->contains(res)) {
                    continue;
                }

                if (optional) {
                    resource = resourceSet->resource(res);
                    resource->setOptional(false);
                }
                else {
                    resourceSet->deleteResource(res);
                }
            }
            else {
                if (resourceSet->contains(res)) {
                    resource = resourceSet->resource(res);
                    if (resource->isOptional() != opt) {
                        resource->setOptional(opt);
                    }

                    continue;
                }

                resource = allocateResource(res, opt);
                if (resource) {
                    resourceSet->addResourceObject(resource);
                }
            }
        }

        pos++;
    }
}

bool Client::initialize(uint32_t all, uint32_t optional, bool alwaysReply, bool autoRelease)
{
    resourceSet = new ResourceSet(applicationClass);
    if (resourceSet == NULL) {
        return false;
    }

    if (alwaysReply) {
        qDebug("client: alwaysReply");
        resourceSet->setAlwaysReply();
    }

    if (autoRelease) {
        qDebug("client: autoRelease");
        resourceSet->setAutoRelease();
    }

    updateSet(all, optional, false);

    if (!connect(resourceSet, SIGNAL(resourcesGranted(QList<ResourcePolicy::ResourceType>)),
                 this, SLOT(resourceAcquiredHandler(QList<ResourcePolicy::ResourceType>))))
    {
        return false;
    }

    if (!connect(resourceSet, SIGNAL(resourcesDenied()), this, SLOT(resourceDeniedHandler()))) {
        return false;
    }

    if (!connect(resourceSet, SIGNAL(lostResources()), this, SLOT(resourceLostHandler()))) {
        return false;
    }
    connect(resourceSet, SIGNAL(resourcesReleased()), this, SLOT(resourceReleasedHandler()));

    connect(resourceSet, SIGNAL(resourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &)),
            this, SLOT(resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &)));

    showPrompt();

    return true;
}

Resource* Client::allocateResource(ResourceType resource, bool optional)
{
    Resource* retValue = NULL;

    switch (resource) {
    case AudioPlaybackType:
        retValue = new AudioResource();
        break;
    case VideoPlaybackType:
        retValue = new VideoResource();
        break;
    case AudioRecorderType:
        retValue = new AudioRecorderResource();
        break;
    case VideoRecorderType:
        retValue = new VideoRecorderResource();
        break;
    case VibraType:
        retValue = new VibraResource();
        break;
    case LedsType:
        retValue = new LedsResource();
        break;
    case BacklightType:
        retValue = new BacklightResource();
        break;
    case SystemButtonType:
        retValue = new SystemButtonResource();
        break;
    case LockButtonType:
        retValue = new LockButtonResource();
        break;
    case ScaleButtonType:
        retValue = new ScaleButtonResource();
        break;
    case SnapButtonType:
        retValue = new SnapButtonResource();
        break;
    case LensCoverType:
        retValue = new LensCoverResource();
        break;
    case HeadsetButtonsType:
        retValue = new HeadsetButtonsResource();
        break;
    case NumberOfTypes:
        return NULL;
    }

    if (retValue) {
        retValue->setOptional(optional);
    }
    else {
        printf("Unknown resource type - %d\n", resource);
    }

    return retValue;
}

ResourceType Client::getResourceType(uint32_t resource)
{
    switch (resource) {
    case RES_AUDIO_PLAYBACK:
        return AudioPlaybackType;
    case RES_VIDEO_PLAYBACK:
        return VideoPlaybackType;
    case RES_AUDIO_RECORDING:
        return AudioRecorderType;
    case RES_VIDEO_RECORDING:
        return VideoRecorderType;
    case RES_VIBRA:
        return VibraType;
    case RES_LEDS:
        return LedsType;
    case RES_BACKLIGHT:
        return BacklightType;
    case RES_SYSTEM_BUTTON:
        return SystemButtonType;
    case RES_LOCK_BUTTON:
        return LockButtonType;
    case RES_SCALE_BUTTON:
        return ScaleButtonType;
    case RES_SNAP_BUTTON:
        return SnapButtonType;
    case RES_LENS_COVER:
        return LensCoverType;
    case RES_HEADSET_BUTTONS:
        return HeadsetButtonsType;
    }

    return NumberOfTypes;
}

void Client::showResources(const QList<ResourceType> resList)
{
    const char* resTypes[] = {
        "AudioPlayback", "VideoPlayback", "AudioRecorder", "VideoRecorder", "Vibra",
        "Leds", "Backlight", "SystemButton", "LockButton", "ScaleButton", "SnapButton",
        "LensCover", "HeadsetButtons"
    };

    for (int i = 0; i < resList.count(); i++) {
        printf("\t%s\n", resTypes[resList[i]]);
    }
}

void Client::showResources(const QList<Resource*> resList)
{
    const char* resTypes[] = {
        "AudioPlayback", "VideoPlayback", "AudioRecorder", "VideoRecorder", "Vibra",
        "Leds", "Backlight", "SystemButton", "LockButton", "ScaleButton", "SnapButton",
        "LensCover", "HeadsetButtons"
    };

    for (int i = 0; i < resList.count(); i++) {
        Resource* r = resList[i];
        printf("\t%s%s%s\n", resTypes[r->type()],
               r->isOptional() ? " (optional)" : "",
               r->isGranted() ? " (granted)" : "");
    }
}

void Client::resourceAcquiredHandler(const QList<ResourceType>& /*grantedResList*/)
{
    if( timeStat.markEnd() ) {
        timeStat.report("\nOperation took %.2f ms\n");
    }

    QList<Resource*> list = resourceSet->resources();
    if (!list.count()) {
        printf("\nGranted resource set is empty. Possible bug?\n");
    }
    else {
        printf("\nManager grants access to these resources:\n");
        printf("Resource set:\n");
        showResources(list);
    }
    showPrompt();
}

void Client::resourceDeniedHandler()
{
    if( timeStat.markEnd() ) {
        timeStat.report("\nOperation took %.2f ms\n");
    }

    printf("\nManager denies access to resources!\n");
    showPrompt();
}

void Client::resourceLostHandler()
{
    if( timeStat.markEnd() ) {
        timeStat.report("\nOperation took %.2f ms\n");
    }

    printf("\nLost resources from manager!\n");
    showPrompt();
}

void Client::resourceReleasedHandler()
{
    if( timeStat.markEnd() ) {
        timeStat.report("\nOperation took %.2f ms\n");
    }

    printf("\nAll resources released\n");
    showPrompt();
}

void Client::resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &availableResources)
{
    printf("\nManager advice: These resources are available:\n");
    printf("Resource set:\n");
    showResources(availableResources);
    showPrompt();
}

void Client::timerEvent(QTimerEvent*)
{
    bool quitFlag = false;

    fd_set stdinfd;
    FD_ZERO(&stdinfd);
    FD_SET(0, &stdinfd);
    timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 0;

    int ready = select(1, &stdinfd, NULL, NULL, &tv);
    if (ready > 0) {
        QString line = standardInput->readLine();
        if (!line.isNull()) {
            QStringList params = line.split(" ");
            if (params[0] == "quit") {
                quitFlag = true;
                QMetaObject::invokeMethod(QCoreApplication::instance(), "quit");
            }
            else if (params[0] == "help") {
                printf("Available commands:\n");
                printf("\t  help   \tprint this help message\n");
                printf("\t  quit   \texit application\n");
                printf("\t  free   \tdestroy and free the resources\n");
                printf("\t  acquire\tacquire required resources\n");
                printf("\t  release\trelease resources\n");
                printf("\t  update\tupdate modified resource set after add or remove command\n");
                printf("\t  add reslist [-o]\tadd reosurce list, if -o provided, set as optional\n");
                printf("\t  remove reslist [-o]\tremove reosurce list, if -o provided, removed only optional flag\n");
                printf("\t  audio pid <pid> | group <audio group> | tag <name> <value>\tset audio properties\n");
                printf("\t  addaudio <audio group> <pid> <tag name> <tag value>\n");
                printf("\t  show  \tshow resources\n");
            }
            else if (params[0] == "show") {
                if (!resourceSet) {
                    printf("Show failed!\n");
                }
                else {
                    QList<Resource*> list = resourceSet->resources();
                    if (!list.count()) {
                        printf("Resource set is empty, use add command to add some ...\n");
                    }
                    else {
                        printf("Resource set:\n");
                        showResources(list);
                    }
                }
            }
            else if (params[0] == "acquire") {
                timeStat.markStart();
                if (!resourceSet || !resourceSet->acquire()) {
                    if( timeStat.markEnd() ) {
                        timeStat.report("Operation took %.2f ms\n");
                    }

                    printf("Acquire failed!\n");
                }
            }
            else if (params[0] == "release") {
                timeStat.markStart();
                if (!resourceSet || !resourceSet->release()) {
                    if( timeStat.markEnd() ) {
                        timeStat.report("Operation took %.2f ms\n");
                    }

                    printf("Release failed!\n");
                }
            }
            else if (params[0] == "add") {
                if (!resourceSet) {
                    printf("Update failed!\n");
                }
                else if (params.count() == 1 || params[1].isEmpty() || params[1].isNull()) {
                    printf("List of desired resources is missing. See help ...\n");
                }
                else {
                    uint32_t temp = Client::parseResourceList(params[1]);
                    if (params.count() > 2 && params[2] == "-o") {
                        updateSet(temp, temp, false);
                    }
                    else {
                        updateSet(temp, 0, false);
                    }
                }
            }
            else if (params[0] == "remove") {
                if (!resourceSet || params.count() == 1) {
                    printf("Update failed!\n");
                }
                else if (params.count() == 1 || params[1].isEmpty() || params[1].isNull()) {
                    printf("List of desired resources is missing. See help ...\n");
                }
                else {
                    uint32_t temp = Client::parseResourceList(params[1]);
                    if (params.count() > 2 && params[2] == "-o") {
                        updateSet(temp, temp, true);
                    }
                    else {
                        updateSet(temp, 0, true);
                    }
                }
            }
            else if (params[0] == "update") {
                if (!resourceSet || !resourceSet->update()) {
                    printf("Update failed!\n");
                }
            }
            else if (params[0] == "audio") {
                if (params.count() < 3) {
                    printf("Not enough parameters! See help!\n");
                }
                else {
                    Resource *resource = resourceSet->resource(AudioPlaybackType);
                    AudioResource *audioResource = static_cast<AudioResource*>(resource);
                    qDebug("resource = %p audioResource = %p", resource, audioResource);
                    if (audioResource == NULL) {
                        printf("No AudioResource available in set!\n");
                    }
                    else {
                        if (params[1] == "group") {
                            audioResource->setAudioGroup(params[2]);
                        }
                        else if (params[1] == "pid") {
                            bool ok=false;
                            quint32 pid = (quint32)params[2].toInt(&ok, 10);
                            if (ok && pid != 0) {
                                qDebug("Setting audio PID to %u", pid);
                                audioResource->setProcessID(pid);
                            }
                            else {
                                printf("Bad pid parameter!\n");
                            }
                        }
                        else if (params[1] == "tag") {
                            if (params.count() < 4) {
                                printf("tag requires TWO parameters name and value. See help \n");
                            }
                            else {
                                audioResource->setStreamTag(params[2], params[3]);
                            }
                        }
                        else {
                            printf("Unknown audio command!\n");
                        }
                    }
                }
            }
            else if (params[0] == "addaudio") {
                if (params.count() < 5) {
                    printf("Not enough parameters! See help!\n");
                }
                else {
                    AudioResource *audioResource = new AudioResource(params[1]);
                    if (audioResource == NULL) {
                        printf("Failed to create an AudioResource object!\n");
                    }
                    else {
                        bool ok=false;
                        quint32 pid = (quint32)params[2].toInt(&ok, 10);
                        if (ok && pid != 0) {
                            audioResource->setProcessID(pid);
                        }
                        else {
                            printf("Bad pid parameter!\n");
                        }
                        audioResource->setStreamTag(params[3], params[4]);
                        resourceSet->addResourceObject(audioResource);
                    }
                }
            }
            else if (params[0] == "free") {
                delete resourceSet;
                resourceSet = new ResourceSet(applicationClass);
            }
            else if (!params[0].isEmpty()) {
                QByteArray ba = line.toLatin1();
                const char *c_line = ba.data();
                printf("unknown command '%s'\n", c_line);
            }

            if (!quitFlag) {
                showPrompt();
            }
        }
    }
}