summaryrefslogtreecommitdiffstats
path: root/chrome/browser/task_manager/task_manager.cc
blob: 785f0dfe8a69d61cd161712a5fe36f3d71bdf051 (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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
// 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/task_manager/task_manager.h"

#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/i18n/number_formatting.h"
#include "base/i18n/rtl.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background/background_contents_service.h"
#include "chrome/browser/background/background_contents_service_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/task_manager/task_manager_resource_providers.h"
#include "chrome/browser/task_manager/task_manager_worker_resource_provider.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/view_type.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/gpu_data_manager_observer.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/result_codes.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/ui_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/text/bytes_formatting.h"
#include "ui/gfx/image/image_skia.h"
#include "unicode/coll.h"

using content::BrowserThread;
using content::OpenURLParams;
using content::Referrer;
using content::ResourceRequestInfo;
using content::WebContents;

namespace {

// The delay between updates of the information (in ms).
#if defined(OS_MACOSX)
// Match Activity Monitor's default refresh rate.
const int kUpdateTimeMs = 2000;
#else
const int kUpdateTimeMs = 1000;
#endif

template <class T>
int ValueCompare(T value1, T value2) {
  if (value1 < value2)
    return -1;
  if (value1 == value2)
    return 0;
  return 1;
}

string16 FormatStatsSize(const WebKit::WebCache::ResourceTypeStat& stat) {
  return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_CACHE_SIZE_CELL_TEXT,
      ui::FormatBytesWithUnits(stat.size, ui::DATA_UNITS_KIBIBYTE, false),
      ui::FormatBytesWithUnits(stat.liveSize, ui::DATA_UNITS_KIBIBYTE, false));
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// TaskManagerModel class
////////////////////////////////////////////////////////////////////////////////

TaskManagerModel::TaskManagerModel(TaskManager* task_manager)
    : pending_video_memory_usage_stats_update_(false),
      update_requests_(0),
      listen_requests_(0),
      update_state_(IDLE),
      goat_salt_(base::RandUint64()),
      last_unique_id_(0) {
  AddResourceProvider(
      new TaskManagerBrowserProcessResourceProvider(task_manager));
  AddResourceProvider(
      new TaskManagerBackgroundContentsResourceProvider(task_manager));
  AddResourceProvider(new TaskManagerTabContentsResourceProvider(task_manager));
  AddResourceProvider(new TaskManagerPanelResourceProvider(task_manager));
  AddResourceProvider(
      new TaskManagerChildProcessResourceProvider(task_manager));
  AddResourceProvider(
      new TaskManagerExtensionProcessResourceProvider(task_manager));
  AddResourceProvider(
      new TaskManagerGuestResourceProvider(task_manager));

#if defined(ENABLE_NOTIFICATIONS)
  TaskManager::ResourceProvider* provider =
      TaskManagerNotificationResourceProvider::Create(task_manager);
  if (provider)
    AddResourceProvider(provider);
#endif

  AddResourceProvider(new TaskManagerWorkerResourceProvider(task_manager));
}

TaskManagerModel::~TaskManagerModel() {
}

int TaskManagerModel::ResourceCount() const {
  return resources_.size();
}

int TaskManagerModel::GroupCount() const {
  return group_map_.size();
}

void TaskManagerModel::AddObserver(TaskManagerModelObserver* observer) {
  observer_list_.AddObserver(observer);
}

void TaskManagerModel::RemoveObserver(TaskManagerModelObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

int TaskManagerModel::GetResourceUniqueId(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->get_unique_id();
}

int TaskManagerModel::GetResourceIndexByUniqueId(const int unique_id) const {
  for (int resource_index = 0; resource_index < ResourceCount();
       ++resource_index) {
    if (GetResourceUniqueId(resource_index) == unique_id)
      return resource_index;
  }
  return -1;
}

string16 TaskManagerModel::GetResourceTitle(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetTitle();
}

string16 TaskManagerModel::GetResourceProfileName(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetProfileName();
}

int64 TaskManagerModel::GetNetworkUsage(int index) const {
  CHECK_LT(index, ResourceCount());
  return GetNetworkUsage(resources_[index]);
}

string16 TaskManagerModel::GetResourceNetworkUsage(int index) const {
  int64 net_usage = GetNetworkUsage(index);
  if (net_usage == -1)
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  if (net_usage == 0)
    return ASCIIToUTF16("0");
  string16 net_byte = ui::FormatSpeed(net_usage);
  // Force number string to have LTR directionality.
  return base::i18n::GetDisplayStringInLTRDirectionality(net_byte);
}

double TaskManagerModel::GetCPUUsage(int index) const {
  CHECK_LT(index, ResourceCount());
  return GetCPUUsage(resources_[index]);
}

string16 TaskManagerModel::GetResourceCPUUsage(int index) const {
  CHECK_LT(index, ResourceCount());
  return UTF8ToUTF16(base::StringPrintf(
#if defined(OS_MACOSX)
      // Activity Monitor shows %cpu with one decimal digit -- be
      // consistent with that.
      "%.1f",
#else
      "%.0f",
#endif
      GetCPUUsage(resources_[index])));
}

string16 TaskManagerModel::GetResourcePrivateMemory(int index) const {
  size_t private_mem;
  if (!GetPrivateMemory(index, &private_mem))
    return ASCIIToUTF16("N/A");
  return GetMemCellText(private_mem);
}

string16 TaskManagerModel::GetResourceSharedMemory(int index) const {
  size_t shared_mem;
  if (!GetSharedMemory(index, &shared_mem))
    return ASCIIToUTF16("N/A");
  return GetMemCellText(shared_mem);
}

string16 TaskManagerModel::GetResourcePhysicalMemory(int index) const {
  size_t phys_mem;
  GetPhysicalMemory(index, &phys_mem);
  return GetMemCellText(phys_mem);
}

int TaskManagerModel::GetProcessId(int index) const {
  CHECK_LT(index, ResourceCount());
  return base::GetProcId(resources_[index]->GetProcess());
}

base::ProcessHandle TaskManagerModel::GetProcess(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetProcess();
}

string16 TaskManagerModel::GetResourceProcessId(int index) const {
  return base::IntToString16(GetProcessId(index));
}

string16 TaskManagerModel::GetResourceGoatsTeleported(int index) const {
  CHECK_LT(index, ResourceCount());
  return base::FormatNumber(GetGoatsTeleported(index));
}

string16 TaskManagerModel::GetResourceWebCoreImageCacheSize(
    int index) const {
  CHECK_LT(index, ResourceCount());
  if (!resources_[index]->ReportsCacheStats())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  const WebKit::WebCache::ResourceTypeStats stats(
      resources_[index]->GetWebCoreCacheStats());
  return FormatStatsSize(stats.images);
}

string16 TaskManagerModel::GetResourceWebCoreScriptsCacheSize(
    int index) const {
  CHECK_LT(index, ResourceCount());
  if (!resources_[index]->ReportsCacheStats())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  const WebKit::WebCache::ResourceTypeStats stats(
      resources_[index]->GetWebCoreCacheStats());
  return FormatStatsSize(stats.scripts);
}

string16 TaskManagerModel::GetResourceWebCoreCSSCacheSize(
    int index) const {
  CHECK_LT(index, ResourceCount());
  if (!resources_[index]->ReportsCacheStats())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  const WebKit::WebCache::ResourceTypeStats stats(
      resources_[index]->GetWebCoreCacheStats());
  return FormatStatsSize(stats.cssStyleSheets);
}

string16 TaskManagerModel::GetResourceVideoMemory(int index) const {
  CHECK_LT(index, ResourceCount());

  bool result;
  size_t video_memory;
  bool has_duplicates;
  result = GetVideoMemory(index, &video_memory, &has_duplicates);

  if (!result || !video_memory) {
    return ASCIIToUTF16("N/A");
  } else if (has_duplicates) {
    return ASCIIToUTF16("(") +
           GetMemCellText(video_memory) +
           ASCIIToUTF16(")");
  } else {
    return GetMemCellText(video_memory);
  }
}

string16 TaskManagerModel::GetResourceFPS(
    int index) const {
  CHECK_LT(index, ResourceCount());
  if (!resources_[index]->ReportsFPS())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  double fps = resources_[index]->GetFPS();
  return UTF8ToUTF16(base::StringPrintf("%.0f", fps));
}

string16 TaskManagerModel::GetResourceSqliteMemoryUsed(int index) const {
  CHECK_LT(index, ResourceCount());
  if (!resources_[index]->ReportsSqliteMemoryUsed())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  return GetMemCellText(resources_[index]->SqliteMemoryUsedBytes());
}

string16 TaskManagerModel::GetResourceV8MemoryAllocatedSize(
    int index) const {
  if (!resources_[index]->ReportsV8MemoryStats())
    return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT);
  return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_CACHE_SIZE_CELL_TEXT,
      ui::FormatBytesWithUnits(resources_[index]->GetV8MemoryAllocated(),
                               ui::DATA_UNITS_KIBIBYTE,
                               false),
      ui::FormatBytesWithUnits(resources_[index]->GetV8MemoryUsed(),
                               ui::DATA_UNITS_KIBIBYTE,
                               false));
}

bool TaskManagerModel::IsResourceFirstInGroup(int index) const {
  CHECK_LT(index, ResourceCount());
  TaskManager::Resource* resource = resources_[index];
  GroupMap::const_iterator iter = group_map_.find(resource->GetProcess());
  DCHECK(iter != group_map_.end());
  const ResourceList* group = iter->second;
  return ((*group)[0] == resource);
}

bool TaskManagerModel::IsResourceLastInGroup(int index) const {
  CHECK_LT(index, ResourceCount());
  TaskManager::Resource* resource = resources_[index];
  GroupMap::const_iterator iter = group_map_.find(resource->GetProcess());
  DCHECK(iter != group_map_.end());
  const ResourceList* group = iter->second;
  return (group->back() == resource);
}

bool TaskManagerModel::IsBackgroundResource(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->IsBackground();
}

gfx::ImageSkia TaskManagerModel::GetResourceIcon(int index) const {
  CHECK_LT(index, ResourceCount());
  gfx::ImageSkia icon = resources_[index]->GetIcon();
  if (!icon.isNull())
    return icon;

  static gfx::ImageSkia* default_icon = ResourceBundle::GetSharedInstance().
      GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
  return *default_icon;
}

TaskManagerModel::GroupRange
TaskManagerModel::GetGroupRangeForResource(int index) const {
  CHECK_LT(index, ResourceCount());
  TaskManager::Resource* resource = resources_[index];
  GroupMap::const_iterator group_iter =
      group_map_.find(resource->GetProcess());
  DCHECK(group_iter != group_map_.end());
  ResourceList* group = group_iter->second;
  DCHECK(group);
  if (group->size() == 1) {
    return std::make_pair(index, 1);
  } else {
    for (int i = index; i >= 0; --i) {
      if (resources_[i] == (*group)[0])
        return std::make_pair(i, group->size());
    }
    NOTREACHED();
    return std::make_pair(-1, -1);
  }
}

int TaskManagerModel::GetGroupIndexForResource(int index) const {
  int group_index = -1;
  for (int i = 0; i <= index; ++i) {
    if (IsResourceFirstInGroup(i))
        group_index++;
  }

  DCHECK_NE(group_index, -1);
  return group_index;
}

int TaskManagerModel::GetResourceIndexForGroup(int group_index,
                                               int index_in_group) const {
  int group_count = -1;
  int count_in_group = -1;
  for (int i = 0; i < ResourceCount(); ++i) {
    if (IsResourceFirstInGroup(i))
      group_count++;

    if (group_count == group_index) {
      count_in_group++;
      if (count_in_group == index_in_group)
        return i;
    } else if (group_count > group_index) {
      break;
    }
  }

  NOTREACHED();
  return -1;
}

int TaskManagerModel::CompareValues(int row1, int row2, int col_id) const {
  CHECK(row1 < ResourceCount() && row2 < ResourceCount());
  if (col_id == IDS_TASK_MANAGER_TASK_COLUMN) {
    // Let's do the default, string compare on the resource title.
    static icu::Collator* collator = NULL;
    if (!collator) {
      UErrorCode create_status = U_ZERO_ERROR;
      collator = icu::Collator::createInstance(create_status);
      if (!U_SUCCESS(create_status)) {
        collator = NULL;
        NOTREACHED();
      }
    }
    string16 title1 = GetResourceTitle(row1);
    string16 title2 = GetResourceTitle(row2);
    UErrorCode compare_status = U_ZERO_ERROR;
    UCollationResult compare_result = collator->compare(
        static_cast<const UChar*>(title1.c_str()),
        static_cast<int>(title1.length()),
        static_cast<const UChar*>(title2.c_str()),
        static_cast<int>(title2.length()),
        compare_status);
    DCHECK(U_SUCCESS(compare_status));
    return compare_result;
  } else if (col_id == IDS_TASK_MANAGER_PROFILE_NAME_COLUMN) {
    string16 profile1 = GetResourceProfileName(row1);
    string16 profile2 = GetResourceProfileName(row2);
    return profile1.compare(0, profile1.length(), profile2, 0,
                            profile2.length());
  } else if (col_id == IDS_TASK_MANAGER_NET_COLUMN) {
    return ValueCompare<int64>(GetNetworkUsage(resources_[row1]),
                               GetNetworkUsage(resources_[row2]));
  } else if (col_id == IDS_TASK_MANAGER_CPU_COLUMN) {
    return ValueCompare<double>(GetCPUUsage(resources_[row1]),
                                GetCPUUsage(resources_[row2]));
  } else if (col_id == IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN) {
    size_t value1;
    size_t value2;
    if (!GetPrivateMemory(row1, &value1) || !GetPrivateMemory(row2, &value2))
      return 0;
    return ValueCompare<size_t>(value1, value2);
  } else if (col_id == IDS_TASK_MANAGER_SHARED_MEM_COLUMN) {
    size_t value1;
    size_t value2;
    if (!GetSharedMemory(row1, &value1) || !GetSharedMemory(row2, &value2))
      return 0;
    return ValueCompare<size_t>(value1, value2);
  } else if (col_id == IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN) {
    size_t value1;
    size_t value2;
    if (!GetPhysicalMemory(row1, &value1) ||
        !GetPhysicalMemory(row2, &value2))
      return 0;
    return ValueCompare<size_t>(value1, value2);
  } else if (col_id == IDS_TASK_MANAGER_PROCESS_ID_COLUMN) {
    int proc1_id = base::GetProcId(resources_[row1]->GetProcess());
    int proc2_id = base::GetProcId(resources_[row2]->GetProcess());
    return ValueCompare<int>(proc1_id, proc2_id);
  } else if (col_id == IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN ||
             col_id == IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN ||
             col_id == IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN) {
    WebKit::WebCache::ResourceTypeStats stats1 = { { 0 } };
    WebKit::WebCache::ResourceTypeStats stats2 = { { 0 } };
    if (resources_[row1]->ReportsCacheStats())
      stats1 = resources_[row1]->GetWebCoreCacheStats();
    if (resources_[row2]->ReportsCacheStats())
      stats2 = resources_[row2]->GetWebCoreCacheStats();
    if (IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN == col_id)
      return ValueCompare<size_t>(stats1.images.size, stats2.images.size);
    if (IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN == col_id)
      return ValueCompare<size_t>(stats1.scripts.size, stats2.scripts.size);
    DCHECK_EQ(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, col_id);
    return ValueCompare<size_t>(stats1.cssStyleSheets.size,
                                stats2.cssStyleSheets.size);
  } else if (col_id == IDS_TASK_MANAGER_FPS_COLUMN) {
    return ValueCompare<float>(resources_[row1]->GetFPS(),
                               resources_[row2]->GetFPS());
  } else if (col_id == IDS_TASK_MANAGER_VIDEO_MEMORY_COLUMN) {
    size_t value1;
    size_t value2;
    bool has_duplicates;
    if (!GetVideoMemory(row1, &value1, &has_duplicates)) value1 = 0;
    if (!GetVideoMemory(row2, &value2, &has_duplicates)) value2 = 0;
    return ValueCompare<size_t>(value1, value2);
  } else if (col_id == IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN) {
    return ValueCompare<int>(GetGoatsTeleported(row1),
                             GetGoatsTeleported(row2));
  } else if (col_id == IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN) {
    size_t value1;
    size_t value2;
    bool reports_v8_memory1 = GetV8Memory(row1, &value1);
    bool reports_v8_memory2 = GetV8Memory(row2, &value2);
    if (reports_v8_memory1 == reports_v8_memory2)
      return ValueCompare<size_t>(value1, value2);
    else
      return reports_v8_memory1 ? 1 : -1;
  } else {
    NOTREACHED();
    return 0;
  }
}

base::ProcessHandle TaskManagerModel::GetResourceProcessHandle(int index)
    const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetProcess();
}

