Check if display is at sleep or receive sleep notifications - objective-c

I have an application utility which becomes useless when there's no user. So, in order to save resources, I'd like it to know when/whether display is at sleep.
There's a dedicated article about wake/sleep notifications by apple, but it deals only with computer sleep and not display sleep.
Is there a way for application to 'hibernate' when display is at sleep?
Thank you

The DisplayWrangler service sends notifications for when the display will power off:
// Doesn't include error checking - just a quick example
io_service_t displayWrangler;
IONotificationPortRef notificationPort;
io_object_t notification;
displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("IODisplayWrangler");
notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, NULL, &notification);
CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
IOObjectRelease (displayWrangler);
Then the callback looks something like this:
void displayPowerNotificationsCallback(void *refcon, io_service_t service, natural_t messageType, void *messageArgument)
{
switch (messageType) {
case kIOMessageDeviceWillPowerOff :
// This is called twice - once for display dim event, then once
// for display power off
break;
case kIOMessageDeviceHasPoweredOn :
// Display powering back on
break;
}
}

This is response to a question asked a while ago - but I thought it would be useful to add my answer.
NSWorkspace has a couple of notifications for when displays wake and sleep: NSWorkspaceScreensDidSleepNotification and NSWorkspaceScreensDidWakeNotification

Since I couldn´t find any call issued by the display falling to sleep (maybe the screensaver does that? It´s very likely to kick in before the system falls to sleep), I´d suggest detecting the idle time manually and then comparing it to the display sleep settings.
This article covers how to get the idle time from IOKit and you should be able to easily get the current sleep settings, e.g. with "pmset -g | grep sleep".
Two minutes after posting the above, I discovered an open source command line tool that will probably help you a lot getting there: SleepWatcher seems to be able to do just what you asked for.

Related

Objective-C: Refreshing FrontmostApplication

