Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / chrome / browser / task_manager / task_manager.h
blobd2c08ec488822077f4a92f7606d2d2ee17eb6024
1 // Copyright (c) 2012 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 #ifndef CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_H_
6 #define CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_H_
8 #include <stdint.h>
10 #include <map>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/singleton.h"
18 #include "base/observer_list.h"
19 #include "base/strings/string16.h"
20 #include "chrome/browser/task_manager/resource_provider.h"
21 #include "chrome/browser/ui/host_desktop.h"
22 #include "content/public/common/gpu_memory_stats.h"
23 #include "third_party/WebKit/public/web/WebCache.h"
25 class PrefRegistrySimple;
26 class PrivateWorkingSetSnapshot;
27 class TaskManagerModel;
28 class TaskManagerModelGpuDataManagerObserver;
30 namespace base {
31 class ProcessMetrics;
34 namespace content {
35 class WebContents;
38 namespace extensions {
39 class Extension;
42 namespace gfx {
43 class ImageSkia;
46 namespace net {
47 class URLRequest;
50 // This class is a singleton.
51 class TaskManager {
52 public:
53 static void RegisterPrefs(PrefRegistrySimple* registry);
55 // Returns true if the process at the specified index is the browser process.
56 bool IsBrowserProcess(int index) const;
58 // Terminates the process at the specified index.
59 void KillProcess(int index);
61 // Activates the browser tab associated with the process in the specified
62 // index.
63 void ActivateProcess(int index);
65 // These methods are invoked by the resource providers to add/remove resources
66 // to the Task Manager. Note that the resources are owned by the
67 // ResourceProviders and are not valid after StopUpdating() has been called
68 // on the ResourceProviders.
69 void AddResource(task_manager::Resource* resource);
70 void RemoveResource(task_manager::Resource* resource);
72 void OnWindowClosed();
74 // Invoked when a change to a resource has occurred that should cause any
75 // observers to completely refresh themselves (for example, the creation of
76 // a background resource in a process). Results in all observers receiving
77 // OnModelChanged() events.
78 void ModelChanged();
80 // Returns the singleton instance (and initializes it if necessary).
81 static TaskManager* GetInstance();
83 TaskManagerModel* model() const { return model_.get(); }
85 void OpenAboutMemory(chrome::HostDesktopType desktop_type);
87 private:
88 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, Basic);
89 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, Resources);
90 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, RefreshCalled);
91 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, Init);
92 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, Sort);
93 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest,
94 SelectionAdaptsToSorting);
95 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest,
96 EnsureNewPrimarySortColumn);
98 // Obtain an instance via GetInstance().
99 TaskManager();
100 friend struct DefaultSingletonTraits<TaskManager>;
102 ~TaskManager();
104 // The model used for gathering and processing task data. It is ref counted
105 // because it is passed as a parameter to MessageLoop::InvokeLater().
106 scoped_refptr<TaskManagerModel> model_;
108 DISALLOW_COPY_AND_ASSIGN(TaskManager);
111 class TaskManagerModelObserver {
112 public:
113 virtual ~TaskManagerModelObserver() {}
115 // Invoked when the model has been completely changed.
116 virtual void OnModelChanged() = 0;
118 // Invoked when a range of items has changed.
119 virtual void OnItemsChanged(int start, int length) = 0;
121 // Invoked when new items are added.
122 virtual void OnItemsAdded(int start, int length) = 0;
124 // Invoked when a range of items has been removed.
125 virtual void OnItemsRemoved(int start, int length) = 0;
127 // Invoked when a range of items is to be immediately removed. It differs
128 // from OnItemsRemoved by the fact that the item is still in the task manager,
129 // so it can be queried for and found.
130 virtual void OnItemsToBeRemoved(int start, int length) {}
132 // Invoked when the initialization of the model has been finished and
133 // periodical updates is started. The first periodical update will be done
134 // in a few seconds. (depending on platform)
135 virtual void OnReadyPeriodicalUpdate() {}
138 // The model used by TaskManager.
140 // TaskManagerModel caches the values from all task_manager::Resources. This is
141 // done so the UI sees a consistant view of the resources until it is told a
142 // value has been updated.
143 class TaskManagerModel : public base::RefCountedThreadSafe<TaskManagerModel> {
144 public:
145 // (start, length)
146 typedef std::pair<int, int> GroupRange;
148 explicit TaskManagerModel(TaskManager* task_manager);
150 void AddObserver(TaskManagerModelObserver* observer);
151 void RemoveObserver(TaskManagerModelObserver* observer);
153 // Returns number of registered resources.
154 int ResourceCount() const;
155 // Returns number of registered groups.
156 int GroupCount() const;
158 // Methods to return raw resource information.
159 int GetNaClDebugStubPort(int index) const;
160 int64 GetNetworkUsage(int index) const;
161 double GetCPUUsage(int index) const;
162 int GetIdleWakeupsPerSecond(int index) const;
163 base::ProcessId GetProcessId(int index) const;
164 base::ProcessHandle GetProcess(int index) const;
166 // Catchall method that calls off to the appropriate GetResourceXXX method
167 // based on |col_id|. |col_id| is an IDS_ value used to identify the column.
168 base::string16 GetResourceById(int index, int col_id) const;
170 // Methods to return formatted resource information.
171 const base::string16& GetResourceTitle(int index) const;
172 const base::string16& GetResourceProfileName(int index) const;
173 base::string16 GetResourceNaClDebugStubPort(int index) const;
174 base::string16 GetResourceNetworkUsage(int index) const;
175 base::string16 GetResourceCPUUsage(int index) const;
176 base::string16 GetResourcePrivateMemory(int index) const;
177 base::string16 GetResourceSharedMemory(int index) const;
178 base::string16 GetResourcePhysicalMemory(int index) const;
179 base::string16 GetResourceProcessId(int index) const;
180 base::string16 GetResourceGDIHandles(int index) const;
181 base::string16 GetResourceUSERHandles(int index) const;
182 base::string16 GetResourceWebCoreImageCacheSize(int index) const;
183 base::string16 GetResourceWebCoreScriptsCacheSize(int index) const;
184 base::string16 GetResourceWebCoreCSSCacheSize(int index) const;
185 base::string16 GetResourceVideoMemory(int index) const;
186 base::string16 GetResourceSqliteMemoryUsed(int index) const;
187 base::string16 GetResourceIdleWakeupsPerSecond(int index) const;
188 base::string16 GetResourceV8MemoryAllocatedSize(int index) const;
190 // Gets the private memory (in bytes) that should be displayed for the passed
191 // resource index. Caches the result since this calculation can take time on
192 // some platforms.
193 bool GetPrivateMemory(int index, size_t* result) const;
195 // Gets the shared memory (in bytes) that should be displayed for the passed
196 // resource index. Caches the result since this calculation can take time on
197 // some platforms.
198 bool GetSharedMemory(int index, size_t* result) const;
200 // Gets the physical memory (in bytes) that should be displayed for the passed
201 // resource index.
202 bool GetPhysicalMemory(int index, size_t* result) const;
204 // On Windows, get the current and peak number of GDI handles in use.
205 void GetGDIHandles(int index, size_t* current, size_t* peak) const;
207 // On Windows, get the current and peak number of USER handles in use.
208 void GetUSERHandles(int index, size_t* current, size_t* peak) const;
210 // Gets the statuses of webkit. Return false if the resource for the given row
211 // isn't a renderer.
212 bool GetWebCoreCacheStats(int index,
213 blink::WebCache::ResourceTypeStats* result) const;
215 // Gets the GPU memory allocated of the given page.
216 bool GetVideoMemory(int index,
217 size_t* video_memory,
218 bool* has_duplicates) const;
220 // Gets the sqlite memory (in byte). Return false if the resource for the
221 // given row doesn't report information.
222 bool GetSqliteMemoryUsedBytes(int index, size_t* result) const;
224 // Gets the amount of memory allocated for javascript. Returns false if the
225 // resource for the given row isn't a renderer.
226 bool GetV8Memory(int index, size_t* result) const;
228 // Gets the amount of memory used for javascript. Returns false if the
229 // resource for the given row isn't a renderer.
230 bool GetV8MemoryUsed(int index, size_t* result) const;
232 // Returns true if resource for the given row can be activated.
233 bool CanActivate(int index) const;
235 // Returns true if the resource is first/last in its group (resources
236 // rendered by the same process are groupped together).
237 bool IsResourceFirstInGroup(int index) const;
238 bool IsResourceLastInGroup(int index) const;
240 // Returns icon to be used for resource (for example a favicon).
241 gfx::ImageSkia GetResourceIcon(int index) const;
243 // Returns the group range of resource.
244 GroupRange GetGroupRangeForResource(int index) const;
246 // Returns an index of groups to which the resource belongs.
247 int GetGroupIndexForResource(int index) const;
249 // Returns an index of resource which belongs to the |group_index|th group
250 // and which is the |index_in_group|th resource in group.
251 int GetResourceIndexForGroup(int group_index, int index_in_group) const;
253 // Compares values in column |col_id| and rows |row1|, |row2|.
254 // Returns -1 if value in |row1| is less than value in |row2|,
255 // 0 if they are equal, and 1 otherwise.
256 int CompareValues(int row1, int row2, int col_id) const;
258 // Returns the unique child process ID generated by Chromium, not the OS
259 // process id. This is used to identify processes internally and for
260 // extensions. It is not meant to be displayed to the user.
261 int GetUniqueChildProcessId(int index) const;
263 // Returns the type of the given resource.
264 task_manager::Resource::Type GetResourceType(int index) const;
266 // Returns WebContents of given resource or NULL if not applicable.
267 content::WebContents* GetResourceWebContents(int index) const;
269 void AddResource(task_manager::Resource* resource);
270 void RemoveResource(task_manager::Resource* resource);
272 void StartUpdating();
273 void StopUpdating();
275 // Listening involves calling StartUpdating on all resource providers. This
276 // causes all of them to subscribe to notifications and enumerate current
277 // resources. It differs from StartUpdating that it doesn't start the
278 // Refresh timer. The end result is that we have a full view of resources, but
279 // don't spend unneeded time updating, unless we have a real need to.
280 void StartListening();
281 void StopListening();
283 void Clear(); // Removes all items.
285 // Sends OnModelChanged() to all observers to inform them of significant
286 // changes to the model.
287 void ModelChanged();
289 // Updates the values for all rows.
290 void Refresh();
292 // Do a bulk repopulation of the physical_memory data on platforms where that
293 // is faster.
294 void RefreshPhysicalMemoryFromWorkingSetSnapshot();
296 void NotifyVideoMemoryUsageStats(
297 const content::GPUVideoMemoryUsageStats& video_memory_usage_stats);
299 void NotifyBytesRead(const net::URLRequest& request, int64_t bytes_read);
301 void RegisterOnDataReadyCallback(const base::Closure& callback);
303 void NotifyDataReady();
305 private:
306 friend class base::RefCountedThreadSafe<TaskManagerModel>;
307 friend class TaskManagerBrowserTest;
308 FRIEND_TEST_ALL_PREFIXES(ExtensionApiTest, ProcessesVsTaskManager);
309 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, RefreshCalled);
310 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest,
311 SelectionAdaptsToSorting);
313 enum UpdateState {
314 IDLE = 0, // Currently not updating.
315 TASK_PENDING, // An update task is pending.
316 STOPPING // A update task is pending and it should stop the update.
319 // The delay between updates of the information (in ms).
320 #if defined(OS_MACOSX)
321 // Match Activity Monitor's default refresh rate.
322 static const int kUpdateTimeMs = 2000;
323 #else
324 static const int kUpdateTimeMs = 1000;
325 #endif
327 // Values cached per resource. Values are validated on demand. The is_XXX
328 // members indicate if a value is valid.
329 struct PerResourceValues {
330 PerResourceValues();
331 ~PerResourceValues();
333 bool is_title_valid;
334 base::string16 title;
336 bool is_profile_name_valid;
337 base::string16 profile_name;
339 // No is_network_usage since default (0) is fine.
340 int64 network_usage;
342 bool is_process_id_valid;
343 base::ProcessId process_id;
345 bool is_webcore_stats_valid;
346 blink::WebCache::ResourceTypeStats webcore_stats;
348 bool is_sqlite_memory_bytes_valid;
349 size_t sqlite_memory_bytes;
351 bool is_v8_memory_valid;
352 size_t v8_memory_allocated;
353 size_t v8_memory_used;
356 // Values cached per process. Values are validated on demand. The is_XXX
357 // members indicate if a value is valid.
358 struct PerProcessValues {
359 PerProcessValues();
360 ~PerProcessValues();
362 bool is_cpu_usage_valid;
363 double cpu_usage;
365 bool is_idle_wakeups_valid;
366 int idle_wakeups;
368 bool is_private_and_shared_valid;
369 size_t private_bytes;
370 size_t shared_bytes;
372 bool is_physical_memory_valid;
373 size_t physical_memory;
375 bool is_video_memory_valid;
376 size_t video_memory;
377 bool video_memory_has_duplicates;
379 bool is_gdi_handles_valid;
380 size_t gdi_handles;
381 size_t gdi_handles_peak;
383 bool is_user_handles_valid;
384 size_t user_handles;
385 size_t user_handles_peak;
387 bool is_nacl_debug_stub_port_valid;
388 int nacl_debug_stub_port;
391 typedef std::vector<task_manager::Resource*> ResourceList;
392 typedef std::vector<scoped_refptr<task_manager::ResourceProvider> >
393 ResourceProviderList;
394 typedef std::map<base::ProcessHandle, ResourceList> GroupMap;
395 typedef std::map<base::ProcessHandle, base::ProcessMetrics*> MetricsMap;
396 typedef std::map<task_manager::Resource*, int64> ResourceValueMap;
397 typedef std::map<task_manager::Resource*,
398 PerResourceValues> PerResourceCache;
399 typedef std::map<base::ProcessHandle, PerProcessValues> PerProcessCache;
401 // This struct is used to exchange information between the io and ui threads.
402 struct BytesReadParam {
403 BytesReadParam(int origin_pid,
404 int child_id,
405 int route_id,
406 int64_t byte_count)
407 : origin_pid(origin_pid),
408 child_id(child_id),
409 route_id(route_id),
410 byte_count(byte_count) {}
412 // The process ID that triggered the request. For plugin requests this
413 // will differ from the renderer process ID.
414 int origin_pid;
416 // The child ID of the process this request was routed through.
417 int child_id;
419 int route_id;
420 int64_t byte_count;
423 ~TaskManagerModel();
425 // Callback from the timer to refresh. Invokes Refresh() as appropriate.
426 void RefreshCallback();
428 void RefreshVideoMemoryUsageStats();
430 // Returns the network usage (in bytes per seconds) for the specified
431 // resource. That's the value retrieved at the last timer's tick.
432 int64 GetNetworkUsageForResource(task_manager::Resource* resource) const;
434 // Called on the UI thread when some bytes are read.
435 void BytesRead(BytesReadParam param);
437 void MultipleBytesRead(const std::vector<BytesReadParam>* params);
439 // Notifies the UI thread about all the bytes read. Allows for coalescing
440 // multiple bytes read into a single task for the UI thread. This is important
441 // for when downloading a lot of data on the IO thread, since posting a Task
442 // for each one is expensive.
443 void NotifyMultipleBytesRead();
445 // Called on the IO thread to start/stop updating byte counts.
446 void SetUpdatingByteCount(bool is_updating);
448 // Returns the network usage (in byte per second) that should be displayed for
449 // the passed |resource|. -1 means the information is not available for that
450 // resource.
451 int64 GetNetworkUsage(task_manager::Resource* resource) const;
453 // Returns the CPU usage (in %) that should be displayed for the passed
454 // |resource|.
455 double GetCPUUsage(task_manager::Resource* resource) const;
457 // Returns the idle wakeups that should be displayed for the passed
458 // |resource|.
459 int GetIdleWakeupsPerSecond(task_manager::Resource* resource) const;
461 // Given a number, this function returns the formatted string that should be
462 // displayed in the task manager's memory cell.
463 base::string16 GetMemCellText(int64 number) const;
465 // Verifies the private and shared memory for |handle| is valid in
466 // |per_process_cache_|. Returns true if the data in |per_process_cache_| is
467 // valid.
468 bool CachePrivateAndSharedMemory(base::ProcessHandle handle) const;
470 // Verifies |webcore_stats| in |per_resource_cache_|, returning true on
471 // success.
472 bool CacheWebCoreStats(int index) const;
474 // Verifies |v8_memory_allocated| and |v8_memory_used| in
475 // |per_resource_cache_|. Returns true if valid, false if not valid.
476 bool CacheV8Memory(int index) const;
478 // Adds a resource provider to be managed.
479 void AddResourceProvider(task_manager::ResourceProvider* provider);
481 // Returns the PerResourceValues for the specified index.
482 PerResourceValues& GetPerResourceValues(int index) const;
484 // Returns the Resource for the specified index.
485 task_manager::Resource* GetResource(int index) const;
487 // The list of providers to the task manager. They are ref counted.
488 ResourceProviderList providers_;
490 // The list of all the resources displayed in the task manager. They are owned
491 // by the ResourceProviders.
492 ResourceList resources_;
494 // A map to keep tracks of the grouped resources (they are grouped if they
495 // share the same process). The groups (the Resources vectors) are owned by
496 // the model (but the actual Resources are owned by the ResourceProviders).
497 GroupMap group_map_;
499 // A map to retrieve the process metrics for a process. The ProcessMetrics are
500 // owned by the model.
501 MetricsMap metrics_map_;
503 // A map that keeps track of the number of bytes read per process since last
504 // tick. The Resources are owned by the ResourceProviders.
505 ResourceValueMap current_byte_count_map_;
507 // A map that contains the video memory usage for a process
508 content::GPUVideoMemoryUsageStats video_memory_usage_stats_;
510 // Set to true when we've requested video stats and false once we get them.
511 bool pending_video_memory_usage_stats_update_;
513 // An observer waiting for video memory usage stats updates from the GPU
514 // process
515 scoped_ptr<TaskManagerModelGpuDataManagerObserver>
516 video_memory_usage_stats_observer_;
518 base::ObserverList<TaskManagerModelObserver> observer_list_;
520 // How many calls to StartUpdating have been made without matching calls to
521 // StopUpdating.
522 int update_requests_;
524 // How many calls to StartListening have been made without matching calls to
525 // StopListening.
526 int listen_requests_;
528 // Whether we are currently in the process of updating.
529 UpdateState update_state_;
531 // Whether the IO thread is currently in the process of updating; accessed
532 // only on the IO thread.
533 bool is_updating_byte_count_;
535 // Buffer for coalescing BytesReadParam so we don't have to post a task on
536 // each NotifyBytesRead() call.
537 std::vector<BytesReadParam> bytes_read_buffer_;
539 std::vector<base::Closure> on_data_ready_callbacks_;
541 #if defined(OS_WIN)
542 scoped_ptr<PrivateWorkingSetSnapshot> working_set_snapshot_;
543 #endif
545 // All per-Resource values are stored here.
546 mutable PerResourceCache per_resource_cache_;
548 // All per-Process values are stored here.
549 mutable PerProcessCache per_process_cache_;
551 DISALLOW_COPY_AND_ASSIGN(TaskManagerModel);
554 #endif // CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_H_