int TaskManagerModel::GetUniqueChildProcessId(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetUniqueChildProcessId();
}

TaskManager::Resource::Type TaskManagerModel::GetResourceType(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetType();
}

WebContents* TaskManagerModel::GetResourceWebContents(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetWebContents();
}

const extensions::Extension* TaskManagerModel::GetResourceExtension(
    int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->GetExtension();
}

int64 TaskManagerModel::GetNetworkUsage(TaskManager::Resource* resource)
    const {
  int64 net_usage = GetNetworkUsageForResource(resource);
  if (net_usage == 0 && !resource->SupportNetworkUsage())
    return -1;
  return net_usage;
}

double TaskManagerModel::GetCPUUsage(TaskManager::Resource* resource) const {
  CPUUsageMap::const_iterator iter =
      cpu_usage_map_.find(resource->GetProcess());
  if (iter == cpu_usage_map_.end())
    return 0;
  return iter->second;
}

bool TaskManagerModel::GetPrivateMemory(int index, size_t* result) const {
  base::ProcessHandle handle = resources_[index]->GetProcess();
  MemoryUsageMap::const_iterator iter = memory_usage_map_.find(handle);
  if (iter == memory_usage_map_.end()) {
    MemoryUsageEntry usage;
    if (!GetAndCacheMemoryMetrics(handle, &usage))
      return false;

    *result = usage.first;
  } else {
    *result = iter->second.first;
  }

  return true;
}

