How do I shut off the Mac screensaver? - objective-c

I'm writing an application that uses Apple's kiosk mode. I would like to disable the screen saver, but the "ScreenSaverDefaults" class reports itself as being 32-bit only. I can change the build to be 32-bit only, but I would like to be able to support 64-bit architectures as well.
Are there any other Frameworks that I should use to disable the screen saver?

First, you need to save the current setting, so you can put it back the way it was before you turned it off:
NSTask *readTask = [[NSTask alloc] init];
[readTask setLaunchPath:#"/usr/bin/defaults"];
NSArray *arguments = [NSArray arrayWithObjects:#"-currentHost", #"read", #"com.apple.screensaver", #"idleTime", nil];
[readTask setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[readTask setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[readTask launch];
[readTask release];
NSData *data = [file readDataToEndOfFile];
NSString *originalValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
So now you have the original value for the screensaver's idleTime. Great! Don't lose that. Now, you have to set the new value:
NSTask *writeTask = [[NSTask alloc] init];
[writeTask setLaunchPath:#"/usr/bin/defaults"];
NSArray *arguments = [NSArray arrayWithObjects:#"-currentHost", #"write", #"com.apple.screensaver", #"idleTime", #"0", nil];
[writeTask setArguments:arguments];
[writeTask launch];
[writeTask release];
And viola! You've just disabled the screensaver. To re-enable it, just use the second block of code again, but pass in originalValue as the last array object rather than #"0", like so:
NSArray *arguments = [NSArray arrayWithObjects:#"-currentHost", #"write", #"com.apple.screensaver", #"idleTime", originalValue, nil]
Enjoy!
Billy
P.S.: One last thing, you may be tempted to save the NSTask objects to re-use them, but don't. They can only be run once, so you'll have to create new ones every time you want to do this.

For anyone searching for how to do this (like I have been doing) and don't want to mess around with editing the preference files, Apple has a proper method to stop the screen saver from starting up while your application is running.
Technical Q&A QA1160: Preventing sleep
Hope this helps.

What I ended up doing was directly reading the com.apple.screensaver preference file and modifying the idleTime and askForPassword values so that the are zero. A simple CFPreferencesSynchronize and all was well!

Related

NSFileManager or NSTask moving filetypes

I've been struggling to find a solution to do what should be a very simple task. I need to move a certain type of file (all zip files in this case) into another directory. I've tried NSTask and NSFileManager but have come up empty. I can move one at a time, but I would like to move them in one shot, at the same time.
- (void)copyFilesTo :(NSString*)thisPath {
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:thisPath];
NSString *filename = nil;
while ((filename = [direnum nextObject] )) {
if ([filename hasSuffix:#".zip"]) {
[fileManager copyItemAtPath:thisPath toPath:newPath];
}
}
}
FAILED - files copied = zeroooo
- (void)copyFilesMaybe :(NSString*)thisPath {
newPath = [newPath stringByAppendingPathComponent:fileName];
task = [[NSTask alloc] init];
[task setLaunchPath: #"/usr/bin/find"];
[task waitUntilExit];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: thisPath, #"-name", #"*.zip", #"-exec", #"cp", #"-f", #"{}", newPath, #"\\", #";", nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
}
Same sad result, no files copied. What the heck am I doing wrong?
In the first case, you aren't using filename in your copy call. You need to construct a full path to the file by combining filename with thisPath and attempting to copy that. Also, the method is -copyItemAtPath:toPath:error:. You left off the last parameter. Try:
NSError* error;
if (![fileManager copyItemAtPath:[thisPath stringByAppendingPathComponent:filename] toPath:newPath error:&error])
// handle error (at least log error)
In the second case, I think your arguments array is wrong. I'm not sure why it includes #"\\". I suspect because at a shell you have to escape the semicolon with a backslash (\;). However, the need to escape the semicolon is because the shell would otherwise interpret it and not pass it to find. Since you're not using a shell, you don't need to do that. (Also, if you did need to escape it, it shouldn't be a separate element of the arguments array. It would be in the same element as the semicolon, like #"\\;".)
Also, are you sure the task has completed? You show the launch but you don't show observing or waiting for its termination. Given that you've set a pipe for its output, you have to read from that pipe to be sure that the subprocess isn't getting stuck writing to it.
I'm not sure why you're calling -waitUntilExit before launching the task. That may be harmless, though.

NSTask launch path not accessible. Works in Xcode. Error shown out of XCode

Ok. There are several questions on stack overflow about this. This question was the only question comes closest to mines, but it uses notifications.
The code is very simple. Create a new empty Mac OSX project and just paste the following code in the applicationDidFinishLaunching: method. It supposed to get the path of any executable file (in this case GIT).
NSTask *aTask = [[NSTask alloc] init];
NSPipe *outputPipe = [NSPipe pipe];
NSPipe *errorPipe = [NSPipe pipe];
[aTask setStandardOutput: outputPipe];
[aTask setStandardError: errorPipe];
[aTask setArguments:[NSArray arrayWithObject:#"which"]];
[aTask setLaunchPath:#"/usr/bin/git"];
NSFileHandle *outputFileHandler = [outputPipe fileHandleForReading];
NSFileHandle *errorFileHandler = [errorPipe fileHandleForReading];
[aTask launch];
[aTask waitUntilExit];
// Task launched now just read and print the data
NSData *data = [outputFileHandler readDataToEndOfFile];
NSString *outPutValue = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSData *errorData = [errorFileHandler readDataToEndOfFile];
NSString *errorValue = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding];
NSLog(#"Error value: %#",errorValue);
NSLog(#"Output Value: %#",outPutValue);
This code sets up two reading pipes and runs one command: which git.
If i run this in XCode i get this results corretly:
Error value: ""
Output Value: /usr/bin/git
If i go to my build/Products/Debug folder and double click the executable file, i get this message printed on the console app:
Question: So, what is really the problem here? please just dont make an alternative solution... I also want to know what the problem is.. thanks.
OK turns out the answer is on stack overflow, but its spread across different questions.
The question was asked here -> Commands with NSTask and here -> NSTask launch path not accessible as well
But their answers as of this date arent clear as to what the problem was. It's only after reading the question from NSTask not picking up $PATH from the user's environment (the question's title was misleading) and with these two answers NSTask not picking up $PATH from the user's environment and Find out location of an executable file in Cocoa that I realized the solution.
It looks like this is about setting up either NS
Task or the user's shell (e.g., ~/.bashrc) so that the correct
environment ($PATH) is seen by NSTask.
Solution:
[task setLaunchPath:#"/bin/bash"];
NSArray *args = [NSArray arrayWithObjects:#"-l",
#"-c",
#"which git", //Assuming git is the launch path you want to run
nil];
[task setArguments: args];
However this assumes the user's shell is always bash and it will fail for others. Solve this by determining the shell.
NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];
NSString *shellString = [environmentDict objectForKey:#"SHELL"];

NSTask with long output (OSX)

I've been digging for an answer for a long time but I never get to a working code.
I have a code that uses dd to generate a file. Sometimes it takes a few minutes depending on the size and I thought it would be great to have a progress bar. So far everything works and is tied up. The progress bar, however, doesn't update because I need to constantly send values to it. I found a way to get the current value, I managed to get pv to display the current data, but now I can't get the output in real time inside the application, except in the log.
So far, this is the best I got to:
// Action:
// dd if=/dev/zero bs=1048576 count=500 |pv -Wn -s <size>|of=/Users/me/Desktop/asd.img
// Be careful, it generates files of 500MB!!
NSTask * d1Task = [[NSTask alloc] init];
NSTask * pvTask = [[NSTask alloc] init];
NSTask * d2Task = [[NSTask alloc] init];
[d1Task setLaunchPath:#"/bin/dd"];
[pvTask setLaunchPath:#"/Users/me/Desktop/pv"];
[d2Task setLaunchPath:#"/bin/dd"];
// For pvTask I use something like...
// [[NSBundle mainBundle] pathForAuxiliaryExecutable: #"pv"]
// ... in the final version.
[d1Task setArguments: [NSArray arrayWithObjects:
#"if=/dev/zero"
, #"bs=1048576"
, #"count=500"
, nil]];
[pvTask setArguments:[NSArray arrayWithObjects:
#"-Wn"
, [ NSString stringWithFormat:#"-s %d", 1048576 * 500]
, nil]];
[d2Task setArguments: [NSArray arrayWithObjects:
#"of=/Users/me/Desktop/file.dmg"
, nil]];
NSPipe * pipeBetween1 = [NSPipe pipe];
[d1Task setStandardOutput: pipeBetween1];
[pvTask setStandardInput: pipeBetween1];
NSPipe * pipeBetween2 = [NSPipe pipe];
[pvTask setStandardOutput: pipeBetween2];
[d2Task setStandardInput: pipeBetween2];
// Missing code here
[d1Task launch];
[pvTask launch];
[d2Task launch];
In the missing code part, I tried several things. First I tried an observer, like this:
NSFileHandle * pvOutput = [pipeBetween2 fileHandleForReading];
[pvOutput readInBackgroundAndNotify];
[ [NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(outputData:)
name:NSFileHandleDataAvailableNotification
object:pvOutput
];
No success. I get feedback only in the beginning or the end of the execution, but still no feedbacks during it.
I also tried something like:
[pvOutput setReadabilityHandler:^(NSFileHandle *file) {
// Stuff here
}];
But there is no such method here. Maybe my XCode is outdated? (I use 4.2).
Lately I've been trying the same generic code using /sbin/ping pinging 10 times a server, but no success getting the output. How can I do this? Any documents I can read about this subject?
Thanks!
The pv tool writes the progress output to standard error, so you should establish
another pipe:
NSPipe *pvStderrPipe = [NSPipe pipe];
[pvTask setStandardError:pvStderrPipe];
NSFileHandle *pvError = [pvStderrPipe fileHandleForReading];
[pvError waitForDataInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification
object:pvError queue:nil
usingBlock:^(NSNotification *note)
{
NSData *progressData = [pvError availableData];
NSString *progressStr = [[NSString alloc] initWithData:progressData encoding:NSUTF8StringEncoding];
NSLog(#"progress: %#", progressStr);
[pvError waitForDataInBackgroundAndNotify];
}];
A completely different solution might be to use the following feature of "dd":
If dd receives a SIGINFO signal,
the current input and output block counts will be written to the
standard error output in the same format as the standard completion
message.
So you could connect a pipe to stderr of "dd" and call
kill([ddTask processIdentifier], SIGINFO);
at regular intervals. Then you don't need "pv" and probably only one "dd" task.

Code to use NSTask with ps to verify a process is running

I am having endless problems checking to see if the screen saver is running. If I use an NSTask with ps, it crashes or hangs on a lot of users. If I use notifications it seems to be spotty for others.
Any ideas as to why this NSTask is flakey? (Yes, I know it's messy for now as I debug)
-(BOOL)checkScreenSaverRunning
{
MYLog(#"Building task to check screen saver running");
BOOL foundSaver=FALSE;
NSTask *task;
int i;
task = [[NSTask alloc] init];
[task setLaunchPath: #"/bin/ps"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: #"-ax", nil];
[task setArguments: arguments];
NSPipe *stdpipe;
stdpipe = [NSPipe pipe];
[task setStandardOutput: stdpipe];
NSFileHandle *stdfile;
stdfile = [stdpipe fileHandleForReading];
MYLog(#"Launching task to check screen saver running");
[task launch];
while ([task isRunning]){
NSData *stddata;
stddata = [stdfile readDataToEndOfFile];
if([stddata length]>0){
NSString *stdstring = [[NSString alloc] initWithData:stddata
encoding:NSUTF8StringEncoding];
NSArray *stdReturnValues=[stdstring componentsSeparatedByString:#"\n"];
for(i=0;i<[stdReturnValues count];i++){
if([[stdReturnValues objectAtIndex:i]
rangeOfString:#"ScreenSaverEngine"].location != NSNotFound){
foundSaver=TRUE;
MYLog(#"Found screensaver in running processes");
}
}
[stdstring release];
stdstring=nil;
}
}
MYLog(#"Task ended");
[task release];
if(foundSaver)screenSaverIsActive=TRUE;
else screenSaverIsActive=FALSE;
return(foundSaver);
}
What is your higher-level purpose for wanting to know if the screen saver is running? There may be a better way to accomplish that.
If you're trying to diagnose a crash or a hang, show the crash or hang report.
Anyway, if you're going to spawn a subprocess for this, you should probably use killall -0 ScreenSaverEngine instead of ps. killall will find a process by name for you. Using the signal 0 (-0) means "just test for process existence, don't actually signal it". Do [task setStandardError:[NSFileHandle fileHandleWithNullDevice]] to make sure its output goes nowhere. You determine if the process existed by examining the success or failure status of the task after it terminates.

New Homebrew Gui mac os project, learning objective-c

I am trying to build a Gui for homebrew on mac , with objective-c, but when i try to see the installed packages with the following code it return empty but if i try other command like update it gives me the result, I tried the same with java and the same error occurs.
Git page: feel free to help the project, the code might have a lot of errors I am new to objective-c.
NSTask *task;
task=[[NSTask alloc]init];
[task setLaunchPath:#"/Users/rogeriop062/homebrew/bin/brew"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects:#"list",nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe =[NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file;
file=[pipe fileHandleForReading];
[task launch];
NSMutableData *data=[NSMutableData dataWithCapacity:1000];
while ([task isRunning]) {
[data appendData:[file readDataToEndOfFile]];
}
[data appendData:[file readDataToEndOfFile]];
NSString *string;
string =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result: %#\n",string);
That's an interesting project; good for you! Homebrew works very nicely on my Mac. I can't see anything wrong with your code. I pasted your code into a test routine on my iMac and it worked perfectly. It listed the programs that I had installed with brew. One per line, which I didn't expect, but it worked. Sorry.
You could also try this. Delete everything in your method from[task launch] to the end, and replace it with this:
task.terminationHandler = ^(NSTask *blockTask) {
NSMutableData *data=[NSMutableData dataWithCapacity:1000];
[data appendData:[file readDataToEndOfFile]];
NSString * string =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result: %#\n",string);
};
[task launch];
and that produces the same results as your code on my machine - it works, I'm afraid - but it will not take compute time waiting for the result.