DesktopWidget

dwcomm source code


//
//  main.m
//  dwcomm
//
//  Created by UncleMiF on 11/3/11.
//  Copyright (c) 2011 Deep IT. All rights reserved.
//

#import <Foundation/Foundation.h>

#define timeout 0

#define DesktopWidgetHostCommand @"DesktopWidgetHostCommand"
#define DesktopWidgetClientCommand @"DesktopWidgetClientCommand"

/*
 
 Usage: ./dwcomm <identifier|bundleID> <command> [<timeout>]
 
 Error codes:
 
 1 - invalid args count
 2 - empty widget identifier/bundleID or command
 3 - can't convert identifier/bundleID or command to UTF-8 encoding
 4 - empty widget identifier/bundleID or command (after args conv.)
 5 - exit by timeout

 Timeout in seconds, 0 to disable waiting for an answer
 (and even disable requesting it at all).
 Default timeout is 0, so it means no wait and no answer is required.
 
 */

@interface DWReply: NSObject
@end

@implementation DWReply

+(void)replyReceived:(NSNotification*)nt
{
 NSString* answer = [[nt userInfo] objectForKey:@"answer"];
 if (answer)
  printf("%s",[answer UTF8String]);
 
 [[NSDistributedNotificationCenter defaultCenter] removeObserver:[DWReply class]];
 
 exit(0);
}

+(NSString*)UUIDString
{
 CFUUIDRef theUUID = CFUUIDCreate(NULL);
 CFStringRef string = CFUUIDCreateString(NULL, theUUID);
 CFRelease(theUUID);
 return [(NSString *)string autorelease];
}

@end

int main (int argc, const char * argv[])
{
 if (argc != 3 && argc != 4)
  return 1;
 
 const char* identifier = argv[1];
 const char* command = argv[2];
 
 if (!strlen(identifier) || !strlen(command))
  return 2;
  
 NSTimeInterval tmi = timeout;
 if (argc == 4)
  tmi = atoi(argv[3]);

 @autoreleasepool
 {
  NSString* idr = [NSString stringWithUTF8String:identifier];
  NSString* cmd = [NSString stringWithUTF8String:command];
  
  if (!idr || !cmd)
   return 3;
  
  if (![idr length] || ![cmd length])
   return 4;
    
  NSDistributedNotificationCenter* dc = [NSDistributedNotificationCenter defaultCenter];
    
  NSString* reply = nil;
  
  if (tmi)
  {
   reply = [DWReply UUIDString];
   [dc addObserver:[DWReply class] selector:@selector(replyReceived:) 
   	name:DesktopWidgetHostCommand object:reply];
  }
  
  [dc postNotificationName:DesktopWidgetClientCommand object:@"script" userInfo:
   [NSDictionary dictionaryWithObjectsAndKeys:idr,@"idr",cmd,@"cmd",reply,@"reply",nil]
        deliverImmediately:YES];
    
  if (tmi)
  {
   [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:tmi]];
   [dc removeObserver:[DWReply class]];
  }
 }
 
 return tmi ? 5 : 0;
}