bool TaskManagerModel::GetSharedMemory(int index, size_t* result) const {
  base::ProcessHandle handle = resources_[index]->GetProcess();
  MemoryUsageMap::const_iterator iter = memory_usage_map_.find(handle);
  if (iter == memory_usage_map_.end()) {
    MemoryUsageEntry usage;
    if (!GetAndCacheMemoryMetrics(handle, &usage))
      return false;

    *result = usage.second;
  } else {
    *result = iter->second.second;
  }

  return true;
}

bool TaskManagerModel::GetPhysicalMemory(int index, size_t* result) const {
  *result = 0;
  base::ProcessMetrics* process_metrics;
  if (!GetProcessMetricsForRow(index, &process_metrics))
    return false;
  base::WorkingSetKBytes ws_usage;
  if (!process_metrics->GetWorkingSetKBytes(&ws_usage))
    return false;

  // Memory = working_set.private + working_set.shareable.
  // We exclude the shared memory.
  size_t total_bytes = process_metrics->GetWorkingSetSize();
  total_bytes -= ws_usage.shared * 1024;
  *result = total_bytes;
  return true;
}

bool TaskManagerModel::GetWebCoreCacheStats(
    int index, WebKit::WebCache::ResourceTypeStats* result) const {
  if (!resources_[index]->ReportsCacheStats())
    return false;

  *result = resources_[index]->GetWebCoreCacheStats();
  return true;
}