I wrote this little program which is supposed to print the current frontmost application twice, with a 3-second break in between.
void printFrontmostApp() {
NSRunningApplication *frontmostApplication = [NSWorkspace sharedWorkspace].frontmostApplication;
NSLog(#"%#",frontmostApplication);
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
printFrontmostApp();
sleep(3);
printFrontmostApp();
}
return 0;
}
When I ran this program, I realised that frontmostApplication is not refreshed when it is called the second time. I found the solution here. But I still have two questions:
1) I want to know why the frontmostApplication is not updated.
2) How do I force it to refresh every time I call it? I don't want to receive a notification every time the frontmost application deactivates, because it is a little inefficient for my purposes.
Edit:
Just to be crystal clear, let's suppose the time now is 10:00:00. I call printFrontmostApp, and it prints "Xcode" to the console, because Xcode is the current frontmost app. Then the program sleeps for 3 seconds. At 10:00:01, I opened another app, say TextEdit. At 10:00:03, my program calls printFrontmostApp for the second time. I expect it to print "TextEdit", which is the current frontmost application. But it prints "Xcode" instead. I can't understand this behaviour.
Can someone please explain what happens at 10:00:03? The function seems to "remember" the value of frontmostApplication at 10:00:00 and retains it when it is called the second time. I thought that any memory will be released once it goes out of scope, so why is this happening?
And how do I get my program to get the frontmost app at 10:00:03? I can get the frontmost app at 10:00:00, I should be able to do the same 3 seconds later right?
The documentation for -[NSWorkspace runningApplications] — not the method you're using, but related — says:
Similar to the NSRunningApplication class’s properties, this property will only change when the main run loop is run in a common mode. Instead of polling, use key-value observing to be notified of changes to this array property.
From the NSRunningApplication documentation:
Properties that vary over time are inherently race-prone. For example, a hidden app may unhide itself at any time. To ameliorate this, properties persist until the next turn of the main run loop in a common mode. For example, if you repeatedly poll an unhidden app for its hidden property without allowing the run loop to run, it will continue to return NO, even if the app hides, until the next turn of the run loop.
It's a near certainty that the same principle applies to -frontmostApplication even though the documentation doesn't say so explicitly. You will never get different results by polling without allowing the run loop to run.
For 1) the answer is the same described in the question you have linked: You have to observe this notification, that tells you when a new application was activated:
NSWorkspaceDidActivateApplicationNotification
About 2) You have different observers for activation and deactivation like:
NSWorkspaceDidDeactivateApplicationNotification
So your are not going to observe notifications that you are not registered, please take a look at NSWorkspace Notifications for a comprehensive list.
Otherwise, please define your question about refreshing/polling (that I think it's not a good idea anyways).

Determining how much time has passed since the app was used

I am looking to make an app that, after a given time of no use, will close or give a message to the user.
How can I implement this?
UKIDleTimer is what you're looking for. You create a timer that only fires when the system becomes idle and implement the following method in its delegate:
-(void) timerBeginsIdling: (id)sender {
// terminate app
[NSApp terminate];
}
How about:
[NSApp performSelector:#selector(terminate:)
withObject:nil
afterDelay:[your delay...]];
Look at various Hello World examples on the net for Objective C. Once you have a hello world example going, you'll want to add some event listeners to monitor user activity. When any of those event handlers are called as a result of a users' actions, they should set a variable with the time of that action. Finally, set up a timer to check for user inactivity, say once every 30 seconds, which checks that value, to see if it's exceeded the time at which you want the application to close. If so, then send an exit command.

Objective-c -> class method to main file query

Sorry to bug twice so quickly, but since people were so kind in their informative responces, I figured it couldnt hurt to ask another question.
The same program i tried to make it rather swanky and have a main screen which allows you to click on a button which leads to a limited options screen. This lets you switch the music on or off. Or at least it should do.
The music running code is in the main file (game.m), under the following:
//Music
[Settings setMusicEnabled:YES];
music = [SPSound soundWithContentsOfFile:#"music.caf"];
channel = [[music createChannel] retain];
channel.loop = YES;
channel.volume = 0.25;
if([Settings musicEnabled]){
[channel play];
}
I apologize for the strange format, but it is Sparrow framework. basically, the Settings file contains the class methods I am trying to use. If the methods cause YES, the music is on. If it is No, then the music is off.
settings.m
static BOOL isMusicEnabled;
#implementation Settings
+ (BOOL)musicEnabled
{
return isMusicEnabled;
}
+ (void)setMusicEnabled:(BOOL)value
{
isMusicEnabled = value;
NSLog(#"SME? %i", isMusicEnabled);
}
#end
Now, the options file is working and i tested that section. The program is reading that isMusicEnabled is getting a new value, thus musicEnabled is being altered as well, so there should be a change and the music should be switched off.
However, nothing happens. I have tried to use debugger, but I am not very good at it and I dont understand a lot of the information i am given. I do understand that the problem is sending the message from Settings file to the main/Game file.
I would appriciate anyone's help who could enlighten me as to how this could be solved.
I'm not familiar with Sparrow Framework, but let me make a guess anyway.
[channel play]; starts playing the music in background until the channel is asked to stop playing.
Changing the isMusicEnabled does not trigger any code to stop the currently playing music. When you change the value in Settings, you should inform the channel to stop (most probably by somehow accessing the channel and calling [channel stop].
There's another problem - isMusicEnabled is just a variable in memory, your program will not remember its state between restarts. And Settings are usually supposed to be remembered.
To summarize I see two problems: persisting settings between restarts first and informing about change of settings second. To remember settings I suggest you look into NSUserDefaults class. To inform the channel to stop playing you have couple of options - depending on you skills. Easiest is to simply access the channel variable from within the setMusicEnabled and call stop. Another option would be to use notifications, but for a beginner programmer that is more complicated (look for NSNotificationCenter if interested).

What's the modern equivalent of GetNextEvent in Cocoa?

I'm porting an archaic C++/Carbon program to Obj-C and Cocoa. The current version uses asynchronous usb reads and GetNextEvent to read the data.
When I try to compile this in Objective C, GetNextEvent isn't found because it's in the Carbon framework.
Searching Apple support yields nothing of use.
EDIT TO ADD:
Ok, so what I'm trying to do is run a document scanner through USB. I have set up the USBDeviceInterface and the USBInterfaceInterface (who came up with THAT name???) and I call (*usbInterfaceInterface)->WritePipeTO() to ask the scanner to scan. I believe this works. AT least the flatbed light moves across the page...
Then I try to use *(usbInterfaceInterface))->ReadPipeAsyncTO() to read data. I give this function a callback function, USBDoneProc().
The general structure is:
StartScan()
WaitForScan()
StartScan() calls the WritePipeTO and the ReadPipeAsyncTO
WaitForScan() has this:
while (deviceActive) {
EventRecord event;
GetNextEvent(0,&event);
if (gDataPtr != saveDataPtr) { // more data up the timeout
timeoutTicks = TickCount() + 60 * 60;
saveDataPtr = gDataPtr;
}
if (TickCount() > timeoutTicks) {
deviceActive = false;
}
}
Meanwhile, USBDoneProc incrementing gDataPtr to be the end of the data that we've read so far. It gets called several times during the asynchronous read, called automatically by the callback, as far as I can tell.
If I cake out the GetNextEvent() call in the WORKING code the USBDoneProc doesn't get called until the asynchronous readpipe timesout.
So it looks to me that I need something to give control back to the event handler so that the USBRead interrupts can actually interrupt and make the USBDoneProcget called...
Does that make any sense?
thanks.
I suppose the nearest thing to a Cocoa equivalent would be -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]. But bear in mind that GetNextEvent is archaic even for Carbon. The preferred way of handing events is the "don't call us, we'll call you" scheme, where the app calls NSApplicationMain or RunApplicationEventLoop and events are dispatched to you.
EDIT to add: Does you app have a normal event loop? If so, maybe WaitForScan could start a Carbon timer and return to the event loop. Each time the timer fires, do what you did in the WaitForScan loop.
there is a USB hidapi that works for mac on windows.
http://www.signal11.us/oss/hidapi/
may this could be of help to you?
It works fine (I can list the connected USB devices and connect/write/read to a device);
however, if i USB device is connected/disconnected during the runtime of the application, I don't see the new connected/disconnected devices.
See: https://github.com/signal11/hidapi/issues/14
If I add the following code to hidapi, then hidapi detects the new USB devices.
#include <Carbon/Carbon.h>
void check_apple_events() {
printf("check_apple_events\n");
RgnHandle cursorRgn = NULL;
Boolean gotEvent=TRUE;
EventRecord event;
while (gotEvent) {
gotEvent = WaitNextEvent(everyEvent, &event, 0L, cursorRgn);
}
}
I need to compile this on OSX10.5 because it uses Carbon instead of Cocoa.
I am currently looking how to transform this to Cocoa.
you are also trying to move your code to cocoa, right?
let me know if you find out; I'll post it here if I get it.
regards,
David
Have you considered throwing the whole thing out and using Image Kit's new-in-10.6 scanner support instead? Even if it's custom, writing a TWAIN driver for it might be easier (and is certainly better) than trying to twist Cocoa into a GetNextEvent shape.

How to know a video source (webcam) is available or not without creating capture window?

It is quite tricky because I wanna to take the result as a sign for later process. If a window flashes, it would be weird to user.
(This is not an answer, just refreshing the question and adding some details:)
Suppose you need to open a video capture driver (webcam) with code like this (delphi, but easy understandable):
result:= SendMessage(hCapWnd, WM_CAP_DRIVER_CONNECT, FDriverNo, 0);
It works fine, except when camera/webcam is busy (opened by another application, for example moviemaker). Then the capture driver suddenly shows a "select video source" window that blocks your application (but not moviemaker, which keeps recording). SendMessage function becomes modal and will not return until undesired window is closed.
Is there a way to detect if a capture driver is busy with another application before connecting to it?
Thanks
This function return number of available webcams and scanners on your mashine(с++).
int GetNumCam()
{
int MemberIndex = 0;
HDEVINFO dev;
SP_DEVINFO_DATA DeviceInfoData;
DeviceInfoData.cbSize = sizeof(DeviceInfoData);
dev = SetupDiGetClassDevsA(&GUID_DEVINTERFACE_IMAGE, NULL,NULL,DIGCF_PRESENT);
if (dev == NULL)
{
MessageBoxA(0,"it is null..","vse propalo",0);
return -1;
}
else
{
while(SetupDiEnumDeviceInfo(dev,MemberIndex, &DeviceInfoData))
{
MemberIndex++;
}
}
return MemberIndex;
}
I wonder if sending a broadcast message could do. I mean, suppose you send a VFW info request message to all windows in system. Then, all windows actually doing VFW processing will answer their status info and you will know which of them are doing video processing; some kind of shouting "anybody here...?"
But it looks like brute force, or even hacking. May be I'll test it... may be not. I am sure there must be a smarter way to know if a video capture driver is busy with another application.
(btw... anybody here?)
I was afraid it would happen.
First I enumerated all opened windows in system, then executed this instruction for each HWND, which just asks for driver information (pascal syntax):
SendMessage(h, WM_CAP_DRIVER_GET_NAME, length(driver)*sizeof(char), LPARAM(PChar(driver))
According to Msdn help, WM_CAP_DRIVER_GET_NAME results are:
"Returns TRUE if successful or FALSE if the capture window is not connected to a capture driver"
(Bold is mine). So it appears a good way to know:
1-If the window is capturing. So it is applyable to ALL windows, don't matter if they are capturing or not.
2-And if so, it tells you which driver is using.
However, after first test round, the results were:
- Task Manager (it was running) crashed and closed
- Explorer crashed and closed (reopened again automatically)
- Belkin Wireless monitor (my pc's WiFi driver) crashed and closed
- Eset Nod32 antivirus crashed, did not closed
The first conclussion can be that this is a bad way to locate which applications are capturing video in a system. But I must ensure to dismiss the possibility of a bug.
I'll keep reporting.
This is not a good solution my any means but I found out that if you disable and enable the camera in device manager immediately before sending the WM_CAP_DRIVER_CONNECT message then for some reason the video source window does not appear and the function returns and works OK.
So for a script I was working on I had to download devcon.exe and I put "devcon disable *PID_3450*MI_00*" and "devcon enable *PID_3450*MI_00*" immediately before my WM_CAP_DRIVER_CONNECT and it seems to work consistently. Unfortunately you need to run as administrator to be able to disable/enable devices. Again not a proper fix by any means...
(Hardware ID of my cam is USB\VID_0AC8&PID_3450&MI_00)