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 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
10 #include "base/mac/bundle_locations.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/sys_string_conversions.h"
13 #include "chrome/browser/browser_process.h"
14 #import "chrome/browser/ui/cocoa/window_size_autosaver.h"
15 #include "chrome/browser/ui/host_desktop.h"
16 #include "chrome/common/pref_names.h"
17 #include "chrome/grit/generated_resources.h"
18 #include "third_party/skia/include/core/SkBitmap.h"
19 #include "ui/base/l10n/l10n_util_mac.h"
20 #include "ui/gfx/image/image_skia.h"
24 // Width of "a" and most other letters/digits in "small" table views.
25 const int kCharWidth = 6;
27 // Some of the strings below have spaces at the end or are missing letters, to
28 // make the columns look nicer, and to take potentially longer localized strings
30 const struct ColumnWidth {
33 int maxWidth; // If this is -1, 1.5*minColumWidth is used as max width.
35 // Note that arraysize includes the trailing \0. That's intended.
36 { IDS_TASK_MANAGER_TASK_COLUMN, 120, 600 },
37 { IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, 60, 200 },
38 { IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN,
39 arraysize("800 MiB") * kCharWidth, -1 },
40 { IDS_TASK_MANAGER_SHARED_MEM_COLUMN,
41 arraysize("800 MiB") * kCharWidth, -1 },
42 { IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN,
43 arraysize("800 MiB") * kCharWidth, -1 },
44 { IDS_TASK_MANAGER_CPU_COLUMN,
45 arraysize("99.9") * kCharWidth, -1 },
46 { IDS_TASK_MANAGER_NET_COLUMN,
47 arraysize("150 kiB/s") * kCharWidth, -1 },
48 { IDS_TASK_MANAGER_PROCESS_ID_COLUMN,
49 arraysize("73099 ") * kCharWidth, -1 },
50 { IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
51 arraysize("2000.0K (2000.0 live)") * kCharWidth, -1 },
52 { IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
53 arraysize("2000.0K (2000.0 live)") * kCharWidth, -1 },
54 { IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
55 arraysize("2000.0K (2000.0 live)") * kCharWidth, -1 },
56 { IDS_TASK_MANAGER_VIDEO_MEMORY_COLUMN,
57 arraysize("2000.0K") * kCharWidth, -1 },
58 { IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
59 arraysize("800 kB") * kCharWidth, -1 },
60 { IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN,
61 arraysize("2000.0K (2000.0 live)") * kCharWidth, -1 },
62 { IDS_TASK_MANAGER_NACL_DEBUG_STUB_PORT_COLUMN,
63 arraysize("32767") * kCharWidth, -1 },
64 { IDS_TASK_MANAGER_IDLE_WAKEUPS_COLUMN,
65 arraysize("idlewakeups") * kCharWidth, -1 },
70 SortHelper(TaskManagerModel* model, NSSortDescriptor* column)
71 : sort_column_([[column key] intValue]),
72 ascending_([column ascending]),
75 bool operator()(int a, int b) {
76 TaskManagerModel::GroupRange group_range1 =
77 model_->GetGroupRangeForResource(a);
78 TaskManagerModel::GroupRange group_range2 =
79 model_->GetGroupRangeForResource(b);
80 if (group_range1 == group_range2) {
81 // The two rows are in the same group, sort so that items in the same
82 // group always appear in the same order. |ascending_| is intentionally
86 // Sort by the first entry of each of the groups.
87 int cmp_result = model_->CompareValues(
88 group_range1.first, group_range2.first, sort_column_);
90 cmp_result = -cmp_result;
91 return cmp_result < 0;
96 TaskManagerModel* model_; // weak;
101 @interface TaskManagerWindowController (Private)
102 - (NSTableColumn*)addColumnWithId:(int)columnId visible:(BOOL)isVisible;
103 - (void)setUpTableColumns;
104 - (void)setUpTableHeaderContextMenu;
105 - (void)toggleColumn:(id)sender;
106 - (void)adjustSelectionAndEndProcessButton;
107 - (void)deselectRows;
110 ////////////////////////////////////////////////////////////////////////////////
111 // TaskManagerWindowController implementation:
113 @implementation TaskManagerWindowController
115 - (id)initWithTaskManagerObserver:(TaskManagerMac*)taskManagerObserver {
116 NSString* nibpath = [base::mac::FrameworkBundle()
117 pathForResource:@"TaskManager"
119 if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
120 taskManagerObserver_ = taskManagerObserver;
121 taskManager_ = taskManagerObserver_->task_manager();
122 model_ = taskManager_->model();
124 if (g_browser_process && g_browser_process->local_state()) {
125 size_saver_.reset([[WindowSizeAutosaver alloc]
126 initWithWindow:[self window]
127 prefService:g_browser_process->local_state()
128 path:prefs::kTaskManagerWindowPlacement]);
130 [self showWindow:self];
135 - (void)sortShuffleArray {
136 viewToModelMap_.resize(model_->ResourceCount());
137 for (size_t i = 0; i < viewToModelMap_.size(); ++i)
138 viewToModelMap_[i] = i;
140 std::sort(viewToModelMap_.begin(), viewToModelMap_.end(),
141 SortHelper(model_, currentSortDescriptor_.get()));
143 modelToViewMap_.resize(viewToModelMap_.size());
144 for (size_t i = 0; i < viewToModelMap_.size(); ++i)
145 modelToViewMap_[viewToModelMap_[i]] = i;
149 // Store old view indices, and the model indices they map to.
150 NSIndexSet* viewSelection = [tableView_ selectedRowIndexes];
151 std::vector<int> modelSelection;
152 for (NSUInteger i = [viewSelection lastIndex];
154 i = [viewSelection indexLessThanIndex:i]) {
155 modelSelection.push_back(viewToModelMap_[i]);
159 [self sortShuffleArray];
161 // Use the model indices to get the new view indices of the selection, and
162 // set selection to that. This assumes that no rows were added or removed
163 // (in that case, the selection is cleared before -reloadData is called).
164 if (!modelSelection.empty())
165 DCHECK_EQ([tableView_ numberOfRows], model_->ResourceCount());
166 NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
167 for (size_t i = 0; i < modelSelection.size(); ++i)
168 [indexSet addIndex:modelToViewMap_[modelSelection[i]]];
169 [tableView_ selectRowIndexes:indexSet byExtendingSelection:NO];
171 [tableView_ reloadData];
172 [self adjustSelectionAndEndProcessButton];
175 - (IBAction)statsLinkClicked:(id)sender {
176 TaskManager::GetInstance()->OpenAboutMemory(chrome::HOST_DESKTOP_TYPE_NATIVE);
179 - (IBAction)killSelectedProcesses:(id)sender {
180 NSIndexSet* selection = [tableView_ selectedRowIndexes];
181 for (NSUInteger i = [selection lastIndex];
183 i = [selection indexLessThanIndex:i]) {
184 taskManager_->KillProcess(viewToModelMap_[i]);
188 - (void)selectDoubleClickedTab:(id)sender {
189 NSInteger row = [tableView_ clickedRow];
191 return; // Happens e.g. if the table header is double-clicked.
192 taskManager_->ActivateProcess(viewToModelMap_[row]);
195 - (NSTableView*)tableView {
199 - (void)awakeFromNib {
200 [self setUpTableColumns];
201 [self setUpTableHeaderContextMenu];
202 [self adjustSelectionAndEndProcessButton];
204 [tableView_ setDoubleAction:@selector(selectDoubleClickedTab:)];
205 [tableView_ setIntercellSpacing:NSMakeSize(0.0, 0.0)];
206 [tableView_ sizeToFit];
210 [tableView_ setDelegate:nil];
211 [tableView_ setDataSource:nil];
215 // Adds a column which has the given string id as title. |isVisible| specifies
216 // if the column is initially visible.
217 - (NSTableColumn*)addColumnWithId:(int)columnId visible:(BOOL)isVisible {
218 base::scoped_nsobject<NSTableColumn> column([[NSTableColumn alloc]
219 initWithIdentifier:[NSString stringWithFormat:@"%d", columnId]]);
221 NSTextAlignment textAlignment =
222 (columnId == IDS_TASK_MANAGER_TASK_COLUMN ||
223 columnId == IDS_TASK_MANAGER_PROFILE_NAME_COLUMN) ?
224 NSLeftTextAlignment : NSRightTextAlignment;
226 [[column.get() headerCell]
227 setStringValue:l10n_util::GetNSStringWithFixup(columnId)];
228 [[column.get() headerCell] setAlignment:textAlignment];
229 [[column.get() dataCell] setAlignment:textAlignment];
231 NSFont* font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
232 [[column.get() dataCell] setFont:font];
234 [column.get() setHidden:!isVisible];
235 [column.get() setEditable:NO];
237 // The page column should by default be sorted ascending.
238 BOOL ascending = columnId == IDS_TASK_MANAGER_TASK_COLUMN;
240 base::scoped_nsobject<NSSortDescriptor> sortDescriptor(
241 [[NSSortDescriptor alloc]
242 initWithKey:[NSString stringWithFormat:@"%d", columnId]
243 ascending:ascending]);
244 [column.get() setSortDescriptorPrototype:sortDescriptor.get()];
246 // Default values, only used in release builds if nobody notices the DCHECK
247 // during development when adding new columns.
248 int minWidth = 200, maxWidth = 400;
251 for (i = 0; i < arraysize(columnWidths); ++i) {
252 if (columnWidths[i].columnId == columnId) {
253 minWidth = columnWidths[i].minWidth;
254 maxWidth = columnWidths[i].maxWidth;
256 maxWidth = 3 * minWidth / 2; // *1.5 for ints.
260 DCHECK(i < arraysize(columnWidths)) << "Could not find " << columnId;
261 [column.get() setMinWidth:minWidth];
262 [column.get() setMaxWidth:maxWidth];
263 [column.get() setResizingMask:NSTableColumnAutoresizingMask |
264 NSTableColumnUserResizingMask];
266 [tableView_ addTableColumn:column.get()];
267 return column.get(); // Now retained by |tableView_|.
270 // Adds all the task manager's columns to the table.
271 - (void)setUpTableColumns {
272 for (NSTableColumn* column in [tableView_ tableColumns])
273 [tableView_ removeTableColumn:column];
274 NSTableColumn* nameColumn = [self addColumnWithId:IDS_TASK_MANAGER_TASK_COLUMN
276 // |nameColumn| displays an icon for every row -- this is done by an
278 base::scoped_nsobject<NSButtonCell> nameCell(
279 [[NSButtonCell alloc] initTextCell:@""]);
280 [nameCell.get() setImagePosition:NSImageLeft];
281 [nameCell.get() setButtonType:NSSwitchButton];
282 [nameCell.get() setAlignment:[[nameColumn dataCell] alignment]];
283 [nameCell.get() setFont:[[nameColumn dataCell] font]];
284 [nameColumn setDataCell:nameCell.get()];
286 // Initially, sort on the tab name.
287 [tableView_ setSortDescriptors:
288 [NSArray arrayWithObject:[nameColumn sortDescriptorPrototype]]];
289 [self addColumnWithId:IDS_TASK_MANAGER_PROFILE_NAME_COLUMN visible:NO];
290 [self addColumnWithId:IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN visible:YES];
291 [self addColumnWithId:IDS_TASK_MANAGER_SHARED_MEM_COLUMN visible:NO];
292 [self addColumnWithId:IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN visible:NO];
293 [self addColumnWithId:IDS_TASK_MANAGER_CPU_COLUMN visible:YES];
294 [self addColumnWithId:IDS_TASK_MANAGER_NET_COLUMN visible:YES];
295 [self addColumnWithId:IDS_TASK_MANAGER_PROCESS_ID_COLUMN visible:YES];
296 [self addColumnWithId:IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN
298 [self addColumnWithId:IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN
300 [self addColumnWithId:IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN visible:NO];
301 [self addColumnWithId:IDS_TASK_MANAGER_VIDEO_MEMORY_COLUMN visible:NO];
302 [self addColumnWithId:IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN visible:NO];
303 [self addColumnWithId:IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN
305 [self addColumnWithId:IDS_TASK_MANAGER_NACL_DEBUG_STUB_PORT_COLUMN
307 [self addColumnWithId:IDS_TASK_MANAGER_IDLE_WAKEUPS_COLUMN
311 // Creates a context menu for the table header that allows the user to toggle
312 // which columns should be shown and which should be hidden (like e.g.
313 // Task Manager.app's table header context menu).
314 - (void)setUpTableHeaderContextMenu {
315 base::scoped_nsobject<NSMenu> contextMenu(
316 [[NSMenu alloc] initWithTitle:@"Task Manager context menu"]);
317 for (NSTableColumn* column in [tableView_ tableColumns]) {
318 NSMenuItem* item = [contextMenu.get()
319 addItemWithTitle:[[column headerCell] stringValue]
320 action:@selector(toggleColumn:)
322 [item setTarget:self];
323 [item setRepresentedObject:column];
324 [item setState:[column isHidden] ? NSOffState : NSOnState];
326 [[tableView_ headerView] setMenu:contextMenu.get()];
329 // Callback for the table header context menu. Toggles visibility of the table
330 // column associated with the clicked menu item.
331 - (void)toggleColumn:(id)item {
332 DCHECK([item isKindOfClass:[NSMenuItem class]]);
333 if (![item isKindOfClass:[NSMenuItem class]])
336 NSTableColumn* column = [item representedObject];
338 NSInteger oldState = [item state];
339 NSInteger newState = oldState == NSOnState ? NSOffState : NSOnState;
340 [column setHidden:newState == NSOffState];
341 [item setState:newState];
342 [tableView_ sizeToFit];
343 [tableView_ setNeedsDisplay];
346 // This function appropriately sets the enabled states on the table's editing
348 - (void)adjustSelectionAndEndProcessButton {
349 bool selectionContainsBrowserProcess = false;
351 // If a row is selected, make sure that all rows belonging to the same process
352 // are selected as well. Also, check if the selection contains the browser
354 NSIndexSet* selection = [tableView_ selectedRowIndexes];
355 for (NSUInteger i = [selection lastIndex];
357 i = [selection indexLessThanIndex:i]) {
358 int modelIndex = viewToModelMap_[i];
359 if (taskManager_->IsBrowserProcess(modelIndex))
360 selectionContainsBrowserProcess = true;
362 TaskManagerModel::GroupRange rangePair =
363 model_->GetGroupRangeForResource(modelIndex);
364 NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
365 for (int j = 0; j < rangePair.second; ++j)
366 [indexSet addIndex:modelToViewMap_[rangePair.first + j]];
367 [tableView_ selectRowIndexes:indexSet byExtendingSelection:YES];
370 bool enabled = [selection count] > 0 && !selectionContainsBrowserProcess;
371 [endProcessButton_ setEnabled:enabled];
374 - (void)deselectRows {
375 [tableView_ deselectAll:self];
378 // Table view delegate methods.
380 // The selection is being changed by mouse (drag/click).
381 - (void)tableViewSelectionIsChanging:(NSNotification*)aNotification {
382 [self adjustSelectionAndEndProcessButton];
385 // The selection is being changed by keyboard (arrows).
386 - (void)tableViewSelectionDidChange:(NSNotification*)aNotification {
387 [self adjustSelectionAndEndProcessButton];
390 - (void)windowWillClose:(NSNotification*)notification {
391 if (taskManagerObserver_) {
392 taskManagerObserver_->WindowWasClosed();
393 taskManagerObserver_ = nil;
400 @implementation TaskManagerWindowController (NSTableDataSource)
402 - (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView {
403 DCHECK(tableView == tableView_ || tableView_ == nil);
404 return model_->ResourceCount();
407 - (NSString*)modelTextForRow:(int)row column:(int)columnId {
408 DCHECK_LT(static_cast<size_t>(row), viewToModelMap_.size());
409 return base::SysUTF16ToNSString(
410 model_->GetResourceById(viewToModelMap_[row], columnId));
413 - (id)tableView:(NSTableView*)tableView
414 objectValueForTableColumn:(NSTableColumn*)tableColumn
415 row:(NSInteger)rowIndex {
416 // NSButtonCells expect an on/off state as objectValue. Their title is set
417 // in |tableView:dataCellForTableColumn:row:| below.
418 if ([[tableColumn identifier] intValue] == IDS_TASK_MANAGER_TASK_COLUMN) {
419 return [NSNumber numberWithInt:NSOffState];
422 return [self modelTextForRow:rowIndex
423 column:[[tableColumn identifier] intValue]];
426 - (NSCell*)tableView:(NSTableView*)tableView
427 dataCellForTableColumn:(NSTableColumn*)tableColumn
428 row:(NSInteger)rowIndex {
429 NSCell* cell = [tableColumn dataCellForRow:rowIndex];
431 // Set the favicon and title for the task in the name column.
432 if ([[tableColumn identifier] intValue] == IDS_TASK_MANAGER_TASK_COLUMN) {
433 DCHECK([cell isKindOfClass:[NSButtonCell class]]);
434 NSButtonCell* buttonCell = static_cast<NSButtonCell*>(cell);
435 NSString* title = [self modelTextForRow:rowIndex
436 column:[[tableColumn identifier] intValue]];
437 [buttonCell setTitle:title];
438 [buttonCell setImage:
439 taskManagerObserver_->GetImageForRow(viewToModelMap_[rowIndex])];
440 [buttonCell setRefusesFirstResponder:YES]; // Don't push in like a button.
441 [buttonCell setHighlightsBy:NSNoCellMask];
447 - (void) tableView:(NSTableView*)tableView
448 sortDescriptorsDidChange:(NSArray*)oldDescriptors {
449 NSArray* newDescriptors = [tableView sortDescriptors];
450 if ([newDescriptors count] < 1)
453 currentSortDescriptor_.reset([[newDescriptors objectAtIndex:0] retain]);
454 [self reloadData]; // Sorts.
459 ////////////////////////////////////////////////////////////////////////////////
460 // TaskManagerMac implementation:
462 TaskManagerMac::TaskManagerMac(TaskManager* task_manager)
463 : task_manager_(task_manager),
464 model_(task_manager->model()),
467 [[TaskManagerWindowController alloc] initWithTaskManagerObserver:this];
468 model_->AddObserver(this);
472 TaskManagerMac* TaskManagerMac::instance_ = NULL;
474 TaskManagerMac::~TaskManagerMac() {
475 if (this == instance_) {
476 // Do not do this when running in unit tests: |StartUpdating()| never got
477 // called in that case.
478 task_manager_->OnWindowClosed();
480 model_->RemoveObserver(this);
483 ////////////////////////////////////////////////////////////////////////////////
484 // TaskManagerMac, TaskManagerModelObserver implementation:
486 void TaskManagerMac::OnModelChanged() {
487 icon_cache_.OnModelChanged();
488 [window_controller_ deselectRows];
489 [window_controller_ reloadData];
492 void TaskManagerMac::OnItemsChanged(int start, int length) {
493 icon_cache_.OnItemsChanged(start, length);
494 [window_controller_ reloadData];
497 void TaskManagerMac::OnItemsAdded(int start, int length) {
498 icon_cache_.OnItemsAdded(start, length);
499 [window_controller_ deselectRows];
500 [window_controller_ reloadData];
503 void TaskManagerMac::OnItemsRemoved(int start, int length) {
504 icon_cache_.OnItemsRemoved(start, length);
505 [window_controller_ deselectRows];
506 [window_controller_ reloadData];
509 NSImage* TaskManagerMac::GetImageForRow(int row) {
510 return icon_cache_.GetImageForRow(row);
513 ////////////////////////////////////////////////////////////////////////////////
514 // TaskManagerMac, public:
516 void TaskManagerMac::WindowWasClosed() {
518 instance_ = NULL; // |instance_| is static
521 int TaskManagerMac::RowCount() const {
522 return model_->ResourceCount();
525 gfx::ImageSkia TaskManagerMac::GetIcon(int r) const {
526 return model_->GetResourceIcon(r);
530 void TaskManagerMac::Show() {
532 [[instance_->window_controller_ window]
533 makeKeyAndOrderFront:instance_->window_controller_];
536 // Create a new instance.
537 instance_ = new TaskManagerMac(TaskManager::GetInstance());
538 instance_->model_->StartUpdating();
542 void TaskManagerMac::Hide() {
544 [instance_->window_controller_ close];
549 // Declared in browser_dialogs.h.
550 void ShowTaskManager(Browser* browser) {
551 TaskManagerMac::Show();
554 void HideTaskManager() {
555 TaskManagerMac::Hide();
558 } // namespace chrome