bool TaskManagerModel::GetVideoMemory(
    int index, size_t* video_memory, bool* has_duplicates) const {
  TaskManager::Resource* resource = resources_[index];
  base::ProcessId pid = base::GetProcId(resource->GetProcess());
  content::GPUVideoMemoryUsageStats::ProcessMap::const_iterator i =
      video_memory_usage_stats_.process_map.find(pid);
  if (i == video_memory_usage_stats_.process_map.end()) {
    *video_memory = 0;
    *has_duplicates = false;
    return false;
  }
  *video_memory = (*i).second.video_memory;
  *has_duplicates = (*i).second.has_duplicates;
  return true;
}

bool TaskManagerModel::GetFPS(int index, float* result) const {
  *result = 0;
  if (!resources_[index]->ReportsFPS())
    return false;

  *result = resources_[index]->GetFPS();
  return true;
}

bool TaskManagerModel::GetSqliteMemoryUsedBytes(
    int index, size_t* result) const {
  *result = 0;
  if (!resources_[index]->ReportsSqliteMemoryUsed())
    return false;

  *result = resources_[index]->SqliteMemoryUsedBytes();
  return true;
}

bool TaskManagerModel::GetV8Memory(int index, size_t* result) const {
  *result = 0;
  if (!resources_[index]->ReportsV8MemoryStats())
    return false;

  *result = resources_[index]->GetV8MemoryAllocated();
  return true;
}

bool TaskManagerModel::GetV8MemoryUsed(int index, size_t* result) const {
  *result = 0;
  if (!resources_[index]->ReportsV8MemoryStats())
    return false;

  *result = resources_[index]->GetV8MemoryUsed();
  return true;
}

bool TaskManagerModel::CanActivate(int index) const {
  CHECK_LT(index, ResourceCount());
  return GetResourceWebContents(index) != NULL;
}

bool TaskManagerModel::CanInspect(int index) const {
  CHECK_LT(index, ResourceCount());
  return resources_[index]->CanInspect();
}

void TaskManagerModel::Inspect(int index) const {
  CHECK_LT(index, ResourceCount());
  resources_[index]->Inspect();
}

int TaskManagerModel::GetGoatsTeleported(int index) const {
  int seed = goat_salt_ * (index + 1);
  return (seed >> 16) & 255;
}

string16 TaskManagerModel::GetMemCellText(int64 number) const {
#if !defined(OS_MACOSX)
  string16 str = base::FormatNumber(number / 1024);

  // Adjust number string if necessary.
  base::i18n::AdjustStringForLocaleDirection(&str);
  return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_MEM_CELL_TEXT, str);
