summaryrefslogtreecommitdiffstats
path: root/content/browser/find_pasteboard.mm
blob: 2d61db1f88c2db8b906b245d8f94f500b0d1aa77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "content/browser/find_pasteboard.h"

#include "base/logging.h"
#include "base/sys_string_conversions.h"

NSString* kFindPasteboardChangedNotification =
    @"kFindPasteboardChangedNotification_Chrome";

@implementation FindPasteboard

+ (FindPasteboard*)sharedInstance {
  static FindPasteboard* instance = nil;
  if (!instance) {
    instance = [[FindPasteboard alloc] init];
  }
  return instance;
}

- (id)init {
  if ((self = [super init])) {
    findText_.reset([[NSString alloc] init]);

    // Check if the text in the findboard has changed on app activate.
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(loadTextFromPasteboard:)
               name:NSApplicationDidBecomeActiveNotification
             object:nil];
    [self loadTextFromPasteboard:nil];
  }
  return self;
}

- (void)dealloc {
  // Since this is a singleton, this should only be executed in test code.
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}

- (NSPasteboard*)findPboard {
  return [NSPasteboard pasteboardWithName:NSFindPboard];
}

- (void)loadTextFromPasteboard:(NSNotification*)notification {
  NSPasteboard* findPboard = [self findPboard];
  if ([[findPboard types] containsObject:NSStringPboardType])
    [self setFindText:[findPboard stringForType:NSStringPboardType]];
}

- (NSString*)findText {
  return findText_;
}

- (void)setFindText:(NSString*)newText {
  DCHECK(newText);
  if (!newText)
    return;

  DCHECK([NSThread isMainThread]);

  BOOL needToSendNotification = ![findText_.get() isEqualToString:newText];
  if (needToSendNotification) {
    findText_.reset([newText copy]);
    NSPasteboard* findPboard = [self findPboard];
    [findPboard declareTypes:[NSArray arrayWithObject:NSStringPboardType]
                       owner:nil];
    [findPboard setString:findText_.get() forType:NSStringPboardType];
    [[NSNotificationCenter defaultCenter]
        postNotificationName:kFindPasteboardChangedNotification
                      object:self];
  }
}

@end

string16 GetFindPboardText() {
  return base::SysNSStringToUTF16([[FindPasteboard sharedInstance] findText]);
}