Home | History | Annotate | Download | only in cocoa
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #import "ui/base/cocoa/focus_tracker.h"
      6 
      7 #include "base/basictypes.h"
      8 
      9 @implementation FocusTracker
     10 
     11 - (id)initWithWindow:(NSWindow*)window {
     12   if ((self = [super init])) {
     13     NSResponder* current_focus = [window firstResponder];
     14 
     15     // Special case NSTextViews, because they are removed from the
     16     // view hierarchy when their text field does not have focus.  If
     17     // an NSTextView is the current first responder, save a pointer to
     18     // its NSTextField delegate instead.
     19     if ([current_focus isKindOfClass:[NSTextView class]]) {
     20       id delegate = [(NSTextView*)current_focus delegate];
     21       if ([delegate isKindOfClass:[NSTextField class]])
     22         current_focus = delegate;
     23       else
     24         current_focus = nil;
     25     }
     26 
     27     if ([current_focus isKindOfClass:[NSView class]]) {
     28       NSView* current_focus_view = (NSView*)current_focus;
     29       focusedView_.reset([current_focus_view retain]);
     30     }
     31   }
     32 
     33   return self;
     34 }
     35 
     36 - (BOOL)restoreFocusInWindow:(NSWindow*)window {
     37   if (!focusedView_.get())
     38     return NO;
     39 
     40   if ([focusedView_ window] && [focusedView_ window] == window)
     41     return [window makeFirstResponder:focusedView_.get()];
     42 
     43   return NO;
     44 }
     45 
     46 @end
     47