#else
  // System expectation is to show "100 kB", "200 MB", etc.
  // TODO(thakis): Switch to metric units (as opposed to powers of two).
  return ui::FormatBytes(number);
#endif
}

void TaskManagerModel::StartListening() {
  // Multiple StartListening requests may come in and we only need to take
  // action the first time.
  listen_requests_++;
  if (listen_requests_ > 1)
    return;
  DCHECK_EQ(1, listen_requests_);

  // Notify resource providers that we should start listening to events.
  for (ResourceProviderList::iterator iter = providers_.begin();
       iter != providers_.end(); ++iter) {
    (*iter)->StartUpdating();
  }
}

void TaskManagerModel::StopListening() {
  // Don't actually stop listening until we have heard as many calls as those
  // to StartListening.
  listen_requests_--;
  if (listen_requests_ > 0)
    return;

  DCHECK_EQ(0, listen_requests_);

  // Notify resource providers that we are done listening.
  for (ResourceProviderList::const_iterator iter = providers_.begin();
       iter != providers_.end(); ++iter) {
    (*iter)->StopUpdating();
  }

  // Must clear the resources before the next attempt to start listening.
  Clear();
}

void TaskManagerModel::StartUpdating() {
  // Multiple StartUpdating requests may come in, and we only need to take
  // action the first time.
  update_requests_++;
  if (update_requests_ > 1)
    return;
  DCHECK_EQ(1, update_requests_);
  DCHECK_NE(TASK_PENDING, update_state_);

  // If update_state_ is STOPPING, it means a task is still pending.  Setting
  // it to TASK_PENDING ensures the tasks keep being posted (by Refresh()).
  if (update_state_ == IDLE) {
      MessageLoop::current()->PostTask(
          FROM_HERE,
          base::Bind(&TaskManagerModel::Refresh, this));
  }
  update_state_ = TASK_PENDING;

  // Notify resource providers that we are updating.
  StartListening();

  if (!resources_.empty()) {
    FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                      OnReadyPeriodicalUpdate());
  }
}

void TaskManagerModel::StopUpdating() {
  // Don't actually stop updating until we have heard as many calls as those
  // to StartUpdating.
  update_requests_--;
  if (update_requests_ > 0)
    return;
  // Make sure that update_requests_ cannot go negative.
  CHECK_EQ(0, update_requests_);
  DCHECK_EQ(TASK_PENDING, update_state_);
  update_state_ = STOPPING;

  // Notify resource providers that we are done updating.
  StopListening();
}

void TaskManagerModel::AddResourceProvider(
    TaskManager::ResourceProvider* provider) {
  DCHECK(provider);
  providers_.push_back(provider);
}

void TaskManagerModel::AddResource(TaskManager::Resource* resource) {
  resource->unique_id_ = ++last_unique_id_;

  base::ProcessHandle process = resource->GetProcess();

  ResourceList* group_entries = NULL;
  GroupMap::const_iterator group_iter = group_map_.find(process);
  int new_entry_index = 0;
  if (group_iter == group_map_.end()) {
    group_entries = new ResourceList();
    group_map_[process] = group_entries;
    group_entries->push_back(resource);

    // Not part of a group, just put at the end of the list.
    resources_.push_back(resource);
    new_entry_index = static_cast<int>(resources_.size() - 1);
  } else {
    group_entries = group_iter->second;
    group_entries->push_back(resource);

    // Insert the new entry right after the last entry of its group.
    ResourceList::iterator iter =
        std::find(resources_.begin(),
                  resources_.end(),
                  (*group_entries)[group_entries->size() - 2]);
    DCHECK(iter != resources_.end());
    new_entry_index = static_cast<int>(iter - resources_.begin()) + 1;
    resources_.insert(++iter, resource);
  }

  // Create the ProcessMetrics for this process if needed (not in map).
  if (metrics_map_.find(process) == metrics_map_.end()) {
    base::ProcessMetrics* pm =
#if !defined(OS_MACOSX)
        base::ProcessMetrics::CreateProcessMetrics(process);
#else
        base::ProcessMetrics::CreateProcessMetrics(
            process, content::BrowserChildProcessHost::GetPortProvider());
#endif

    metrics_map_[process] = pm;
  }

  // Notify the table that the contents have changed for it to redraw.
  FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                    OnItemsAdded(new_entry_index, 1));
}

void TaskManagerModel::RemoveResource(TaskManager::Resource* resource) {
  base::ProcessHandle process = resource->GetProcess();

  // Find the associated group.
  GroupMap::iterator group_iter = group_map_.find(process);
  DCHECK(group_iter != group_map_.end());
  ResourceList* group_entries = group_iter->second;

  // Remove the entry from the group map.
  ResourceList::iterator iter = std::find(group_entries->begin(),
                                          group_entries->end(),
                                          resource);
  DCHECK(iter != group_entries->end());
  group_entries->erase(iter);

  // If there are no more entries for that process, do the clean-up.
  if (group_entries->empty()) {
    delete group_entries;
    group_map_.erase(process);

    // Nobody is using this process, we don't need the process metrics anymore.
    MetricsMap::iterator pm_iter = metrics_map_.find(process);
    DCHECK(pm_iter != metrics_map_.end());
    if (pm_iter != metrics_map_.end()) {
      delete pm_iter->second;
      metrics_map_.erase(process);
    }
    // And we don't need the CPU usage anymore either.
    CPUUsageMap::iterator cpu_iter = cpu_usage_map_.find(process);
    if (cpu_iter != cpu_usage_map_.end())
      cpu_usage_map_.erase(cpu_iter);
  }

  // Prepare to remove the entry from the model list.
  iter = std::find(resources_.begin(), resources_.end(), resource);
  DCHECK(iter != resources_.end());
  int index = static_cast<int>(iter - resources_.begin());

  // Notify the observers that the contents will change.
  FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                    OnItemsToBeRemoved(index, 1));

  // Now actually remove the entry from the model list.
  resources_.erase(iter);

  // Remove the entry from the network maps.
  ResourceValueMap::iterator net_iter =
      current_byte_count_map_.find(resource);
  if (net_iter != current_byte_count_map_.end())
    current_byte_count_map_.erase(net_iter);
  net_iter = displayed_network_usage_map_.find(resource);
  if (net_iter != displayed_network_usage_map_.end())
    displayed_network_usage_map_.erase(net_iter);

  // Notify the table that the contents have changed.
  FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                    OnItemsRemoved(index, 1));
}

