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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
|
// 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.
#include "chrome/browser/download/download_status_updater.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
#include "base/supports_user_data.h"
#import "chrome/browser/ui/cocoa/dock_icon.h"
#include "content/public/browser/download_item.h"
#include "googleurl/src/gurl.h"
// --- Private 10.8 API for showing progress ---
// rdar://12058866 http://www.openradar.me/12058866
namespace {
NSString* const kNSProgressAppBundleIdentifierKey =
@"NSProgressAppBundleIdentifierKey";
NSString* const kNSProgressEstimatedTimeRemainingKey =
@"NSProgressEstimatedTimeRemainingKey";
// NSProgressEstimatedTimeKey is 10.8 SPI only; it became
// NSProgressEstimatedTimeRemainingKey when NSProgress became API in 10.9.
NSString* const kNSProgressEstimatedTimeKey =
@"NSProgressEstimatedTimeKey";
NSString* const kNSProgressFileCompletedCountKey =
@"NSProgressFileCompletedCountKey";
NSString* const kNSProgressFileContainerURLKey =
@"NSProgressFileContainerURLKey";
NSString* const kNSProgressFileDownloadingSourceURLKey =
@"NSProgressFileDownloadingSourceURLKey";
NSString* const kNSProgressFileIconKey =
@"NSProgressFileIconKey";
NSString* const kNSProgressFileIconOriginalRectKey =
@"NSProgressFileIconOriginalRectKey";
NSString* const kNSProgressFileLocationCanChangeKey =
@"NSProgressFileLocationCanChangeKey";
NSString* const kNSProgressFileOperationKindAirDropping =
@"NSProgressFileOperationKindAirDropping";
NSString* const kNSProgressFileOperationKindCopying =
@"NSProgressFileOperationKindCopying";
NSString* const kNSProgressFileOperationKindDecompressingAfterDownloading =
@"NSProgressFileOperationKindDecompressingAfterDownloading";
NSString* const kNSProgressFileOperationKindDownloading =
@"NSProgressFileOperationKindDownloading";
NSString* const kNSProgressFileOperationKindEncrypting =
@"NSProgressFileOperationKindEncrypting";
NSString* const kNSProgressFileOperationKindKey =
@"NSProgressFileOperationKindKey";
NSString* const kNSProgressFileTotalCountKey =
@"NSProgressFileTotalCountKey";
NSString* const kNSProgressFileURLKey =
@"NSProgressFileURLKey";
NSString* const kNSProgressIsWaitingKey =
@"NSProgressIsWaitingKey";
NSString* const kNSProgressKindFile =
@"NSProgressKindFile";
NSString* const kNSProgressThroughputKey =
@"NSProgressThroughputKey";
NSString* ProgressString(NSString* string) {
static NSMutableDictionary* cache;
static CFBundleRef foundation;
if (!cache) {
cache = [[NSMutableDictionary alloc] init];
foundation = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Foundation"));
}
NSString* result = [cache objectForKey:string];
if (!result) {
NSString** ref = static_cast<NSString**>(
CFBundleGetDataPointerForName(
foundation, base::mac::NSToCFCast(string)));
if (ref) {
result = *ref;
[cache setObject:result forKey:string];
}
}
if (!result && string == kNSProgressEstimatedTimeRemainingKey) {
// Perhaps this is 10.8; try the old name of this key.
NSString** ref = static_cast<NSString**>(
CFBundleGetDataPointerForName(
foundation, base::mac::NSToCFCast(kNSProgressEstimatedTimeKey)));
if (ref) {
result = *ref;
[cache setObject:result forKey:string];
}
}
if (!result) {
// Huh. At least return a local copy of the expected string.
result = string;
NSString* const kKeySuffix = @"Key";
if ([result hasSuffix:kKeySuffix])
result = [result substringToIndex:[result length] - [kKeySuffix length]];
}
return result;
}
} // namespace
@interface NSProgress : NSObject
- (id)initWithParent:(id)parent userInfo:(NSDictionary*)info;
@property(copy) NSString* kind;
- (void)unpublish;
- (void)publish;
- (void)setUserInfoObject:(id)object forKey:(NSString*)key;
- (NSDictionary*)userInfo;
@property(readonly) double fractionCompleted;
// Set the totalUnitCount to -1 to indicate an indeterminate download. The dock
// shows a non-filling progress bar; the Finder is lame and draws its progress
// bar off the right side.
@property(readonly, getter=isIndeterminate) BOOL indeterminate;
@property long long completedUnitCount;
@property long long totalUnitCount;
// Pausing appears to be unimplemented in 10.8.0.
- (void)pause;
@property(readonly, getter=isPaused) BOOL paused;
@property(getter=isPausable) BOOL pausable;
- (void)setPausingHandler:(id)blockOfUnknownSignature;
- (void)cancel;
@property(readonly, getter=isCancelled) BOOL cancelled;
@property(getter=isCancellable) BOOL cancellable;
// Note that the cancellation handler block will be called on a random thread.
- (void)setCancellationHandler:(void (^)())block;
// Allows other applications to provide feedback as to whether the progress is
// visible in that app. Note that the acknowledgement handler block will be
// called on a random thread.
// com.apple.dock => BOOL indicating whether the download target folder was
// successfully "flown to" at the beginning of the download.
// This primarily depends on whether the download target
// folder is in the dock. Note that if the download target
// folder is added or removed from the dock during the
// duration of the download, it will not trigger a callback.
// Note that if the "fly to the dock" keys were not set, the
// callback's parameter will always be NO.
// com.apple.Finder => always YES, no matter whether the download target
// folder's window is open.
- (void)handleAcknowledgementByAppWithBundleIdentifier:(NSString*)bundle
usingBlock:(void (^)(BOOL success))block;
@end
// --- Private 10.8 API for showing progress ---
namespace {
bool NSProgressSupported() {
static bool supported;
static bool valid;
if (!valid) {
supported = NSClassFromString(@"NSProgress");
valid = true;
}
return supported;
}
const char kCrNSProgressUserDataKey[] = "CrNSProgressUserData";
class CrNSProgressUserData : public base::SupportsUserData::Data {
public:
CrNSProgressUserData(NSProgress* progress, const base::FilePath& target)
: target_(target) {
progress_.reset(progress);
}
virtual ~CrNSProgressUserData() {
[progress_.get() unpublish];
}
NSProgress* progress() const { return progress_.get(); }
base::FilePath target() const { return target_; }
void setTarget(const base::FilePath& target) { target_ = target; }
private:
base::scoped_nsobject<NSProgress> progress_;
base::FilePath target_;
};
void UpdateAppIcon(int download_count,
bool progress_known,
float progress) {
DockIcon* dock_icon = [DockIcon sharedDockIcon];
[dock_icon setDownloads:download_count];
[dock_icon setIndeterminate:!progress_known];
[dock_icon setProgress:progress];
[dock_icon updateIcon];
}
void CreateNSProgress(content::DownloadItem* download) {
NSURL* source_url = [NSURL URLWithString:
base::SysUTF8ToNSString(download->GetURL().possibly_invalid_spec())];
base::FilePath destination_path = download->GetFullPath();
NSURL* destination_url = [NSURL fileURLWithPath:
base::mac::FilePathToNSString(destination_path)];
// If there were an image to fly to the download folder in the dock, then
// the keys in the userInfo to set would be:
// - @"NSProgressFlyToImageKey" : NSImage
// - kNSProgressFileIconOriginalRectKey : NSValue of NSRect in global coords
NSDictionary* user_info = @{
ProgressString(kNSProgressFileLocationCanChangeKey) : @true,
ProgressString(kNSProgressFileOperationKindKey) :
ProgressString(kNSProgressFileOperationKindDownloading),
ProgressString(kNSProgressFileURLKey) : destination_url
};
Class progress_class = NSClassFromString(@"NSProgress");
NSProgress* progress = [progress_class performSelector:@selector(alloc)];
progress = [progress performSelector:@selector(initWithParent:userInfo:)
withObject:nil
withObject:user_info];
progress.kind = ProgressString(kNSProgressKindFile);
if (source_url) {
[progress setUserInfoObject:source_url forKey:
ProgressString(kNSProgressFileDownloadingSourceURLKey)];
}
progress.pausable = NO;
progress.cancellable = YES;
[progress setCancellationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
download->Cancel(true);
});
}];
progress.totalUnitCount = download->GetTotalBytes();
progress.completedUnitCount = download->GetReceivedBytes();
[progress publish];
download->SetUserData(&kCrNSProgressUserDataKey,
new CrNSProgressUserData(progress, destination_path));
}
void UpdateNSProgress(content::DownloadItem* download,
CrNSProgressUserData* progress_data) {
NSProgress* progress = progress_data->progress();
progress.totalUnitCount = download->GetTotalBytes();
progress.completedUnitCount = download->GetReceivedBytes();
[progress setUserInfoObject:@(download->CurrentSpeed())
forKey:ProgressString(kNSProgressThroughputKey)];
base::TimeDelta time_remaining;
NSNumber* time_remaining_ns = nil;
if (download->TimeRemaining(&time_remaining))
time_remaining_ns = @(time_remaining.InSeconds());
[progress setUserInfoObject:time_remaining_ns
forKey:ProgressString(kNSProgressEstimatedTimeRemainingKey)];
base::FilePath download_path = download->GetFullPath();
if (progress_data->target() != download_path) {
progress_data->setTarget(download_path);
NSURL* download_url = [NSURL fileURLWithPath:
base::mac::FilePathToNSString(download_path)];
[progress setUserInfoObject:download_url
forKey:ProgressString(kNSProgressFileURLKey)];
}
}
void DestroyNSProgress(content::DownloadItem* download,
CrNSProgressUserData* progress_data) {
download->RemoveUserData(&kCrNSProgressUserDataKey);
}
} // namespace
void DownloadStatusUpdater::UpdateAppIconDownloadProgress(
content::DownloadItem* download) {
// Always update overall progress.
float progress = 0;
int download_count = 0;
bool progress_known = GetProgress(&progress, &download_count);
UpdateAppIcon(download_count, progress_known, progress);
// Update NSProgress-based indicators.
if (NSProgressSupported()) {
CrNSProgressUserData* progress_data = static_cast<CrNSProgressUserData*>(
download->GetUserData(&kCrNSProgressUserDataKey));
// Only show progress if the download is IN_PROGRESS and it hasn't been
// renamed to its final name. Setting the progress after the final rename
// results in the file being stuck in an in-progress state on the dock. See
// http://crbug.com/166683.
if (download->GetState() == content::DownloadItem::IN_PROGRESS &&
!download->GetFullPath().empty() &&
download->GetFullPath() != download->GetTargetFilePath()) {
if (!progress_data)
CreateNSProgress(download);
else
UpdateNSProgress(download, progress_data);
} else {
DestroyNSProgress(download, progress_data);
}
}
// Handle downloads that ended.
if (download->GetState() != content::DownloadItem::IN_PROGRESS &&
!download->GetTargetFilePath().empty()) {
NSString* download_path =
base::mac::FilePathToNSString(download->GetTargetFilePath());
if (download->GetState() == content::DownloadItem::COMPLETE) {
// Bounce the dock icon.
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:download_path];
}
// Notify the Finder.
NSString* parent_path = [download_path stringByDeletingLastPathComponent];
FNNotifyByPath(
reinterpret_cast<const UInt8*>([parent_path fileSystemRepresentation]),
kFNDirectoryModifiedMessage,
kNilOptions);
}
}
|