summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/cocoa/chrome_to_mobile_bubble_controller.mm
blob: 4bce3eb1524985405dd795f462fd3830f05e294f (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright (c) 2012 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 "chrome/browser/ui/cocoa/chrome_to_mobile_bubble_controller.h"

#include "base/mac/mac_util.h"
#include "base/memory/weak_ptr.h"
#include "base/sys_string_conversions.h"
#include "chrome/browser/chrome_to_mobile_service_factory.h"
#import "chrome/browser/ui/cocoa/browser_window_controller.h"
#import "chrome/browser/ui/cocoa/info_bubble_view.h"
#import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h"
#include "content/public/browser/notification_service.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/text/bytes_formatting.h"

namespace {

// The verical padding between the radio group and the send copy checkbox.
const CGFloat kVerticalPadding = 10;

// The duration of the "Sending..." progress throb animation in seconds.
const NSTimeInterval kProgressThrobDurationS = 1.2;

// The seconds to delay before automatically closing the bubble after sending.
const NSTimeInterval kCloseS = 3;

}  // namespace

ChromeToMobileBubbleNotificationBridge::ChromeToMobileBubbleNotificationBridge(
    ChromeToMobileBubbleController* controller,
    SEL selector)
    : controller_(controller),
      selector_(selector) {
  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
                 content::NotificationService::AllSources());
  registrar_.Add(this, content::NOTIFICATION_TAB_CLOSED,
                 content::NotificationService::AllSources());
}

// All observed notifications perform the same selector to close the bubble.
void ChromeToMobileBubbleNotificationBridge::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  [controller_ performSelector:selector_ withObject:controller_];
}

void ChromeToMobileBubbleNotificationBridge::SnapshotGenerated(
    const FilePath& path,
    int64 bytes) {
  [controller_ snapshotGenerated:path bytes:bytes];
}

void ChromeToMobileBubbleNotificationBridge::OnSendComplete(bool success) {
  [controller_ onSendComplete:success];
}

@interface ChromeToMobileBubbleController (Private)
// Construct and start the "Sending..." progress animation.
- (void)startProgressAnimation;

// Handle the "Sending..." progress animation.
- (void)animation:(NSAnimation *)animation
    didReachProgressMark:(NSAnimationProgress)progress;
@end

@implementation ChromeToMobileBubbleController

- (id)initWithParentWindow:(NSWindow*)parentWindow
                   profile:(Profile*)profile {
  self = [super initWithWindowNibPath:@"ChromeToMobileBubble"
                         parentWindow:parentWindow
                           anchoredAt:NSZeroPoint];
  if (self) {
    service_ = ChromeToMobileServiceFactory::GetForProfile(profile);
  }
  return self;
}

- (void)windowWillClose:(NSNotification*)notification {
  // We caught a close so we don't need to observe further notifications.
  bridge_.reset(NULL);
  [progressAnimation_ stopAnimation];
  // Cancel any delayed requests that may still be pending (close, etc.).
  [NSObject cancelPreviousPerformRequestsWithTarget:self];
  [super windowWillClose:notification];
}

// Override -[BaseBubbleController showWindow:] to set up UI elements.
- (void)showWindow:(id)sender {
  // Force load the NIB.
  NSWindow* window = [self window];

  // Get the list of mobile devices.
  mobiles_ = service_->mobiles();
  DCHECK_GT(mobiles_.size(), 0U);
  if (mobiles_.size() == 1) {
    // Set the single device title; it's for multiple devices by default.
    string16 name;
    mobiles_[0]->GetString("name", &name);
    NSString* title =
        l10n_util::GetNSStringF(IDS_CHROME_TO_MOBILE_BUBBLE_SINGLE_TITLE, name);
    [title_ setStringValue:title];
  } else {
    // Initialize the mobile device radio buttons.
    [mobileRadioGroup_ renewRows:mobiles_.size() columns:1];
    NSArray* cellArray = [mobileRadioGroup_ cells];
    for (NSUInteger i = 0; i < mobiles_.size(); ++i) {
      string16 name;
      mobiles_[i]->GetString("name", &name);
      [[cellArray objectAtIndex:i] setTitle:SysUTF16ToNSString(name)];
    }
    [mobileRadioGroup_ setEnabled:YES];
    [mobileRadioGroup_ setHidden:NO];
    [mobileRadioGroup_ sizeToCells];

    // Adjust the window size to accommodate the radio group.
    CGFloat deltaY = [mobileRadioGroup_ frame].size.height + kVerticalPadding;
    NSRect windowFrame = [window frame];
    windowFrame.size.height += deltaY;
    [window setFrame:windowFrame display:YES animate:NO];
  }

  // Get the anchor point for the bubble in screen coordinates.
  BrowserWindowController* controller = [BrowserWindowController
      browserWindowControllerForWindow:self.parentWindow];
  if ([controller isKindOfClass:[BrowserWindowController class]]) {
    LocationBarViewMac* locationBar = [controller locationBarBridge];
    NSPoint bubblePoint = locationBar->GetChromeToMobileBubblePoint();
    [self setAnchorPoint:[self.parentWindow convertBaseToScreen:bubblePoint]];
  }
  [self.bubble setArrowLocation:info_bubble::kTopRight];

  // Initialize the checkbox to send an offline copy.
  NSString* sendCopyString =
      l10n_util::GetNSStringF(IDS_CHROME_TO_MOBILE_BUBBLE_SEND_COPY,
          l10n_util::GetStringUTF16(
              IDS_CHROME_TO_MOBILE_BUBBLE_SEND_COPY_GENERATING));
  [sendCopy_ setTitle:sendCopyString];
  [sendCopy_ setState:NSOffState];

  // Observe Chrome and ChromeToMobileService changes.
  bridge_.reset(new ChromeToMobileBubbleNotificationBridge(
      self, @selector(cancel:)));

  // Generate the MHTML snapshot now to report its size in the bubble.
  service_->GenerateSnapshot(bridge_->AsWeakPtr());

  // Request a mobile device list update.
  service_->RequestMobileListUpdate();

  [super showWindow:sender];
}