void TaskManagerModel::Clear() {
  int size = ResourceCount();
  if (size > 0) {
    resources_.clear();

    // Clear the groups.
    STLDeleteValues(&group_map_);

    // Clear the process related info.
    STLDeleteValues(&metrics_map_);
    cpu_usage_map_.clear();

    // Clear the network maps.
    current_byte_count_map_.clear();
    displayed_network_usage_map_.clear();

    FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                      OnItemsRemoved(0, size));
  }
  last_unique_id_ = 0;
}

void TaskManagerModel::ModelChanged() {
  // Notify the table that the contents have changed for it to redraw.
  FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_, OnModelChanged());
}

void TaskManagerModel::NotifyResourceTypeStats(
    base::ProcessId renderer_id,
    const WebKit::WebCache::ResourceTypeStats& stats) {
  for (ResourceList::iterator it = resources_.begin();
       it != resources_.end(); ++it) {
    if (base::GetProcId((*it)->GetProcess()) == renderer_id) {
      (*it)->NotifyResourceTypeStats(stats);
    }
  }
}

void TaskManagerModel::NotifyFPS(base::ProcessId renderer_id,
                                 int routing_id,
                                 float fps) {
  for (ResourceList::iterator it = resources_.begin();
       it != resources_.end(); ++it) {
    if (base::GetProcId((*it)->GetProcess()) == renderer_id &&
        (*it)->GetRoutingID() == routing_id) {
      (*it)->NotifyFPS(fps);
    }
  }
}

void TaskManagerModel::NotifyVideoMemoryUsageStats(
    const content::GPUVideoMemoryUsageStats& video_memory_usage_stats) {
  DCHECK(pending_video_memory_usage_stats_update_);
  video_memory_usage_stats_ = video_memory_usage_stats;
  pending_video_memory_usage_stats_update_ = false;
}

void TaskManagerModel::NotifyV8HeapStats(base::ProcessId renderer_id,
                                         size_t v8_memory_allocated,
                                         size_t v8_memory_used) {
  for (ResourceList::iterator it = resources_.begin();
       it != resources_.end(); ++it) {
    if (base::GetProcId((*it)->GetProcess()) == renderer_id) {
      (*it)->NotifyV8HeapStats(v8_memory_allocated, v8_memory_used);
    }
  }
}

class TaskManagerModelGpuDataManagerObserver
    : public content::GpuDataManagerObserver {
 public:
  TaskManagerModelGpuDataManagerObserver() {
    content::GpuDataManager::GetInstance()->AddObserver(this);
  }

  virtual ~TaskManagerModelGpuDataManagerObserver() {
    content::GpuDataManager::GetInstance()->RemoveObserver(this);
  }

  static void NotifyVideoMemoryUsageStats(
      content::GPUVideoMemoryUsageStats video_memory_usage_stats) {
    TaskManager::GetInstance()->model()->NotifyVideoMemoryUsageStats(
        video_memory_usage_stats);
  }

  virtual void OnGpuInfoUpdate() OVERRIDE {}

  virtual void OnVideoMemoryUsageStatsUpdate(
      const content::GPUVideoMemoryUsageStats& video_memory_usage_stats)
          OVERRIDE {
    if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      NotifyVideoMemoryUsageStats(video_memory_usage_stats);
    } else {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE, base::Bind(
              &TaskManagerModelGpuDataManagerObserver::
                  NotifyVideoMemoryUsageStats,
              video_memory_usage_stats));
    }
  }
};

void TaskManagerModel::RefreshVideoMemoryUsageStats() {
  if (pending_video_memory_usage_stats_update_) return;
  if (!video_memory_usage_stats_observer_.get()) {
    video_memory_usage_stats_observer_.reset(
        new TaskManagerModelGpuDataManagerObserver());
  }
  pending_video_memory_usage_stats_update_ = true;
  content::GpuDataManager::GetInstance()->RequestVideoMemoryUsageStatsUpdate();
}

