The Road to Code: The Glue That Binds
Volume Number: 25
Issue Number: 09
Column Tag: Road to Code
The Road to Code: The Glue That Binds
Copy and paste
by Dave Dribin
One of the hallmark features of modern GUI applications is the ability to copy content and paste it into either the same or a second, separate application. In this month's article, we are going to add copy and paste to the Favorite Word application that we developed in the June 2009 article. As a quick refresher, our application has a single window with a custom view that displays your favorite word, as shown in Figure 1.
Figure 1: Favorite Word window
The word can currently only be set in the application's preferences. We're going to add the ability to copy, cut, and paste the word in the custom view. In addition, if the user pastes a word, we're going to update the word in the preferences.
It turns out that our application already has an Edit menu along with the Cut, Copy, and Paste menu items, since they're included with the standard application template. However, if you open the Edit menu, you'll notice that all three are grayed out, as shown in Figure 2.
Figure 2: Disabled Cut, Copy, and Paste
Before we delve into the code changes needed to bring copy, cut, and paste to our application, we need to cover the first responder, the responder chain, and nil-targeted actions topics.
Responders
In the April article, A Window with a View, we talked about the view hierarchy and the NSResponder class. As a quick overview, the view hierarchy is how views (subclasses of NSView) are arranged inside a window. For example, the window in Figure 3 has a view hierarchy as shown in Figure 4.
Figure 3: Window with text field and button
Figure 4: View hierarchy
Also, the NSResponder class is the base class for all classes that participate in the Cocoa event handling system, and the NSView class is a subclass of NSResponder. This makes all views capable of handling events. In the April article, you learned how to handle mouse events by overriding the mouseDown:, mouseUp:, and mouseDragged: methods of NSResponder.
First Responder
Even though windows contain multiple views, keyboard events are only routed to one view that has the users focus. This focused view is designated as the first responder. The first responder is the first view that is given the opportunity to handle user events. It doesn't have to handle events, but it has the first opportunity to do so. As the user clicks or tabs around to other views in the window, the first responder changes.
The way the first responder changes is a bit complicated, because the current first responder may refuse to give up its first responder status, or the view the user clicks on may reject first responder status.
Responder Chain
I mentioned above that the first responder gets first crack at handling keyboard events. If a view decides not to handle the event, the application keeps trying to find a responder that does handle the event. The application will next ask the first responder's super view to handle the event. If this view does not handle the event, it continues up the view hierarchy. If none of the views handle the event, the NSWindow gets a chance to handle the event, and finally an NSWindowController, if there is one.
Nil-Targeted Actions
In some case, the responder chain is also used for handling actions. In previous articles, we've used a specific target and selector to handle actions. For example, when we connect up a button's action in Interface Builder by control-dragging to our controller class, it sets the target and selector of the button's action. If we were to emulate this in code, it would look like:
[button setTarget:controller];
[button setAction:@selector(buttonPressed:)];
This tells the button selector, in this case buttonPressed:, to call on a specific object, controller. However, the target does not need to be a specific object. It can be set to nil which has special meaning: to call the action selector on the first responder. If the first responder does not implement the action selector, then the application tries to find some object to which to send the action. To do this, it uses the responder chain in a similar manner to what I described above for handling key events. The precise nature of the responder chain for nil-targeted actions is a bit complicated, so for the exact rules, I suggest you read the Cocoa Event-Handling Guide on the Apple's developer site. The important point to note is that the first responder gets to handle nil-target events.
Handling Copy, Cut, and Paste Actions
So how does all this fit into copy, cut, and paste? As it turns out the Copy, Cut, and Paste menu items are not disabled because they are not connected up to anything. They are actually connected to an action selector, but they are nil-targeted actions. The copy, cut, and paste menu items are connected to the following action selectors, respectively:
- (IBAction)copy:(id)sender;
- (IBAction)cut:(id)sender;
- (IBAction)paste:(id)sender;
The reason why the menu items are grayed out is because neither the first responder nor any object in the responder chain implements these methods. To fix this, we need make sure our custom view, WordView, becomes first responder and then implement these methods.
NSView has a method named acceptsFirstResponder that returns a BOOL:
- (BOOL)acceptsFirstResponder;
The default implementation of this method returns NO, meaning it cannot become the first responder. Since our view currently cannot become the first responder, it does not become part of the responder chain, and thus is not eligible to handle the copy, cut, and paste action methods. Thus, our first step is to override this method to return YES in WordView.m:
- (BOOL)acceptsFirstResponder
{
return YES;
}
Next, we need to implement the action methods, but let's just use stubs for now, just to make sure we've got everything hooked up right:
- (IBAction)copy:(id)sender
{
NSLog(@"Copy");
}
- (IBAction)cut:(id)sender
{
NSLog(@"Cut");
}
- (IBAction)paste:(id)sender
{
NSLog(@"Paste");
}
If you run the application at this point, the Cut, Copy, and Paste menu items should be selectable, and if you chose one, you should see the appropriate log message.
How did that happen? Since our custom view is the only view in the window, the window is going to ask it if it wants to become the first responder. Since the view accepts first responder status, it becomes the first responder. When the user clicks the Edit menu, the application checks the responder chain for an object to handle the cut:, copy:, and paste: action methods. Since our custom view does, and it's the first responder, the application knows it can send these actions to our view and makes the menu items available. When the user actually selects, for example, the Copy menu item, the application sends the action to our view.
The Pasteboard
We've got the user interface working properly, but now we actually need to implement the action methods. Copy and paste between applications is handled by the pasteboard. The pasteboard lives outside of all applications and acts as a mediator between them to support copy and paste. When a user copies some text, the source application puts this text on the pasteboard. When the user pastes in another application, the receiving application retrieves the text from the pasteboard.
Cocoa has a class called NSPasteboard that provides an interface to the pasteboard. It handles the low-level inter-process communication and makes implementing copy and paste relatively straightforward.
To implement copy, an application puts data on the pasteboard. An application may put multiple representations of the data on the pasteboard. For example, an application may put styled text as RTF or PDF as well as plain text on the pasteboard. The application that receives data from the pasteboard can choose the best representation for its needs. For example, TextEdit may choose the styled text whereas Terminal may choose the plain text.
Putting Data on the Pasteboard
To put data on the pasteboard, you first need an instance of the NSPasteboard class. Then you tell it what types of data you are going to put on the pasteboard. And finally, you put the actual data for each type on the pasteboard. Here's code to put a string on the pasteboard:
NSString * string = @"a string";
NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
NSArray * types = [NSArray arrayWithObject:NSStringPboardType];
[pasteboard declareTypes:types owner:nil];
[pasteboard setString:string forType:NSStringPboardType];
While we are using a static string, the string variable would come from the view, as we shall soon see. There are multiple different pasteboards in the system, but the general pasteboard is used for copy and paste. You can get a reference to the general pasteboard by using the +generalPasteboard class method. The declareTypes:owner: method tells the pasteboard which types of data you are going to put on the pasteboard. You pass it an array of types, ordered by preference of type, with the preferred type first. The NSStringPboardType is a constant for plain text type. If an application uses rich text and plain text, it probably wants to use the rich text first. Since this example uses only plain text, that's all we need. Finally, we put the plain text on the pasteboard using the setString:forType: method.
When an application declares the types it's going to put on the pasteboard, it gives the pasteboard an owner. This is because it may not want to put the actual data on the pasteboard immediately. Say an application wants to put an image on the pasteboard in multiple formats. It's rather wasteful to put all image types on the pasteboard immediately. In these cases, the source application may put a promise on the pasteboard. When and if another application requests the data from the pasteboard, the pasteboard will ask the owner to provide the data and fulfill the promise. Since we are providing all the data immediately, we do not have to set the owner.
Reading Data from the Pasteboard
Just as the sending application may put multiple types of data on the pasteboard, the receiving application may accept multiple types. Again, the application specifies which types it can support, and then, if the pasteboard contains any of those types, it retrieves the data. The code to retrieve a string from the pasteboard looks like this:
NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
NSArray * types = [NSArray arrayWithObject:NSStringPboardType];
NSString * bestType = [pasteboard availableTypeFromArray:types];
if (bestType != nil)
{
NSString * value =
[pasteboard stringForType:NSStringPboardType];
// Use pasted value
}
Again, this code uses the general pasteboard. The availableTypeFromArray: returns the best type of all those specified in the array or nil if none of the types are available. Finally, the stringForType: method retrieves the actual string from the pasteboard.
Implementing Copy
Armed with our new knowledge of the pasteboard, we can now implement copy for our WordView custom view. Since this view uses styled text to draw the string using an attributed string, it can put both styled text and plain text on the pasteboard. It's easy to get an RTF representation of an attributed string, so we can use RTF as the styled text type.
As a refresher, here is the drawRect: method that creates an attributed string:
- (void)drawWord
{
NSRect bounds = [self bounds];
bounds = NSInsetRect(bounds, 4.0, 4.0);
NSFont * font = [NSFont systemFontOfSize:50];
NSDictionary * attributes =
[NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
NSAttributedString * string =
[[NSAttributedString alloc] initWithString:_word
attributes:attributes];
NSSize stringSize = [string size];
NSPoint point;
// Center vertically
point.y = bounds.size.height/2 - stringSize.height/2;
// Align horizonally
if (_textAlignment == WordViewCenterTextAlignment)
point.x = bounds.size.width/2 - stringSize.width/2;
else if (_textAlignment == WordViewLeftTextAlignment)
point.x = bounds.origin.x;
else if (_textAlignment == WordViewRightTextAlignment)
point.x = bounds.size.width - stringSize.width;
[string drawAtPoint:point];
}
We are creating an attributed string with a font size of 50 points. Since we can use the attributed string in our copy: method, we can re-use this code by extracting t into its own method. Extracting code into a method is one of the refactoring types that Xcode supports, so let's use it to help us out.
To do this, you select the code you want to extract, as shown in Figure 5, and then choose the Edit > Refactor... menu. Xcode then analyzes the code and pops up a dialog box to name this new method. Name it wordAsAttributedString, and then chose Preview followed by Apply.
Figure 5: Selection to extract
Xcode creates the method and calls it where your selection was. I typically fix up the indentation and coding style a bit, but this refactoring tool does help automate creating a new method from existing code. In the end, this new method should look like this:
- (NSAttributedString *)wordAsAttributedString
{
NSFont * font = [NSFont systemFontOfSize:50];
NSDictionary * attributes =
[NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
NSAttributedString * string =
[[NSAttributedString alloc] initWithString:_word
attributes:attributes];
return string;
}
We can now write a method that puts the word on the pasteboard, in both rich text and plain text:
- (void)writeToPasteboard:(NSPasteboard *)pasteboard
{
NSArray * types = [NSArray arrayWithObjects:
NSRTFPboardType, NSStringPboardType, nil];
[pasteboard declareTypes:types owner:nil];
[pasteboard setString:_word forType:NSStringPboardType];
NSAttributedString * attributedWord = [self wordAsAttributedString];
NSRange fullRange = NSMakeRange(0, [attributedWord length]);
NSData * rtfData = [attributedWord RTFFromRange:fullRange
documentAttributes:nil];
[pasteboard setData:rtfData forType:NSRTFPboardType];
}
This code is similar to the simple case we looked at above for writing a plain text string. In this case, the pasteboard is being passed in, to make this code more generic. It is also declaring two types, an RTF type and a plain text string type. Setting the string data is simple enough, since we can use the _word instance variable. Setting the RTF data is a bit more involved because we have to specify the range of characters. We create a range that encompasses the full string. And finally, it sets the RTF data using the setData:forType: method.
All we have left to do is to call this method from the copy: method:
- (IBAction)copy:(id)sender
{
NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
[self writeToPasteboard:pasteboard];
}
With this code in place, we can now finally test out copy. Run the application and chose the Edit > Copy menu item. Now run TextEdit and chose Edit > Paste in a new document. The TextEdit document should contain the word "Cocoa" with in same font and size that we used in our application, as shown in Figure 6.
Figure 6: Pasted RTF
If you try pasting in a plain text document or an application like the Terminal, then only the word "Cocoa" is pasted, without the font style. This is because our application put both rich and plain text on the pasteboard.
Implementing Paste
With copy implemented, we now need to implement paste. In a similar fashion, we are going to use a generic method to read from a pasteboard, as follows:
- (BOOL)readFromPasteboard:(NSPasteboard *)pasteboard
{
NSArray * supportedTypes =
[NSArray arrayWithObject:NSStringPboardType];
NSString * bestType =
[pasteboard availableTypeFromArray:supportedTypes];
if (bestType == nil)
return NO;
NSString * value =
[pasteboard stringForType:NSStringPboardType];
NSCharacterSet * whitespace =
[NSCharacterSet whitespaceCharacterSet];
value = [value stringByTrimmingCharactersInSet:whitespace];
NSArray * words =
[value componentsSeparatedByCharactersInSet:whitespace];
if ([words count] != 1)
return NO;
self.word = value;
return YES;
}
To simplify matters, we are only going to accept plain text type. This method returns a BOOL that returns YES if it did update the word from the pasteboard, otherwise NO. Since our view is only supposed to show a single word, it also ensures that there's only one word on the pasteboard.
This code retrieves a plain text string from the pasteboard, as previously demonstrated, returning NO if the plain text type is not available. Next, we need to count the number of words in this string. First, we use the stringByTrimmingCharactersInSet: method to remove leading and trailing whitespace characters. The whitespace character set includes the space and tab characters. After removing any leading and trailing whitespace, we split the string into words by using componentsSeparatedByCharactersInSet:. If the number of words is not one, then we abort and return NO. If there is a single word, we set our word to this new word and return YES.
To complete our paste implementation, we need to implement the paste: method as follows:
- (IBAction)paste:(id)sender
{
NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
if (![self readFromPasteboard:pasteboard])
NSBeep();
}
Again, we use the general pasteboard. If reading from the pasteboard fails, we beep to let the user know something has gone wrong.
Implementing Cut
Cut is similar to a copy followed by a delete action. Thus we could implement cut: as follows:
- (IBAction)cut:(id)sender
{
[self copy:sender];
self.word = @"";
}
Updating User Preferences
We've now finished updating our WordView. The application stores the user's favorite word in its preferences. As a final touch, we'd like to update the user preferences when the user pastes in a new word. Since the view is supposed to be a generic word view, we don't want to put this logic in the view. Thus, the main window controller needs to watch for changes to the view's word and update the preferences. Thankfully, our view is fully key-value coding (KVC) compliant, so we can use key-value observing (KVO) to be notified of changes to the word. At the end of the awakeFromNib method add this bit of code:
[_wordView addObserver:self
forKeyPath:@"word"
options:0
context:&WordChangedContext];
In the observer method, we want to update the user defaults:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == &WordChangedContext)
{
NSUserDefaults * defaults =
[NSUserDefaults standardUserDefaults];
[defaults setObject:_wordView.word
forKey:FavoriteWordKey];
}
}
Unfortunately, this code has a serious bug. The main window controller is already observing changes to user defaults and updates the word view if it changes. The code as it stands results in an infinite loop. Updating the default value sets the word view's word, which again triggers the key-value observing method. This in turn sets the default again, ad infinitum.
To fix this, we don't want to update the word view's word if the default changed due to a KVO trigger. We use a new instance variable, _wordUpdatingFromView that is set to YES during our KVO method:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == &WordChangedContext)
{
_wordUpdatingFromView = YES;
NSUserDefaults * defaults =
[NSUserDefaults standardUserDefaults];
[defaults setObject:_wordView.word
forKey:FavoriteWordKey];
_wordUpdatingFromView = NO;
}
}
Finally, we need to update our notification method to use this new instance variable, as well:
- (void)updateFromDefaults:(NSNotification *)notification
{
NSUserDefaults * defaults =
[NSUserDefaults standardUserDefaults];
if (!_wordUpdatingFromView)
_wordView.word = [defaults objectForKey:FavoriteWordKey];
NSData * colorData = [defaults objectForKey:BackgroundColorKey];
NSColor * color =
[NSKeyedUnarchiver unarchiveObjectWithData:colorData];
_wordView.backgroundColor = color;
WordViewTextAlignment alignment =
[defaults integerForKey:TextAligmentKey];
_wordView.textAlignment = alignment;
}
The only modification from our previous version is these two lines:
if (!_wordUpdatingFromView)
_wordView.word = [defaults objectForKey:FavoriteWordKey];
This protects from the infinite loop, only updating the word view if it wasn't initiated from the word view itself.
Conclusion
In this article, we've learned all about the first responder, the responder chain, nil-target actions, and also the pasteboard. And we've put all of these concepts together so we could implement copy, paste, and cut. As usual, the full code is available on the MacTech website.