How to read a global selection using MacRuby?

153 Views Asked by At

How can I read a global UI selection within MacRuby? For instance, of selected text in Preview.

Having no experience in Ruby and Cocoa, I've decided to take a plunge and to write a small dictionary app to aid myself with translation. All the pieces are ready, I just need to know how to read selected text on hotkey.

1

There are 1 best solutions below

2
On

You can't, because there isn't one.

There is not one global selection. There is one text selection per text view (or other selectable-text-containing view). A window may have any number of such views, an application may have any number of such windows open, and the user may have any number of such applications running.

A further problem is that not all applications are Cocoa. Of those that are, most are accessible, but not all; custom views may trip you up (think of the Text tool in a graphics editor, for example). If the user selects text in a non-Cocoa application, chances are you won't be able to read it.

If you want to access the selected text in the focused view in the focused window in the focused application, the best way to do that is to make your application provide a Service, which the user can invoke from nearly any Cocoa application and some of the more enlightened Carbon apps. That's the best you can do.

Apple's own Dictionary gets special treatment in AppKit (including the availability of a floating Dictionary panel in Cocoa and Carbon apps), but otherwise works the same way: It provides a service that shows up in every Services menu (if the user hasn't turned it off).