- (IBAction)send:(id)sender {
  int index = (mobiles_.size() > 1) ? [mobileRadioGroup_ selectedRow] : 0;
  DCHECK_GE(index, 0);

  string16 mobileId;
  mobiles_[index]->GetString("id", &mobileId);
  FilePath path = ([sendCopy_ state] == NSOnState) ? snapshotPath_ : FilePath();
  service_->SendToMobile(mobileId, path, bridge_->AsWeakPtr());

  // Update the bubble's contents to show the "Sending..." progress animation.
  [cancel_ setEnabled:NO];
  [send_ setEnabled:NO];
  [send_ setAlignment:NSNaturalTextAlignment];
  [self startProgressAnimation];
}

// By implementing this, ESC causes the window to go away.
- (IBAction)cancel:(id)sender {
  [self close];
}

- (void)snapshotGenerated:(const FilePath&)path
                    bytes:(int64)bytes {
  NSString* text = nil;
  if (bytes > 0) {
    snapshotPath_ = path;
    [sendCopy_ setEnabled:YES];
    text = l10n_util::GetNSStringF(IDS_CHROME_TO_MOBILE_BUBBLE_SEND_COPY,
                                   ui::FormatBytes(bytes));
  } else {
    text = l10n_util::GetNSString(IDS_CHROME_TO_MOBILE_BUBBLE_SEND_COPY_FAILED);
  }
  [sendCopy_ setTitle:text];
  [sendCopy_ setState:NSOffState];
}

- (void)onSendComplete:(bool)success {
  [progressAnimation_ stopAnimation];
  [send_ setAlignment:NSCenterTextAlignment];

  NSString* text = nil;
  if (success) {
    text = l10n_util::GetNSString(IDS_CHROME_TO_MOBILE_BUBBLE_SENT);
    [self performSelector:@selector(cancel:) withObject:nil afterDelay:kCloseS];
  } else {
    text = l10n_util::GetNSString(IDS_CHROME_TO_MOBILE_BUBBLE_ERROR);
    [error_ setHidden:NO];
  }
  [send_ setTitle:text];
}

- (void)startProgressAnimation {
  progressAnimation_.reset([[NSAnimation alloc]
      initWithDuration:kProgressThrobDurationS
        animationCurve:NSAnimationLinear]);
  [progressAnimation_ setAnimationBlockingMode:NSAnimationNonblocking];
  [progressAnimation_ setDelegate:self];
  [progressAnimation_ setProgressMarks:[NSArray arrayWithObjects:
      [NSNumber numberWithFloat:0.00], [NSNumber numberWithFloat:0.25],
      [NSNumber numberWithFloat:0.50], [NSNumber numberWithFloat:0.75],
      [NSNumber numberWithFloat:1.00], nil]];
  [progressAnimation_ startAnimation];
}

- (void)animation:(NSAnimation *)animation
    didReachProgressMark:(NSAnimationProgress)progress {
  DCHECK_EQ(animation, progressAnimation_.get());
  int id = IDS_CHROME_TO_MOBILE_BUBBLE_SENDING_3;
  // Show each of four messages for 1/4 of the animation.
  if (progress < 0.25) {
    id = IDS_CHROME_TO_MOBILE_BUBBLE_SENDING_0;
  } else if (progress < 0.50) {
    id = IDS_CHROME_TO_MOBILE_BUBBLE_SENDING_1;
  } else if (progress < 0.75) {
    id = IDS_CHROME_TO_MOBILE_BUBBLE_SENDING_2;
  } else if (progress >= 1.00) {
    // Restart the animation to continuously loop.
    [self startProgressAnimation];
  }
  [send_ setTitle:l10n_util::GetNSString(id)];
}

@end  // ChromeToMobileBubbleController

@implementation ChromeToMobileBubbleController (JustForTesting)

- (id)initWithParentWindow:(NSWindow*)parentWindow
                   service:(scoped_refptr<ChromeToMobileService>)service {
  self = [super initWithWindowNibPath:@"ChromeToMobileBubble"
                         parentWindow:parentWindow
                           anchoredAt:NSZeroPoint];
  if (self) {
    service_ = service;
  }
  return self;
}

- (void)setSendCopy:(bool)sendCopy {
  [sendCopy_ setState:(sendCopy ? NSOnState : NSOffState)];
}

- (ChromeToMobileBubbleNotificationBridge*)bridge {
  return bridge_.get();
}

@end  // ChromeToMobileBubbleController (JustForTesting)