Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import <Cocoa/Cocoa.h>
- #import <libproc.h>
- #import <string.h>
- #import <stdlib.h>
- #import <stdio.h>
- bool activate_window_of_id(long wid) {
- bool success = false;
- const CGWindowLevel kScreensaverWindowLevel = CGWindowLevelForKey(kCGScreenSaverWindowLevelKey);
- CFArrayRef windowArray = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
- CFIndex windowCount = 0;
- if ((windowCount = CFArrayGetCount(windowArray))) {
- for (CFIndex i = 0; i < windowCount; i++) {
- NSDictionary *windowInfoDictionary = (__bridge NSDictionary *)((CFDictionaryRef)CFArrayGetValueAtIndex(windowArray, i));
- NSNumber *ownerPID = (NSNumber *)(windowInfoDictionary[(id)kCGWindowOwnerPID]);
- NSNumber *level = (NSNumber *)(windowInfoDictionary[(id)kCGWindowLayer]);
- if (level.integerValue < kScreensaverWindowLevel) {
- NSNumber *windowID = windowInfoDictionary[(id)kCGWindowNumber];
- if (wid == windowID.integerValue) {
- CFIndex appCount = [[[NSWorkspace sharedWorkspace] runningApplications] count];
- for (CFIndex j = 0; j < appCount; j++) {
- if (ownerPID.integerValue == [[[[NSWorkspace sharedWorkspace] runningApplications] objectAtIndex:j] processIdentifier]) {
- NSRunningApplication *appWithPID = [[[NSWorkspace sharedWorkspace] runningApplications] objectAtIndex:j];
- [appWithPID activateWithOptions:NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
- char buf[PROC_PIDPATHINFO_MAXSIZE];
- proc_pidpath(ownerPID.integerValue, buf, sizeof(buf));
- NSString *buffer = [NSString stringWithUTF8String:buf];
- long location = [buffer rangeOfString:@".app/Contents/MacOS/" options:NSBackwardsSearch].location;
- NSString *path = (location != NSNotFound) ? [buffer substringWithRange:NSMakeRange(0, location)] : buffer;
- NSString *app = [@" of application \\\"" stringByAppendingString:[path lastPathComponent]];
- NSString *index = [@"set index of window id " stringByAppendingString:[windowID stringValue]];
- NSString *execScript = [[index stringByAppendingString:app] stringByAppendingString:@"\\\" to 1"];
- char *pointer = NULL;
- size_t buffer_size = 0;
- NSMutableArray *array = [[NSMutableArray alloc] init];
- FILE *file = popen([[[@"osascript -e \"" stringByAppendingString:execScript] stringByAppendingString:@"\""] UTF8String], "r");
- while (getline(&pointer, &buffer_size, file) != -1)
- [array addObject:[NSString stringWithUTF8String:pointer]];
- char *error = (char *)[[array componentsJoinedByString:@""] UTF8String];
- if (strlen(error) > 0 && error[strlen(error) - 1] == '\n')
- error[strlen(error) - 1] = '\0';
- if ([[NSString stringWithUTF8String:error] isEqualToString:@""])
- success = true;
- [array release];
- free(pointer);
- pclose(file);
- break;
- }
- }
- }
- }
- }
- }
- CFRelease(windowArray);
- return success;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement