1 // Copyright 2014 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.
5 #import "ios/web/crw_network_activity_indicator_manager.h"
7 #import <UIKit/UIKit.h>
9 #include "base/logging.h"
10 #include "base/mac/scoped_nsobject.h"
11 #include "base/threading/thread_checker.h"
13 @interface CRWNetworkActivityIndicatorManager () {
14 base::scoped_nsobject<NSMutableDictionary> _groupCounts;
15 NSUInteger _totalCount;
16 base::ThreadChecker _threadChecker;
21 @implementation CRWNetworkActivityIndicatorManager
23 + (CRWNetworkActivityIndicatorManager*)sharedInstance {
24 static CRWNetworkActivityIndicatorManager* instance =
25 [[CRWNetworkActivityIndicatorManager alloc] init];
29 - (instancetype)init {
32 _groupCounts.reset([[NSMutableDictionary alloc] init]);
38 - (void)startNetworkTaskForGroup:(NSString*)group {
39 [self startNetworkTasks:1 forGroup:group];
42 - (void)stopNetworkTaskForGroup:(NSString*)group {
43 [self stopNetworkTasks:1 forGroup:group];
46 - (void)startNetworkTasks:(NSUInteger)numTasks forGroup:(NSString*)group {
47 DCHECK(_threadChecker.CalledOnValidThread());
49 DCHECK_GT(numTasks, 0U);
51 NSNumber* number = [_groupCounts objectForKey:group];
53 count = [number unsignedIntegerValue];
57 [_groupCounts setObject:@(count) forKey:group];
58 _totalCount += numTasks;
59 if (_totalCount == numTasks) {
60 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
64 - (void)stopNetworkTasks:(NSUInteger)numTasks forGroup:(NSString*)group {
65 DCHECK(_threadChecker.CalledOnValidThread());
67 DCHECK_GT(numTasks, 0U);
68 NSNumber* number = [_groupCounts objectForKey:group];
70 NSUInteger count = [number unsignedIntegerValue];
71 DCHECK(count >= numTasks);
74 [_groupCounts removeObjectForKey:group];
76 [_groupCounts setObject:@(count) forKey:group];
78 _totalCount -= numTasks;
79 if (_totalCount == 0) {
80 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
84 - (NSUInteger)clearNetworkTasksForGroup:(NSString*)group {
85 DCHECK(_threadChecker.CalledOnValidThread());
87 NSNumber* number = [_groupCounts objectForKey:group];
91 NSUInteger count = [number unsignedIntegerValue];
93 [self stopNetworkTasks:count forGroup:group];
97 - (NSUInteger)numNetworkTasksForGroup:(NSString*)group {
98 DCHECK(_threadChecker.CalledOnValidThread());
100 NSNumber* number = [_groupCounts objectForKey:group];
104 return [number unsignedIntegerValue];
107 - (NSUInteger)numTotalNetworkTasks {
108 DCHECK(_threadChecker.CalledOnValidThread());