void TaskManagerModel::Refresh() {
  DCHECK_NE(IDLE, update_state_);

  if (update_state_ == STOPPING) {
    // We have been asked to stop.
    update_state_ = IDLE;
    return;
  }

  goat_salt_ = base::RandUint64();

  // Compute the CPU usage values.
  // Note that we compute the CPU usage for all resources (instead of doing it
  // lazily) as process_util::GetCPUUsage() returns the CPU usage since the last
  // time it was called, and not calling it everytime would skew the value the
  // next time it is retrieved (as it would be for more than 1 cycle).
  cpu_usage_map_.clear();
  for (ResourceList::iterator iter = resources_.begin();
       iter != resources_.end(); ++iter) {
    base::ProcessHandle process = (*iter)->GetProcess();
    CPUUsageMap::iterator cpu_iter = cpu_usage_map_.find(process);
    if (cpu_iter != cpu_usage_map_.end())
      continue;  // Already computed.

    MetricsMap::iterator metrics_iter = metrics_map_.find(process);
    DCHECK(metrics_iter != metrics_map_.end());
    cpu_usage_map_[process] = metrics_iter->second->GetCPUUsage();
  }

  // Clear the memory values so they can be querried lazily.
  memory_usage_map_.clear();

  // Send a request to refresh GPU memory consumption values
  RefreshVideoMemoryUsageStats();

  // Compute the new network usage values.
  displayed_network_usage_map_.clear();
  base::TimeDelta update_time =
      base::TimeDelta::FromMilliseconds(kUpdateTimeMs);
  for (ResourceValueMap::iterator iter = current_byte_count_map_.begin();
       iter != current_byte_count_map_.end(); ++iter) {
    if (update_time > base::TimeDelta::FromSeconds(1)) {
      int divider = update_time.InSeconds();
      displayed_network_usage_map_[iter->first] = iter->second / divider;
    } else {
      displayed_network_usage_map_[iter->first] = iter->second *
          (1 / update_time.InSeconds());
    }

    // Then we reset the current byte count.
    iter->second = 0;
  }

  // Let resources update themselves if they need to.
  for (ResourceList::iterator iter = resources_.begin();
       iter != resources_.end(); ++iter) {
     (*iter)->Refresh();
  }

  if (!resources_.empty()) {
    FOR_EACH_OBSERVER(TaskManagerModelObserver, observer_list_,
                      OnItemsChanged(0, ResourceCount()));
  }

  // Schedule the next update.
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&TaskManagerModel::Refresh, this),
      base::TimeDelta::FromMilliseconds(kUpdateTimeMs));
}

int64 TaskManagerModel::GetNetworkUsageForResource(
    TaskManager::Resource* resource) const {
  ResourceValueMap::const_iterator iter =
      displayed_network_usage_map_.find(resource);
  if (iter == displayed_network_usage_map_.end())
    return 0;
  return iter->second;
}

void TaskManagerModel::BytesRead(BytesReadParam param) {
  if (update_state_ != TASK_PENDING || listen_requests_ == 0) {
    // A notification sneaked in while we were stopping the updating, just
    // ignore it.
    return;
  }

  // TODO(jcampan): this should be improved once we have a better way of
  // linking a network notification back to the object that initiated it.
  TaskManager::Resource* resource = NULL;
  for (ResourceProviderList::iterator iter = providers_.begin();
       iter != providers_.end(); ++iter) {
    resource = (*iter)->GetResource(param.origin_pid,
                                    param.render_process_host_child_id,
                                    param.routing_id);
    if (resource)
      break;
  }

  if (resource == NULL) {
    // We can't match a resource to the notification.  That might mean the
    // tab that started a download was closed, or the request may have had
    // no originating resource associated with it in the first place.
    // We attribute orphaned/unaccounted activity to the Browser process.
    CHECK(param.origin_pid || (param.render_process_host_child_id != -1));
    param.origin_pid = 0;
    param.render_process_host_child_id = param.routing_id = -1;
    BytesRead(param);
    return;
  }

  // We do support network usage, mark the resource as such so it can report 0
  // instead of N/A.
  if (!resource->SupportNetworkUsage())
    resource->SetSupportNetworkUsage();

  ResourceValueMap::const_iterator iter_res =
      current_byte_count_map_.find(resource);
  if (iter_res == current_byte_count_map_.end())
    current_byte_count_map_[resource] = param.byte_count;
  else
    current_byte_count_map_[resource] = iter_res->second + param.byte_count;
}

void TaskManagerModel::MultipleBytesRead(
    const std::vector<BytesReadParam>* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  for (std::vector<BytesReadParam>::const_iterator it = params->begin();
       it != params->end(); ++it) {
    BytesRead(*it);
  }
}

void TaskManagerModel::NotifyMultipleBytesRead() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!bytes_read_buffer_.empty());

  std::vector<BytesReadParam>* bytes_read_buffer =
      new std::vector<BytesReadParam>;
  bytes_read_buffer_.swap(*bytes_read_buffer);
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&TaskManagerModel::MultipleBytesRead, this,
                 base::Owned(bytes_read_buffer)));
}

void TaskManagerModel::NotifyBytesRead(const net::URLRequest& request,
                                       int byte_count) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // Only net::URLRequestJob instances created by the ResourceDispatcherHost
  // have an associated ResourceRequestInfo.
  const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(&request);

  // have a render view associated.  All other jobs will have -1 returned for
  // the render process child and routing ids - the jobs may still match a
  // resource based on their origin id, otherwise BytesRead() will attribute
  // the activity to the Browser resource.
  int render_process_host_child_id = -1, routing_id = -1;
  if (info)
    info->GetAssociatedRenderView(&render_process_host_child_id, &routing_id);

  // Get the origin PID of the request's originator.  This will only be set for
  // plugins - for renderer or browser initiated requests it will be zero.
  int origin_pid = 0;
  if (info)
    origin_pid = info->GetOriginPID();

  if (bytes_read_buffer_.empty()) {
    MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&TaskManagerModel::NotifyMultipleBytesRead, this),
        base::TimeDelta::FromSeconds(1));
  }

  bytes_read_buffer_.push_back(
      BytesReadParam(origin_pid, render_process_host_child_id,
                     routing_id, byte_count));
}

