Search code examples
cocoanspasteboard

Get location (coordinates) of text when getting NSServices information from sender app


This is the code works fine in order to receive and return a NSString from and to another any other app by implementing the NSServices as it is explained here: https://developer.apple.com/library/mac/documentation/cocoa/conceptual/SysServices/Articles/properties.html

 - (void)simpleEncrypt:(NSPasteboard *)pboard
             userData:(NSString *)userData error:(NSString **)error {

  // Test for strings on the pasteboard.
  NSArray *classes = [NSArray arrayWithObject:[NSString class]];
  NSDictionary *options = [NSDictionary dictionary];

  if (![pboard canReadObjectForClasses:classes options:options]) {
    *error = NSLocalizedString(@"Error: couldn't encrypt text.",
                               @"pboard couldn't give string.");
    return;
  }
  // Get and encrypt the string.
  NSString *pboardString = [pboard stringForType:NSPasteboardTypeString];
  NSString *newString = [self rotateLettersInString:pboardString];
  if (!newString) {
    *error = NSLocalizedString(@"Error: couldn't encrypt text.",
                               @"self couldn't rotate letters.");
    return;
  }

  // Write the encrypted string onto the pasteboard.
  [pboard clearContents];
  [pboard writeObjects:[NSArray arrayWithObject:newString]];
}

Is there a way to get the position, location and/or coordinates where the sender app has the selected text in order to show a pop-up exactly in that location?


Solution

  • What you can do is, capture and store the mouse location when user had selected text by double clicking the text. When your application gets control after user as selected your menu from the contextual menu, use the stored mouse location to show the pop-up.

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
      [NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseUpMask handler:
        ^(NSEvent *event)
        {
        if([event clickCount] == 2)
        {
            NSPoint mousePointInScreen = [NSEvent mouseLocation];//store this to a member ivar.    
        }
    }];
    
    [NSApp setServicesProvider:self];
    NSUpdateDynamicServices();
    }
    
    - (void) simpleEncrypt:(NSPasteboard *)pboard
              userData:(NSString *)userData
                 error:(NSString **)error
     {
        //Get the stored mouse location 
        //Perform other tasks
     }