frontApp.m 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #import <Cocoa/Cocoa.h>
  2. @interface MDAppController : NSObject <NSApplicationDelegate>
  3. @property (retain) NSString *outfile;
  4. @end
  5. @implementation MDAppController
  6. - (id)init {
  7. if ((self = [super init])) {
  8. [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
  9. selector:@selector(activeAppDidChange:)
  10. name:NSWorkspaceDidActivateApplicationNotification object:nil];
  11. }
  12. return self;
  13. }
  14. - (void)dealloc {
  15. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
  16. [super dealloc];
  17. }
  18. - (void)activeAppDidChange:(NSNotification *)notification {
  19. NSRunningApplication* runningApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
  20. NSString *str = [NSString stringWithFormat:@"%@\n", runningApp.bundleIdentifier];
  21. if (![str writeToFile:[self outfile] atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil]) {
  22. NSLog(@"Unable to write to path: %@", [self outfile]);
  23. }
  24. }
  25. @end
  26. int main(int argc, const char * argv[]) {
  27. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  28. [NSApplication sharedApplication];
  29. MDAppController *appController = [[MDAppController alloc] init];
  30. [NSApp setDelegate:appController];
  31. // Construct a default path or use the provided one
  32. if (argc > 1) {
  33. NSString *str = [NSString stringWithUTF8String: argv[1]];
  34. [appController setOutfile:str];
  35. } else {
  36. NSString *tmpDir = NSTemporaryDirectory();
  37. [appController setOutfile:[NSString stringWithFormat:@"%@plexMonitor/FRONT_APP", tmpDir]];
  38. }
  39. // Force an update at init
  40. [appController activeAppDidChange:nil];
  41. // Wait forever
  42. [NSApp run];
  43. // Never reached
  44. [pool release];
  45. return 0;
  46. }