bool TaskManagerModel::GetProcessMetricsForRow(
    int row, base::ProcessMetrics** proc_metrics) const {
  DCHECK(row < ResourceCount());
  *proc_metrics = NULL;

  MetricsMap::const_iterator iter =
      metrics_map_.find(resources_[row]->GetProcess());
  if (iter == metrics_map_.end())
    return false;
  *proc_metrics = iter->second;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// TaskManager class
////////////////////////////////////////////////////////////////////////////////

int TaskManager::Resource::GetRoutingID() const { return 0; }

bool TaskManager::Resource::ReportsCacheStats() const { return false; }

WebKit::WebCache::ResourceTypeStats
TaskManager::Resource::GetWebCoreCacheStats() const {
  return WebKit::WebCache::ResourceTypeStats();
}

bool TaskManager::Resource::ReportsFPS() const { return false; }

float TaskManager::Resource::GetFPS() const { return 0.0f; }

bool TaskManager::Resource::ReportsSqliteMemoryUsed() const { return false; }

size_t TaskManager::Resource::SqliteMemoryUsedBytes() const { return 0; }

const extensions::Extension* TaskManager::Resource::GetExtension() const {
  return NULL;
}

bool TaskManager::Resource::ReportsV8MemoryStats() const { return false; }

size_t TaskManager::Resource::GetV8MemoryAllocated() const { return 0; }

size_t TaskManager::Resource::GetV8MemoryUsed() const { return 0; }

bool TaskManager::Resource::CanInspect() const { return false; }

content::WebContents* TaskManager::Resource::GetWebContents() const {
  return NULL;
}

bool TaskManager::Resource::IsBackground() const { return false; }

// static
void TaskManager::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kTaskManagerWindowPlacement);
}

TaskManager::TaskManager()
    : ALLOW_THIS_IN_INITIALIZER_LIST(model_(new TaskManagerModel(this))) {
}

TaskManager::~TaskManager() {
}

bool TaskManager::IsBrowserProcess(int index) const {
  // If some of the selection is out of bounds, ignore. This may happen when
  // killing a process that manages several pages.
  return index < model_->ResourceCount() &&
      model_->GetResourceProcessHandle(index) ==
      base::GetCurrentProcessHandle();
}

void TaskManager::KillProcess(int index) {
  base::ProcessHandle process = model_->GetResourceProcessHandle(index);
  DCHECK(process);
  if (process != base::GetCurrentProcessHandle())
    base::KillProcess(process, content::RESULT_CODE_KILLED, false);
}

void TaskManager::ActivateProcess(int index) {
  // GetResourceWebContents returns a pointer to the relevant web contents for
  // the resource.  If the index doesn't correspond to any web contents
  // (i.e. refers to the Browser process or a plugin), GetWebContents will
  // return NULL.
  WebContents* chosen_web_contents = model_->GetResourceWebContents(index);
  if (chosen_web_contents && chosen_web_contents->GetDelegate())
    chosen_web_contents->GetDelegate()->ActivateContents(chosen_web_contents);
}

void TaskManager::AddResource(Resource* resource) {
  model_->AddResource(resource);
}

void TaskManager::RemoveResource(Resource* resource) {
  model_->RemoveResource(resource);
}

void TaskManager::OnWindowClosed() {
  model_->StopUpdating();
}

void TaskManager::ModelChanged() {
  model_->ModelChanged();
}

// static
TaskManager* TaskManager::GetInstance() {
  return Singleton<TaskManager>::get();
}

void TaskManager::OpenAboutMemory() {
  // TODO(robertshield): FTB - Merge MAD's TaskManager change.
  Browser* browser = browser::FindOrCreateTabbedBrowserDeprecated(
      ProfileManager::GetDefaultProfileOrOffTheRecord());
  chrome::NavigateParams params(browser, GURL(chrome::kChromeUIMemoryURL),
                                content::PAGE_TRANSITION_LINK);
  params.disposition = NEW_FOREGROUND_TAB;
  chrome::Navigate(&params);
}

bool TaskManagerModel::GetAndCacheMemoryMetrics(base::ProcessHandle handle,
                                                MemoryUsageEntry* usage) const {
  MetricsMap::const_iterator iter = metrics_map_.find(handle);
  if (iter == metrics_map_.end())
    return false;

  if (!iter->second->GetMemoryBytes(&usage->first, &usage->second))
    return false;

  memory_usage_map_.insert(std::make_pair(handle, *usage));
  return true;
}

namespace {

// Counts the number of extension background pages associated with this profile.
int CountExtensionBackgroundPagesForProfile(Profile* profile) {
  int count = 0;
  ExtensionProcessManager* manager =
      extensions::ExtensionSystem::Get(profile)->process_manager();
  if (!manager)
    return count;

  const ExtensionProcessManager::ExtensionHostSet& background_hosts =
      manager->background_hosts();
  for (ExtensionProcessManager::const_iterator iter = background_hosts.begin();
       iter != background_hosts.end(); ++iter) {
    ++count;
  }
  return count;
}

}  // namespace

// static
int TaskManager::GetBackgroundPageCount() {
  int count = 0;
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  if (!profile_manager)  // Null when running unit tests.
    return count;
  std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
  for (std::vector<Profile*>::const_iterator iter = profiles.begin();
       iter != profiles.end();
       ++iter) {
    Profile* profile = *iter;
    // Count the number of Background Contents (background pages for hosted
    // apps). Incognito windows do not support hosted apps, so just check the
    // main profile.
    BackgroundContentsService* background_contents_service =
        BackgroundContentsServiceFactory::GetForProfile(profile);
    if (background_contents_service)
      count += background_contents_service->GetBackgroundContents().size();

    // Count the number of extensions with background pages (including
    // incognito).
    count += CountExtensionBackgroundPagesForProfile(profile);
    if (profile->HasOffTheRecordProfile()) {
      count += CountExtensionBackgroundPagesForProfile(
          profile->GetOffTheRecordProfile());
    }
  }
  return count;
}