diff options
-rw-r--r-- | libresourceqt/include/qt4/policy/resource-set.h | 3 | ||||
-rw-r--r-- | libresourceqt/src/resource-engine.cpp | 10 | ||||
-rw-r--r-- | libresourceqt/src/resource-set.cpp | 10 | ||||
-rw-r--r-- | resourceqt-client/client.cpp | 683 | ||||
-rw-r--r-- | resourceqt-client/client.h | 129 | ||||
-rw-r--r-- | resourceqt-client/commandlineparser.cpp | 222 | ||||
-rw-r--r-- | resourceqt-client/commandlineparser.h | 47 | ||||
-rw-r--r-- | resourceqt-client/resourceqt-client.cpp | 223 | ||||
-rw-r--r-- | resourceqt-client/resourceqt-client.pro | 7 | ||||
-rw-r--r-- | resourceqt-client/time-stat.c | 34 | ||||
-rw-r--r-- | resourceqt-client/time-stat.h | 16 |
11 files changed, 684 insertions, 700 deletions
diff --git a/libresourceqt/include/qt4/policy/resource-set.h b/libresourceqt/include/qt4/policy/resource-set.h index 4943c35..710dc7d 100644 --- a/libresourceqt/include/qt4/policy/resource-set.h +++ b/libresourceqt/include/qt4/policy/resource-set.h @@ -82,7 +82,8 @@ public: * application. * \param parent The optional parent of of this class. */ - ResourceSet(const QString &applicationClass, QObject *parent = NULL); + ResourceSet(const QString &applicationClass, QObject *parent = NULL, + bool alwaysReply = false, bool autoRelease = false); /** * The destructor */ diff --git a/libresourceqt/src/resource-engine.cpp b/libresourceqt/src/resource-engine.cpp index 47ec436..e040562 100644 --- a/libresourceqt/src/resource-engine.cpp +++ b/libresourceqt/src/resource-engine.cpp @@ -207,8 +207,8 @@ static void handleAdviceMessage(resmsg_t *message, resset_t *libresourceSet, voi void ResourceEngine::receivedAdvice(resmsg_notify_t *message) { - qDebug("ResourceEngine(%d) - %s: %04x", identifier, __FUNCTION__, message->resrc); uint32_t allResources = allResourcesToBitmask(resourceSet); + qDebug("ResourceEngine(%d) - %s: have: %02x got %02x", identifier, __FUNCTION__, allResources, message->resrc); if(message->resrc < allResources) { emit resourcesLost(allResources-message->resrc); } @@ -296,8 +296,11 @@ static inline quint32 allResourcesToBitmask(const ResourceSet *resourceSet) QList<Resource *> resourceList = resourceSet->resources(); quint32 bitmask = 0; for (int i = 0; i < resourceList.size(); i++) { - bitmask += resourceTypeToLibresourceType(resourceList[i]->type()); + quint32 bits = resourceTypeToLibresourceType(resourceList[i]->type()); + qDebug("Converted Resource 0x%02x to 0x%02x", resourceList[i]->type(), bits); + bitmask += bits; } + qDebug("All resources as bitmask is 0x%04x", bitmask); return bitmask; } @@ -331,7 +334,8 @@ quint32 ResourcePolicy::resourceTypeToLibresourceType(ResourceType type) case HeadsetButtonsType: return RESMSG_HEADSET_BUTTONS; default: - return 0; + qDebug("Unknown resource Type %d", quint32(type)); + return 0xffff; } } diff --git a/libresourceqt/src/resource-set.cpp b/libresourceqt/src/resource-set.cpp index b5d3de2..f5faade 100644 --- a/libresourceqt/src/resource-set.cpp +++ b/libresourceqt/src/resource-set.cpp @@ -4,11 +4,12 @@ using namespace ResourcePolicy; static quint32 resourceSetId=1; -ResourceSet::ResourceSet(const QString &applicationClass, QObject * parent) +ResourceSet::ResourceSet(const QString &applicationClass, QObject * parent, + bool initialAlwaysReply, bool initialAutoRelease) : QObject(parent), resourceClass(applicationClass), resourceEngine(NULL), - audioResource(NULL), autoRelease(false), alwaysReply(false), - initialized(false), pendingAcquire(false), pendingUpdate(false), - pendingAudioProperties(false) + audioResource(NULL), autoRelease(initialAutoRelease), + alwaysReply(initialAlwaysReply), initialized(false), pendingAcquire(false), + pendingUpdate(false), pendingAudioProperties(false) { identifier = resourceSetId++; memset(resourceSet, 0, sizeof(QPointer<Resource *>)*NumberOfTypes); @@ -378,6 +379,7 @@ void ResourceSet::handleReleased() resourceSet[i]->unsetGranted(); } } + qDebug("ResourceSet(%d) - resourcesReleased!", identifier); emit resourcesReleased(); } diff --git a/resourceqt-client/client.cpp b/resourceqt-client/client.cpp index 5f1875b..adf1feb 100644 --- a/resourceqt-client/client.cpp +++ b/resourceqt-client/client.cpp @@ -1,5 +1,6 @@ #include <QtCore/QCoreApplication> #include <QtCore/QFile> +#include <QTextStream> #include <sys/time.h> #include <sys/types.h> @@ -9,160 +10,85 @@ using namespace ResourcePolicy; -Client::Client(QString appClass) : QObject() -{ - applicationClass = appClass; - resourceSet = NULL; +QMap<QString, CommandListArgs> Client::commandList; - standardInput = new QTextStream(stdin, QFile::ReadOnly); - mainTimerID = startTimer(0); -} - -Client::~Client() +CommandListArgs::CommandListArgs() + : args(), help() { - killTimer(mainTimerID); +} - if (resourceSet != NULL) { - delete resourceSet; - resourceSet = NULL; - } - if (standardInput != NULL) { - delete standardInput; - standardInput = NULL; - } +CommandListArgs::CommandListArgs(const QString &arguments, const QString &helpText) + : args(arguments), help(helpText) +{ } -uint32_t Client::parseResourceList(QString resourceListStr) +CommandListArgs::~CommandListArgs() { - 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; +Client::Client() + : QObject(), standardInput(stdin, QIODevice::ReadOnly), stdInNotifier(0, QSocketNotifier::Read), applicationClass(), + resourceSet(NULL), output(stdout) +{ + mainTimerID = startTimer(0); + commandList["help"] = CommandListArgs("", "print this help message"); + commandList["quit"] = CommandListArgs("", "exit application"); + commandList["free"] = CommandListArgs("", "destroy and free the resources"); + commandList["acquire"] = CommandListArgs("", "acquire required resources"); + commandList["release"] = CommandListArgs("", "release resources"); + commandList["update"] = CommandListArgs("", "update modified resource set after add or remove command"); + commandList["add"] = CommandListArgs("reslist [-o]", "add resource list, if -o provided, set as optional"); + commandList["remove"] = CommandListArgs("reslist [-o]", "remove resource list, if -o provided, removed only optional flag"); + commandList["audio"] = CommandListArgs("pid <pid> | group <audio group> | tag <name> <value>", "set audio properties"); + commandList["addaudio"] = CommandListArgs("<audio group> <pid> <tag name> <tag value>", "Add an audio resource and set the properties"); + commandList["show"] = CommandListArgs("", "show resources"); - pos++; - } +} - if (!resourceDef[pos].resourceName) { - const char* res = qPrintable(resList[i]); - printf("Ignoring invalid resource name '%s'\n", res); - } - else { - resourceList |= resourceDef[pos].resourceType; - } - } - } +Client::~Client() +{ + killTimer(mainTimerID); - return resourceList; + delete resourceSet; } void Client::showPrompt() { - printf("res-client> "); - fflush(stdout); + output << "res-client> " << flush; } -void Client::updateSet(uint32_t list, uint32_t optional, bool remove) +bool Client::initialize(const CommandLineParser &parser) { - 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); - } + QSet<ResourcePolicy::ResourceType> allResources; + QSet<ResourcePolicy::ResourceType> optionalResources; - continue; - } - - resource = allocateResource(res, opt); - if (resource) { - resourceSet->addResourceObject(resource); - } - } - } + if (parser.shouldAlwaysReply()) { + output << "client: AlwaysReply" << endl; + } - pos++; + if (parser.shouldAutoRelease()) { + output << "client: AutoRelease" << endl; } -} -bool Client::initialize(uint32_t all, uint32_t optional, bool alwaysReply, bool autoRelease) -{ - resourceSet = new ResourceSet(applicationClass); + resourceSet = new ResourceSet(parser.resourceApplicationClass(), this, + parser.shouldAlwaysReply(), + parser.shouldAutoRelease()); if (resourceSet == NULL) { return false; } - if (alwaysReply) { - qDebug("client: alwaysReply"); - resourceSet->setAlwaysReply(); - } - - if (autoRelease) { - qDebug("client: autoRelease"); - resourceSet->setAutoRelease(); + allResources.unite(parser.resources()); + optionalResources.unite(parser.optionalResources()); + foreach(ResourcePolicy::ResourceType resource, allResources) { + resourceSet->addResource(resource); + if (optionalResources.contains(resource)) { + resourceSet->resource(resource)->setOptional(); + } } - updateSet(all, optional, false); - if (!connect(resourceSet, SIGNAL(resourcesGranted(QList<ResourcePolicy::ResourceType>)), - this, SLOT(resourceAcquiredHandler(QList<ResourcePolicy::ResourceType>)))) - { + this, SLOT(resourceAcquiredHandler(QList<ResourcePolicy::ResourceType>)))) { return false; } @@ -173,150 +99,100 @@ bool Client::initialize(uint32_t all, uint32_t optional, bool alwaysReply, bool 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> &))); + if (!connect(resourceSet, SIGNAL(resourcesReleased()), this, SLOT(resourceReleasedHandler()))) { + return false; + } + if (!connect(resourceSet, SIGNAL(resourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &)), + this, SLOT(resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &)))) { + return false; + } + if (!connect(&stdInNotifier, SIGNAL(activated(int)), this, SLOT(readLine(int)))) { + return false; + } + if (!connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), + this, SLOT(doExit()))) { + return false; + } showPrompt(); return true; } -Resource* Client::allocateResource(ResourceType resource, bool optional) +void Client::doExit() { - Resource* retValue = NULL; + if (resourceSet != NULL) + resourceSet->release(); +} - switch (resource) { +const char * resourceTypeToString(ResourceType type) +{ + switch (type) { case AudioPlaybackType: - retValue = new AudioResource(); - break; - case VideoPlaybackType: - retValue = new VideoResource(); - break; + return "AudioPlayback"; case AudioRecorderType: - retValue = new AudioRecorderResource(); - break; + return "AudioRecording"; + case VideoPlaybackType: + return "VideoPlayback"; case VideoRecorderType: - retValue = new VideoRecorderResource(); - break; + return "VideoRegording"; case VibraType: - retValue = new VibraResource(); - break; + return "Vibra"; case LedsType: - retValue = new LedsResource(); - break; + return "Leds"; case BacklightType: - retValue = new BacklightResource(); - break; + return "Backlight"; case SystemButtonType: - retValue = new SystemButtonResource(); - break; + return "SystemButton"; case LockButtonType: - retValue = new LockButtonResource(); - break; + return "LockButton"; case ScaleButtonType: - retValue = new ScaleButtonResource(); - break; + return "ScaleButton"; case SnapButtonType: - retValue = new SnapButtonResource(); - break; + return "SnapButton"; case LensCoverType: - retValue = new LensCoverResource(); - break; + return "LensCover"; case HeadsetButtonsType: - retValue = new HeadsetButtonsResource(); - break; - case NumberOfTypes: - return NULL; - } - - if (retValue) { - retValue->setOptional(optional); + return "HeadsetButtons"; + default: + return "Unknown/Invalid Resource"; } - 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) +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]]); + output << "Resource Set:\n"; + foreach(ResourceType resource, resList) { + output << "\t" << resourceTypeToString(resource) << endl; } } -void Client::showResources(const QList<Resource*> resList) +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)" : ""); + output << "Resource Set:\n"; + foreach(Resource* resource, resList) { + output << "\t" << resourceTypeToString(resource->type()); + if (resource->isOptional()) + output << " (optional)"; + if (resource->isGranted()) + output << " (granted)"; + output << endl; } } void Client::resourceAcquiredHandler(const QList<ResourceType>& /*grantedResList*/) { - if( timeStat.markEnd() ) { - timeStat.report("\nOperation took %.2f ms\n"); + long int ms = stop_timer(); + if (ms > 0) { + output << "Operation took " << ms << "ms"; } QList<Resource*> list = resourceSet->resources(); if (!list.count()) { - printf("\nGranted resource set is empty. Possible bug?\n"); + qFatal("Granted resource set is empty. Possible bug?"); } else { - printf("\nManager grants access to these resources:\n"); - printf("Resource set:\n"); + output << "\nReceived a grant.\n"; showResources(list); } showPrompt(); @@ -324,227 +200,234 @@ void Client::resourceAcquiredHandler(const QList<ResourceType>& /*grantedResList void Client::resourceDeniedHandler() { - if( timeStat.markEnd() ) { - timeStat.report("\nOperation took %.2f ms\n"); + long int ms = stop_timer(); + if (ms > 0) { + output << "Operation took " << ms << "ms"; } - printf("\nManager denies access to resources!\n"); + output << "\nManager denies access to resources!" << endl; showPrompt(); } void Client::resourceLostHandler() { - if( timeStat.markEnd() ) { - timeStat.report("\nOperation took %.2f ms\n"); + long int ms = stop_timer(); + if (ms > 0) { + output << "Operation took " << ms << "ms"; } - printf("\nLost resources from manager!\n"); + output << "\nLost resources from manager!" << endl; showPrompt(); } void Client::resourceReleasedHandler() { - if( timeStat.markEnd() ) { - timeStat.report("\nOperation took %.2f ms\n"); + long int ms = stop_timer(); + if (ms > 0) { + output << "Operation took " << ms << "ms"; } - printf("\nAll resources released\n"); + output << "\nAll resources released" << endl; showPrompt(); } void Client::resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &availableResources) { - printf("\nManager advice: These resources are available:\n"); - printf("Resource set:\n"); + output << "Manager advice: These resources are available:\n"; showResources(availableResources); showPrompt(); } -void Client::timerEvent(QTimerEvent*) +void Client::readLine(int) { - 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"); + QString line = standardInput.readLine(); + if (line.isNull() || line.isEmpty()) { + showPrompt(); + return; + } + QTextStream input(&line, QIODevice::ReadOnly); + QString command; + input >> command; + if (command.isNull() || command.isEmpty()) { + qDebug("Unable to read a command"); + return; + } + + if ((command == "quit") || (command == "exit")) { + QCoreApplication::quit(); + return; + } + else if (command == "help") { + output << "Available commands:\n"; + QMap<QString, CommandListArgs>::const_iterator i = + commandList.constBegin(); + while (i != commandList.constEnd()) { + output << qSetFieldWidth(10) << right << i.key() + << qSetFieldWidth(1) << " " + << qSetFieldWidth(55) << left << i.value().args + << qSetFieldWidth(0) << i.value().help << endl; + ++i; + } + } + else if (command == "show") { + if (!resourceSet) { + qCritical("%s failed!", qPrintable(command)); + } + else { + QList<Resource*> list = resourceSet->resources(); + if (!list.count()) { + output << "Resource set is empty, use add command to add some." + << endl; + } + else { + showResources(list); } - 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 (command == "acquire") { + start_timer(); + if (!resourceSet || !resourceSet->acquire()) { + stop_timer(); + qCritical("%s failed!", qPrintable(command)); + } + } + else if (command == "release") { + start_timer(); + if (!resourceSet || !resourceSet->release()) { + stop_timer(); + qCritical("%s failed!", qPrintable(command)); + } + } + else if (command == "add") { + QString resourceList, flag; + input >> resourceList >> flag; + if (!resourceSet) { + qCritical("%s failed!", qPrintable(command)); + } + else if (resourceList.isEmpty() || resourceList.isNull()) { + output << "List of desired resources is missing. Use help."; + } + else { + bool optional = false; + QSet<ResourcePolicy::ResourceType> resToAdd; + CommandLineParser::parseResourceList(resourceList, resToAdd); + if (flag == "-o") { + optional = true; } - else if (params[0] == "show") { - if (!resourceSet) { - printf("Show failed!\n"); + foreach(ResourcePolicy::ResourceType resource, resToAdd) { + if (!resourceSet->contains(resource)) { + resourceSet->addResource(resource); } - 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); - } + if (optional) { + resourceSet->resource(resource)->setOptional(); } } - 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 (command == "remove") { + QString resourceList, flag; + input >> resourceList >> flag; + if (!resourceSet) { + qCritical("%s failed!", qPrintable(command)); + } + else if (resourceList.isEmpty() || resourceList.isNull()) { + output << "List of desired resources is missing. Use help."; + } + else { + QSet<ResourcePolicy::ResourceType> resToRemove; + CommandLineParser::parseResourceList(resourceList, resToRemove); + if (flag == "-o") { + foreach(ResourcePolicy::ResourceType resource, resToRemove) { + resourceSet->resource(resource)->setOptional(false); } } - 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 { + foreach(ResourcePolicy::ResourceType resource, resToRemove) { + resourceSet->deleteResource(resource); } } - 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 (command == "update") { + if (!resourceSet || !resourceSet->update()) { + qCritical("%s failed!", qPrintable(command)); + } + } + else if (command == "audio") { + QString what, group, tagName, tagValue; + quint32 pid = 0; + input >> what; + + if (what.isEmpty() || what.isNull()) { + output << "Not enough parameters! See help" << endl; + } + else { + Resource *resource = resourceSet->resource(AudioPlaybackType); + AudioResource *audioResource = static_cast<AudioResource*>(resource); + qDebug("resource = %p audioResource = %p", resource, audioResource); + if (audioResource == NULL) { + output << "No AudioResource available in set!" << endl; } - 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 { + if (what == "group") { + input >> group; + audioResource->setAudioGroup(group); } - else { - uint32_t temp = Client::parseResourceList(params[1]); - if (params.count() > 2 && params[2] == "-o") { - updateSet(temp, temp, true); + else if (what == "pid") { + input >> pid; + if (pid != 0) { + qDebug("Setting audio PID to %u", pid); + audioResource->setProcessID(pid); } else { - updateSet(temp, 0, true); + output << "Bad pid parameter!" << endl; } } - } - 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 (what == "tag") { + input >> tagName >> tagValue; + if (tagName.isEmpty() || tagName.isNull() || + tagValue.isEmpty() || tagValue.isNull()) { + output << "tag requires 2 parameters name and value. See help" + << endl; } 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"); - } + audioResource->setStreamTag(tagValue, tagName); } } - } - 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); - } + output << "Unknown audio command!"; } } - 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); - } + } + } + else if (command == "addaudio") { + QString group, tagName, tagValue; + quint32 pid = 0; + input >> group >> pid >> tagName >> tagValue; - if (!quitFlag) { - showPrompt(); + if (group.isEmpty() || (pid == 0) || tagName.isEmpty() || tagValue.isEmpty()) { + output << "Invalid parameters! See help!" << endl; + } + else { + AudioResource *audioResource = new AudioResource(group); + if (audioResource == NULL) { + output << "Failed to create an AudioResource object!" << endl; + } + else { + audioResource->setProcessID(pid); + audioResource->setStreamTag(tagName, tagValue); + resourceSet->addResourceObject(audioResource); } } } + else if (command == "free") { + delete resourceSet; + resourceSet = new ResourceSet(applicationClass); + } + else { + output << "unknown command '" << command << "'" << endl; + } + + showPrompt(); } diff --git a/resourceqt-client/client.h b/resourceqt-client/client.h index 200e4b6..1a04961 100644 --- a/resourceqt-client/client.h +++ b/resourceqt-client/client.h @@ -3,123 +3,62 @@ #include <QObject> #include <QtCore/QTextStream> +#include <QSocketNotifier> #include <stdint.h> #include <policy/resource-set.h> #include <sys/resource.h> -#define RES_AUDIO_PLAYBACK (1<<0) -#define RES_VIDEO_PLAYBACK (1<<1) -#define RES_AUDIO_RECORDING (1<<2) -#define RES_VIDEO_RECORDING (1<<3) -#define RES_VIBRA (1<<4) -#define RES_LEDS (1<<5) -#define RES_BACKLIGHT (1<<6) -#define RES_SYSTEM_BUTTON (1<<7) -#define RES_LOCK_BUTTON (1<<8) -#define RES_SCALE_BUTTON (1<<9) -#define RES_SNAP_BUTTON (1<<10) -#define RES_LENS_COVER (1<<11) -#define RES_HEADSET_BUTTONS (1<<12) +#include "commandlineparser.h" +#include "time-stat.h" -class TimeStat +class CommandListArgs { public: - double totalTime; - - TimeStat() - { - running = false; - totalTime = 0; - }; - - inline void markStart() - { - running = true; - getrusage(RUSAGE_SELF, &start); - } - - inline bool markEnd() - { - getrusage(RUSAGE_SELF, &end); - - if( !running ) - return false; - - running = false; - timevalSub(&end.ru_utime, &start.ru_utime, &end.ru_utime); - timevalSub(&end.ru_stime, &start.ru_stime, &end.ru_stime); - - double sys = end.ru_stime.tv_sec * 1000.0 + end.ru_stime.tv_usec / 1000.0; - double usr = end.ru_utime.tv_sec * 1000.0 + end.ru_utime.tv_usec / 1000.0; - totalTime = sys + usr; - - return true; - } - - void report(const char* format) - { - printf(format, totalTime); - } - -private: - bool running; - struct rusage start; - struct rusage end; - - void timevalSub(struct timeval *a, struct timeval *b, struct timeval *diff) - { - diff->tv_sec = a->tv_sec - b->tv_sec; - if( a->tv_usec < b->tv_usec ) - { - diff->tv_sec--; - diff->tv_usec = 1000000 - b->tv_usec + a->tv_usec; - } - else - diff->tv_usec = a->tv_usec - b->tv_usec; - } + CommandListArgs(const QString &arguments, const QString &helpText); + CommandListArgs(); + ~CommandListArgs(); + QString args; + QString help; }; class Client : public QObject { - Q_OBJECT + Q_OBJECT public: - Client(QString appClass); - ~Client(); + Client(); + ~Client(); - bool initialize(uint32_t all, uint32_t optional, bool alwaysReply, bool autoRelease); - static uint32_t parseResourceList(QString resourceListStr); + bool initialize(const CommandLineParser &commandParser); + static uint32_t parseResourceList(QString resourceListStr); private slots: - void resourceAcquiredHandler(const QList<ResourcePolicy::ResourceType>& grantedResList); - void resourceDeniedHandler(); - void resourceLostHandler(); - void resourceReleasedHandler(); - void resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &availableResources); - -protected: - void timerEvent(QTimerEvent *e); + void resourceAcquiredHandler(const QList<ResourcePolicy::ResourceType>& grantedResList); + void resourceDeniedHandler(); + void resourceLostHandler(); + void resourceReleasedHandler(); + void resourcesBecameAvailableHandler(const QList<ResourcePolicy::ResourceType> &availableResources); + void readLine(int); + void doExit(); private: - QTextStream* standardInput; - int mainTimerID; + QTextStream standardInput; + QSocketNotifier stdInNotifier; + int mainTimerID; + QString applicationClass; + ResourcePolicy::ResourceSet *resourceSet; + QTextStream output; - uint32_t resourcesAll; - uint32_t resourcesOptional; - QString applicationClass; + static QMap<QString, CommandListArgs> commandList; - TimeStat timeStat; + ResourcePolicy::Resource* allocateResource(ResourcePolicy::ResourceType resource, bool optional); + ResourcePolicy::ResourceType getResourceType(uint32_t resource); - ResourcePolicy::ResourceSet* resourceSet; - - ResourcePolicy::Resource* allocateResource(ResourcePolicy::ResourceType resource, bool optional); - ResourcePolicy::ResourceType getResourceType(uint32_t resource); - - void showPrompt(); - void showResources(const QList<ResourcePolicy::ResourceType> resList); - void showResources(const QList<ResourcePolicy::Resource*> resList); - void updateSet(uint32_t list, uint32_t optional, bool remove); + void showPrompt(); + void showResources(const QList<ResourcePolicy::ResourceType> &resList); + void showResources(const QList<ResourcePolicy::Resource*> &resList); }; #endif + diff --git a/resourceqt-client/commandlineparser.cpp b/resourceqt-client/commandlineparser.cpp new file mode 100644 index 0000000..732d361 --- /dev/null +++ b/resourceqt-client/commandlineparser.cpp @@ -0,0 +1,222 @@ +#include <QDebug> +#include "commandlineparser.h" + +QHash<QString, ResourcePolicy::ResourceType> CommandLineParser::resourceValues; + +CommandLineParser::CommandLineParser(): + allResources(), optResources(), autoRelease(false), alwaysReply(false), + verbose(false), allowUnkownResourceClass(false), output(stdout) +{ + resourceValues["AudioPlayback"] = ResourcePolicy::AudioPlaybackType; + resourceValues["VideoPlayback"] = ResourcePolicy::VideoPlaybackType; + resourceValues["AudioRecording"] = ResourcePolicy::AudioRecorderType; + resourceValues["VideoRecording"] = ResourcePolicy::VideoRecorderType; + resourceValues["Vibra"] = ResourcePolicy::VibraType; + resourceValues["Leds"] = ResourcePolicy::LedsType; + resourceValues["Backlight"] = ResourcePolicy::BacklightType; + resourceValues["SystemButton"] = ResourcePolicy::SystemButtonType; + resourceValues["LockButton"] = ResourcePolicy::LockButtonType; + resourceValues["ScaleButton"] = ResourcePolicy::ScaleButtonType; + resourceValues["SnapButton"] = ResourcePolicy::SnapButtonType; + resourceValues["LensCover"] = ResourcePolicy::LensCoverType; + resourceValues["HeadsetButtons"] = ResourcePolicy::HeadsetButtonsType; +} + +CommandLineParser::~CommandLineParser() +{ +} + +bool CommandLineParser::parseArguments() +{ + QStringList args = QCoreApplication::arguments(); + QStringList::const_iterator ci = args.constBegin(); + // skip the first arg, which is program name + ++ci; + while (ci != args.constEnd()) { + if ((*ci).at(0) == QChar('-')) { + switch ((*ci).at(1).toAscii()) { + case 'd': + ++ci; + case 'm': + case 's': + case 't': + break; + case 'f': + if (!parseModeValues(*(++ci))) { + return false; + } + break; + case 'o': + if (!parseResourceList(*(++ci), optResources)) { + output << "Failed to parse resources: " << *ci << endl; + return false; + } + break; + case 'u': + allowUnkownResourceClass = true; + break; + case 'h': + default: + usage(); + return false; + } + } + else { + //assume there are no more args + break; + } + ++ci; + } + + if (ci == args.constEnd()) { + usage(); + return false; + } + else { + if (!parseClassString(*ci)) { + return false; + } + ++ci; + if (ci != args.constEnd()) { + if (!parseResourceList(*ci, allResources)) { + output << "Error while parsing resource list" << endl; + } + } + } + + if (!allResources.contains(optResources)) { + output << "optional resources are not subset of all resources" << endl; + return false; + } + return true; +} + +bool CommandLineParser::parseClassString(const QString &str) +{ + if (!allowUnkownResourceClass && + (str != "call") && + (str != "camera") && + (str != "ringtone") && + (str != "alarm") && + (str != "navigator") && + (str != "game") && + (str != "player") && + (str != "event") && + (str != "background") && + (str != "videoeditor")) { + output << "invalid class " << str; + return false; + } + + applicationClass = str; + return true; +} + +bool CommandLineParser::parseResourceList(const QString &resourceListStr, + QSet<ResourcePolicy::ResourceType> &resources) +{ + if (resourceListStr.isEmpty() || resourceListStr.isNull()) { + return false; + } + else { + QStringList resList = resourceListStr.split(",", QString::SkipEmptyParts); + + foreach(QString res, resList) { + if (resourceValues.contains(res)) { + resources.insert(resourceValues[res]); + } + } + } + + return true; +} + +bool CommandLineParser::parseModeValues(const QString &modeListStr) +{ + if (modeListStr.isEmpty() || modeListStr.isNull()) { + return false; + } + + QStringList modeList = modeListStr.split(",", QString::SkipEmptyParts); + + foreach(QString mode, modeList) { + if (mode == "AutoRelease") { + autoRelease = true; + } + else if (mode == "AlwaysReply") { + alwaysReply = true; + } + else { + output << "Ignoring unknown mode '" << mode << "'!" << endl; + } + } + return true; +} + +void CommandLineParser::usage() +{ + output << "usage: resourceqt-client [-h] [-m mode-values]" << + "[-o optional-resources] [-s shared-resources -m shared-mask] " << + "class all-resources" << endl; + output << "\toptions:" << endl; + output << "\t h\tprint this help message and exit" << endl; + output << "\t f\tmode values. See 'modes' below for the " + "\n\t\tsyntax of <mode-values>" << endl; + output << "\t o\toptional resources. See 'resources' below for the " + "syntax of\n\t\t<optional-resources>" << endl; + output << "\tclass:" << endl; + output << "\t\tcall\t - for native or 3rd party telephony" << endl; + output << "\t\tcamera\t - for photo applications" << endl; + output << "\t\tringtone - for ringtones" << endl; + output << "\t\talarm\t - for alarm clock" << endl; + output << "\t\tnavigator - for mapping applications" << endl; + output << "\t\tgame\t - for gaming" << endl; + output << "\t\tplayer\t - for media playback/recording" << endl; + output << "\t\tevent\t - for messaging and other event notifications" << endl; + output << "\t\tbackground - for thumbnailing etc" << endl; + output << "\t\tvideoeditor\t - for video editing/MMS" << endl; + output << "\tresources:" << endl; + output << "\t comma separated list of the following resources" << endl; + + QHash<QString, ResourcePolicy::ResourceType>::const_iterator ci = resourceValues.constBegin(); + while (ci != resourceValues.constEnd()) { + output << "\t\t" << ci.key() << endl; + ++ci; + } + output << "\t no whitespace allowed in the resource list." << endl; + output << "\tmodes:" << endl; + output << "\t comma separated list of the following modes" << endl; + output << "\t\tAutoRelease" << endl; + output << "\t\tAlwaysReply" << endl; +} + +const QSet<ResourcePolicy::ResourceType>& CommandLineParser::resources() const +{ + return allResources; +} + +const QSet<ResourcePolicy::ResourceType>& CommandLineParser::optionalResources() const +{ + return optResources; +} + +QString CommandLineParser::resourceApplicationClass() const +{ + return applicationClass; +} + +bool CommandLineParser::shouldAutoRelease() const +{ + return autoRelease; +} + +bool CommandLineParser::shouldAlwaysReply() const +{ + return alwaysReply; +} + +bool CommandLineParser::shouldBeVerbose() const +{ + return verbose; +} + diff --git a/resourceqt-client/commandlineparser.h b/resourceqt-client/commandlineparser.h new file mode 100644 index 0000000..420c633 --- /dev/null +++ b/resourceqt-client/commandlineparser.h @@ -0,0 +1,47 @@ +#ifndef COMMANDLINEPARSER_H +#define COMMANDLINEPARSER_H +#include <QString> +#include <QList> +#include <QSet> +#include <QHash> +#include <QTextStream> +#include <policy/resource.h> + +class CommandLineParser +{ +public: + CommandLineParser(); + ~CommandLineParser(); + +public: + bool parseArguments(); + + static bool parseResourceList(const QString &resourceListStr, + QSet<ResourcePolicy::ResourceType> &resourceList); + + const QSet<ResourcePolicy::ResourceType>& resources() const; + const QSet<ResourcePolicy::ResourceType>& optionalResources() const; + QString resourceApplicationClass() const; + bool shouldAutoRelease() const; + bool shouldAlwaysReply() const; + bool shouldBeVerbose() const; + +private: + QSet<ResourcePolicy::ResourceType> allResources; + QSet<ResourcePolicy::ResourceType> optResources; + static QHash<QString, ResourcePolicy::ResourceType> resourceValues; + QString applicationClass; + bool autoRelease; + bool alwaysReply; + bool verbose; + bool allowUnkownResourceClass; + QTextStream output; + + bool parseClassString(const QString &str); + bool parseModeValues(const QString &modeListStr); + + void usage(); + +}; +#endif + diff --git a/resourceqt-client/resourceqt-client.cpp b/resourceqt-client/resourceqt-client.cpp index 522ce8d..f5b534e 100644 --- a/resourceqt-client/resourceqt-client.cpp +++ b/resourceqt-client/resourceqt-client.cpp @@ -1,210 +1,45 @@ #include <QtCore/QCoreApplication> #include <QtCore/QString> #include <QtCore/QStringList> -#include <stdlib.h> -#include <errno.h> -#include <libgen.h> -#include <getopt.h> #include "client.h" +#include "commandlineparser.h" -class CommandLineParser -{ -public: - CommandLineParser(int argc, char** argv) { - exitCode = 0; - exitFlag = false; - exeName = strdup(basename(argv[0])); - - resourcesAll = 0; - resourcesOptional = 0; - autoRelease = false; - alwaysReply = false; - - parseArguments(argc, argv); - } - - ~CommandLineParser() { - if (exeName != NULL) { - delete exeName; - exeName = NULL; - } - } - -public: - bool exitFlag; - int exitCode; - - uint32_t resourcesAll; - uint32_t resourcesOptional; - QString applicationClass; - bool autoRelease; - bool alwaysReply; - - void printMessage(const char *fmt, ...) { - va_list ap; - char fmtbuf[512]; - - snprintf(fmtbuf, sizeof(fmtbuf), "%s\n", fmt); - va_start(ap, fmt); - vprintf(fmtbuf, ap); - va_end(ap); - } - -private: - char* exeName; - - void printError(const char *fmt, ...) { - va_list ap; - char fmtbuf[512]; - - snprintf(fmtbuf, sizeof(fmtbuf), "%s\n", fmt); - va_start(ap, fmt); - vprintf(fmtbuf, ap); - va_end(ap); - - exitCode = errno; - exitFlag = true; - } - - void parseArguments(int argc, char** argv) { - int option; - - while ((option = getopt(argc, argv, "hm:o:")) != -1) { - switch (option) { - case 'h': - usage(0); - return; - case 'm': - parseModeValues(optarg); - break; - case 'o': - resourcesOptional = Client::parseResourceList(optarg); - break; - default: - usage(EINVAL); - return; - } - } +bool verbose = false; - if ((optind != argc - 2) && (optind != argc - 1)) { - usage(EINVAL); - return; - } - else { - applicationClass = parseClassString(argv[optind]); - if (argc > optind + 1) - resourcesAll = Client::parseResourceList(argv[optind+1]); - else - resourcesAll = 0; - } - - if (!resourcesAll) { - printMessage("No resources found, use add command to add some ..."); - } - - if ((resourcesAll | resourcesOptional) != resourcesAll) { - printError("optional resources are not subset of all resources"); - } - } - - char* parseClassString(char *str) { - if (strcmp(str, "call") && - strcmp(str, "camera") && - strcmp(str, "ringtone") && - strcmp(str, "alarm") && - strcmp(str, "navigator") && - strcmp(str, "game") && - strcmp(str, "player") && - strcmp(str, "event") && - strcmp(str, "background")) { - printError("invalid class '%s'", str); - return NULL; - } - - return str; - } - - void parseModeValues(QString modeListStr) { - if (!modeListStr.isEmpty() && !modeListStr.isNull()) { - QStringList modeList = modeListStr.split(",", QString::SkipEmptyParts); - - for (int i = 0; i < modeList.count(); i++) { - if (modeList[i] == "AutoRelease") { - autoRelease = true; - } - else if (modeList[i] == "AlwaysReply") { - alwaysReply = true; - } - else { - const char* mode = qPrintable(modeList[i]); - printMessage("Ignoring unknown mode '%s'!", mode); - } - } - } - } - - void usage(int theExitCode) { - printf("usage: %s [-h] [-m mode-values]" - "[-o optional-resources] [-s shared-resources -m shared-mask] " - "class all-resources\n", - exeName); - printf("\toptions:\n"); - printf("\t h\tprint this help message and exit\n"); - printf("\t m\tmode values. See 'modes' below for the " - "\n\t\tsyntax of <mode-values>\n"); - printf("\t o\toptional resources. See 'resources' below for the " - "syntax of\n\t\t<optional-resources>\n"); - printf("\tclass:\n"); - printf("\t\tcall\t - for native or 3rd party telephony\n"); - printf("\t\tcamera\t - for photo applications\n"); - printf("\t\tringtone - for ringtones\n"); - printf("\t\talarm\t - for alarm clock\n"); - printf("\t\tnavigator - for mapping applications\n"); - printf("\t\tgame\t - for gaming\n"); - printf("\t\tplayer\t - for media playback/recording\n"); - printf("\t\tevent\t - for messaging and other event notifications\n"); - printf("\t\tbackground - for thumbnailing etc\n"); - printf("\tresources:\n"); - printf("\t comma separated list of the following resources\n"); - printf("\t\tAudioPlayback\n"); - printf("\t\tVideoPlayback\n"); - printf("\t\tAudioRecording\n"); - printf("\t\tVideoRecording\n"); - printf("\t\tVibra\n"); - printf("\t\tLeds\n"); - printf("\t\tBackLight\n"); - printf("\t\tSystemButton\n"); - printf("\t\tLockButton\n"); - printf("\t\tScaleButton\n"); - printf("\t\tSnapButton\n"); - printf("\t\tLensCover\n"); - printf("\t\tHeadsetButtons\n"); - printf("\t no whitespace allowed in the resource list.\n"); - printf("\tmodes:\n"); - printf("\t comma separated list of the following modes\n"); - printf("\t\tAutoRelease\n"); - printf("\t\tAlwaysReply\n"); - fflush(stdout); - - exitCode = theExitCode; - exitFlag = true; +void debugOutput(QtMsgType type, const char *msg) +{ + switch (type) { + case QtDebugMsg: + if (verbose) + fprintf(stderr, "Debug: %s\n", msg); + break; + case QtWarningMsg: + fprintf(stderr, "Warning: %s\n", msg); + break; + case QtCriticalMsg: + fprintf(stderr, "Critical: %s\n", msg); + break; + case QtFatalMsg: + fprintf(stderr, "Fatal Error: %s\n", msg); + abort(); } -}; +} int main(int argc, char *argv[]) { - CommandLineParser parser(argc, argv); - - if (parser.exitFlag) - return parser.exitCode; - + qInstallMsgHandler(debugOutput); QCoreApplication app(argc, argv); + CommandLineParser parser; + Client client; + + if (!parser.parseArguments()) { + return 1; + } - Client client(parser.applicationClass); - if (!client.initialize(parser.resourcesAll, parser.resourcesOptional, parser.alwaysReply, parser.autoRelease)) { - parser.printMessage("initialization failed!"); - return EINVAL; + if (!client.initialize(parser)) { + qFatal("Initialization failed"); } return app.exec(); } + diff --git a/resourceqt-client/resourceqt-client.pro b/resourceqt-client/resourceqt-client.pro index 7b4e7ff..ce378c6 100644 --- a/resourceqt-client/resourceqt-client.pro +++ b/resourceqt-client/resourceqt-client.pro @@ -11,11 +11,12 @@ CONFIG -= app_bundle INCLUDEPATH += $${LIBRESOURCEINC} QMAKE_CXXFLAGS += -Wall -LIBS += -L$${LIBRESOURCEQT}/build -lresourceqt -L$${LIBDBUSQEVENTLOOP}/build -ldbus-qeventloop +QMAKE_CFLAGS += -std=c99 -D_POSIX_C_SOURCE=199309L +LIBS += -L$${LIBRESOURCEQT}/build -lresourceqt -L$${LIBDBUSQEVENTLOOP}/build -ldbus-qeventloop -lm -lrt # Input -HEADERS = client.h -SOURCES += resourceqt-client.cpp client.cpp +HEADERS = client.h commandlineparser.h time-stat.h +SOURCES += resourceqt-client.cpp commandlineparser.cpp client.cpp time-stat.c QMAKE_DISTCLEAN += -r .moc .obj diff --git a/resourceqt-client/time-stat.c b/resourceqt-client/time-stat.c new file mode 100644 index 0000000..fd79916 --- /dev/null +++ b/resourceqt-client/time-stat.c @@ -0,0 +1,34 @@ +#include <math.h> +#include "time-stat.h" + +static struct timespec start_time; + +int start_timer(void) +{ + int r; + r = clock_gettime(CLOCK_REALTIME, &start_time); + + if (r == 0) + return 1; + else + return 0; +} + +long int stop_timer(void) +{ + struct timespec end_time; + int r; + double milliseconds = 0.0; + + r = clock_gettime(CLOCK_REALTIME, &end_time); + + if (r == 0) { + milliseconds = 1000.0 * (end_time.tv_sec - start_time.tv_sec) + + (end_time.tv_nsec - start_time.tv_nsec) / 1000000.0; + } + start_time.tv_sec = 0; + start_time.tv_nsec = 0; + + return lround(milliseconds); +} + diff --git a/resourceqt-client/time-stat.h b/resourceqt-client/time-stat.h new file mode 100644 index 0000000..5fbe582 --- /dev/null +++ b/resourceqt-client/time-stat.h @@ -0,0 +1,16 @@ +#ifndef TIME_STAT_H +#define TIME_STAT_H +#include <time.h> + +#ifdef __cplusplus +extern "C" { +#endif + int start_timer(void); + + long int stop_timer(void); +#ifdef __cplusplus +} +#endif + +#endif + |