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
8@implementation FocusTracker
9
10- (instancetype)initWithWindow:(NSWindow*)window {
11  if ((self = [super init])) {
12    NSResponder* current_focus = [window firstResponder];
13
14    // Special case NSTextViews, because they are removed from the
15    // view hierarchy when their text field does not have focus.  If
16    // an NSTextView is the current first responder, save a pointer to
17    // its NSTextField delegate instead.
18    if ([current_focus isKindOfClass:[NSTextView class]]) {
19      id delegate = [(NSTextView*)current_focus delegate];
20      if ([delegate isKindOfClass:[NSTextField class]])
21        current_focus = delegate;
22      else
23        current_focus = nil;
24    }
25
26    if ([current_focus isKindOfClass:[NSView class]]) {
27      NSView* current_focus_view = (NSView*)current_focus;
28      _focusedView.reset([current_focus_view retain]);
29    }
30  }
31
32  return self;
33}
34
35- (BOOL)restoreFocusInWindow:(NSWindow*)window {
36  if (!_focusedView.get())
37    return NO;
38
39  if ([_focusedView window] && [_focusedView window] == window)
40    return [window makeFirstResponder:_focusedView.get()];
41
42  return NO;
43}
44
45@end
46