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/history_menu_bridge.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/string_util.h"
10 #include "base/strings/sys_string_conversions.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/app/chrome_command_ids.h" // IDC_HISTORY_MENU
13 #include "chrome/browser/favicon/favicon_service_factory.h"
14 #include "chrome/browser/history/history_service_factory.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/sessions/tab_restore_service_factory.h"
17 #import "chrome/browser/ui/cocoa/history_menu_cocoa_controller.h"
18 #include "chrome/grit/generated_resources.h"
19 #include "grit/theme_resources.h"
20 #include "ui/base/l10n/l10n_util.h"
21 #include "ui/base/resource/resource_bundle.h"
22 #include "ui/gfx/image/image.h"
23 #include "ui/gfx/text_elider.h"
24 #include "ui/resources/grit/ui_resources.h"
28 // Maximum number of pixels to use for a menu item title.
29 const float kTitlePixelWidth = 400;
31 // Number of days to consider when getting the number of visited items.
32 const int kVisitedScope = 90;
34 // The number of visisted results to get.
35 const int kVisitedCount = 15;
37 // The number of recently closed items to get.
38 const unsigned int kRecentlyClosedCount = 10;
42 HistoryMenuBridge::HistoryItem::HistoryItem()
43 : icon_requested(false),
44 icon_task_id(base::CancelableTaskTracker::kBadTaskId),
48 HistoryMenuBridge::HistoryItem::HistoryItem(const HistoryItem& copy)
51 icon_requested(false),
52 icon_task_id(base::CancelableTaskTracker::kBadTaskId),
54 session_id(copy.session_id) {}
56 HistoryMenuBridge::HistoryItem::~HistoryItem() {
59 HistoryMenuBridge::HistoryMenuBridge(Profile* profile)
60 : controller_([[HistoryMenuCocoaController alloc] initWithBridge:this]),
62 history_service_(NULL),
63 tab_restore_service_(NULL),
64 create_in_progress_(false),
65 need_recreate_(false),
66 history_service_observer_(this) {
67 // If we don't have a profile, do not bother initializing our data sources.
68 // This shouldn't happen except in unit tests.
70 // Check to see if the history service is ready. Because it loads async, it
71 // may not be ready when the Bridge is created. If this happens, register
72 // for a notification that tells us the HistoryService is ready.
73 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
74 profile_, ServiceAccessType::EXPLICIT_ACCESS);
76 history_service_observer_.Add(hs);
77 if (hs->BackendLoaded()) {
78 history_service_ = hs;
83 tab_restore_service_ = TabRestoreServiceFactory::GetForProfile(profile_);
84 if (tab_restore_service_) {
85 tab_restore_service_->AddObserver(this);
86 // If the tab entries are already loaded, invoke the observer method to
87 // build the "Recently Closed" section. Otherwise it will be when the
89 if (!tab_restore_service_->IsLoaded())
90 tab_restore_service_->LoadTabsFromLastSession();
92 TabRestoreServiceChanged(tab_restore_service_);
96 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
97 default_favicon_.reset(
98 rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).CopyNSImage());
100 // Set the static icons in the menu.
101 NSMenuItem* item = [HistoryMenu() itemWithTag:IDC_SHOW_HISTORY];
102 [item setImage:rb.GetNativeImageNamed(IDR_HISTORY_FAVICON).ToNSImage()];
106 // Note that all requests sent to either the history service or the favicon
107 // service will be automatically cancelled by their respective Consumers, so
108 // task cancellation is not done manually here in the dtor.
109 HistoryMenuBridge::~HistoryMenuBridge() {
110 // Unregister ourselves as observers and notifications.
113 if (tab_restore_service_)
114 tab_restore_service_->RemoveObserver(this);
116 // Since the map owns the HistoryItems, delete anything that still exists.
117 std::map<NSMenuItem*, HistoryItem*>::iterator it = menu_item_map_.begin();
118 while (it != menu_item_map_.end()) {
119 HistoryItem* item = it->second;
120 menu_item_map_.erase(it++);
125 void HistoryMenuBridge::TabRestoreServiceChanged(TabRestoreService* service) {
126 const TabRestoreService::Entries& entries = service->entries();
128 // Clear the history menu before rebuilding.
129 NSMenu* menu = HistoryMenu();
130 ClearMenuSection(menu, kRecentlyClosed);
132 // Index for the next menu item.
133 NSInteger index = [menu indexOfItemWithTag:kRecentlyClosedTitle] + 1;
134 NSUInteger added_count = 0;
136 for (TabRestoreService::Entries::const_iterator it = entries.begin();
137 it != entries.end() && added_count < kRecentlyClosedCount; ++it) {
138 TabRestoreService::Entry* entry = *it;
140 // If this is a window, create a submenu for all of its tabs.
141 if (entry->type == TabRestoreService::WINDOW) {
142 TabRestoreService::Window* entry_win = (TabRestoreService::Window*)entry;
143 std::vector<TabRestoreService::Tab>& tabs = entry_win->tabs;
147 // Create the item for the parent/window. Do not set the title yet because
148 // the actual number of items that are in the menu will not be known until
149 // things like the NTP are filtered out, which is done when the tab items
150 // are actually created.
151 HistoryItem* item = new HistoryItem();
152 item->session_id = entry_win->id;
154 // Create the submenu.
155 base::scoped_nsobject<NSMenu> submenu([[NSMenu alloc] init]);
157 // Create standard items within the window submenu.
158 NSString* restore_title = l10n_util::GetNSString(
159 IDS_HISTORY_CLOSED_RESTORE_WINDOW_MAC);
160 base::scoped_nsobject<NSMenuItem> restore_item(
161 [[NSMenuItem alloc] initWithTitle:restore_title
162 action:@selector(openHistoryMenuItem:)
164 [restore_item setTarget:controller_.get()];
165 // Duplicate the HistoryItem otherwise the different NSMenuItems will
166 // point to the same HistoryItem, which would then be double-freed when
167 // removing the items from the map or in the dtor.
168 HistoryItem* dup_item = new HistoryItem(*item);
169 menu_item_map_.insert(std::make_pair(restore_item.get(), dup_item));
170 [submenu addItem:restore_item.get()];
171 [submenu addItem:[NSMenuItem separatorItem]];
173 // Loop over the window's tabs and add them to the submenu.
174 NSInteger subindex = [[submenu itemArray] count];
175 std::vector<TabRestoreService::Tab>::const_iterator it;
176 for (it = tabs.begin(); it != tabs.end(); ++it) {
177 TabRestoreService::Tab tab = *it;
178 HistoryItem* tab_item = HistoryItemForTab(tab);
180 item->tabs.push_back(tab_item);
181 AddItemToMenu(tab_item, submenu.get(), kRecentlyClosed + 1,
186 // Now that the number of tabs that has been added is known, set the title
187 // of the parent menu item.
188 item->title = l10n_util::GetPluralStringFUTF16(
189 IDS_RECENTLY_CLOSED_WINDOW, item->tabs.size());
191 // Sometimes it is possible for there to not be any subitems for a given
192 // window; if that is the case, do not add the entry to the main menu.
193 if ([[submenu itemArray] count] > 2) {
194 // Create the menu item parent.
195 NSMenuItem* parent_item =
196 AddItemToMenu(item, menu, kRecentlyClosed, index++);
197 [parent_item setSubmenu:submenu.get()];
200 } else if (entry->type == TabRestoreService::TAB) {
201 TabRestoreService::Tab* tab =
202 static_cast<TabRestoreService::Tab*>(entry);
203 HistoryItem* item = HistoryItemForTab(*tab);
205 AddItemToMenu(item, menu, kRecentlyClosed, index++);
212 void HistoryMenuBridge::TabRestoreServiceDestroyed(
213 TabRestoreService* service) {
214 // Intentionally left blank. We hold a weak reference to the service.
217 void HistoryMenuBridge::ResetMenu() {
218 NSMenu* menu = HistoryMenu();
219 ClearMenuSection(menu, kVisited);
220 ClearMenuSection(menu, kRecentlyClosed);
223 void HistoryMenuBridge::BuildMenu() {
224 // If the history service is ready, use it. Otherwise, a Notification will
225 // force an update when it's loaded.
226 if (history_service_)
230 HistoryMenuBridge::HistoryItem* HistoryMenuBridge::HistoryItemForMenuItem(
232 std::map<NSMenuItem*, HistoryItem*>::iterator it = menu_item_map_.find(item);
233 if (it != menu_item_map_.end()) {
239 history::HistoryService* HistoryMenuBridge::service() {
240 return history_service_;
243 Profile* HistoryMenuBridge::profile() {
247 NSMenu* HistoryMenuBridge::HistoryMenu() {
248 NSMenu* history_menu = [[[NSApp mainMenu] itemWithTag:IDC_HISTORY_MENU]
253 void HistoryMenuBridge::ClearMenuSection(NSMenu* menu, NSInteger tag) {
254 for (NSMenuItem* menu_item in [menu itemArray]) {
255 if ([menu_item tag] == tag && [menu_item target] == controller_.get()) {
256 // This is an item that should be removed, so find the corresponding model
258 HistoryItem* item = HistoryItemForMenuItem(menu_item);
260 // Cancel favicon requests that could hold onto stale pointers. Also
261 // remove the item from the mapping.
263 CancelFaviconRequest(item);
264 menu_item_map_.erase(menu_item);
268 // If this menu item has a submenu, recurse.
269 if ([menu_item hasSubmenu]) {
270 ClearMenuSection([menu_item submenu], tag + 1);
273 // Now actually remove the item from the menu.
274 [menu removeItem:menu_item];
279 NSMenuItem* HistoryMenuBridge::AddItemToMenu(HistoryItem* item,
283 // Elide the title of the history item, or use the URL if there is none.
284 std::string url = item->url.possibly_invalid_spec();
285 base::string16 full_title = item->title;
286 base::string16 title =
287 gfx::ElideText(full_title.empty() ? base::UTF8ToUTF16(url) : full_title,
288 gfx::FontList(gfx::Font([NSFont menuFontOfSize:0])),
292 item->menu_item.reset(
293 [[NSMenuItem alloc] initWithTitle:base::SysUTF16ToNSString(title)
296 [item->menu_item setTarget:controller_];
297 [item->menu_item setAction:@selector(openHistoryMenuItem:)];
298 [item->menu_item setTag:tag];
299 if (item->icon.get())
300 [item->menu_item setImage:item->icon.get()];
301 else if (!item->tabs.size())
302 [item->menu_item setImage:default_favicon_.get()];
305 NSString* tooltip = [NSString stringWithFormat:@"%@\n%@",
306 base::SysUTF16ToNSString(full_title), base::SysUTF8ToNSString(url)];
307 [item->menu_item setToolTip:tooltip];
309 [menu insertItem:item->menu_item.get() atIndex:index];
310 menu_item_map_.insert(std::make_pair(item->menu_item.get(), item));
312 return item->menu_item.get();
315 void HistoryMenuBridge::Init() {
316 DCHECK(history_service_);
319 void HistoryMenuBridge::CreateMenu() {
320 // If we're currently running CreateMenu(), wait until it finishes.
321 if (create_in_progress_)
323 create_in_progress_ = true;
324 need_recreate_ = false;
326 DCHECK(history_service_);
328 history::QueryOptions options;
329 options.max_count = kVisitedCount;
330 options.SetRecentDayRange(kVisitedScope);
332 history_service_->QueryHistory(
335 base::Bind(&HistoryMenuBridge::OnVisitedHistoryResults,
336 base::Unretained(this)),
337 &cancelable_task_tracker_);
340 void HistoryMenuBridge::OnHistoryChanged() {
341 // History has changed, rebuild menu.
342 need_recreate_ = true;
346 void HistoryMenuBridge::OnVisitedHistoryResults(
347 history::QueryResults* results) {
348 NSMenu* menu = HistoryMenu();
349 ClearMenuSection(menu, kVisited);
350 NSInteger top_item = [menu indexOfItemWithTag:kVisitedTitle] + 1;
352 size_t count = results->size();
353 for (size_t i = 0; i < count; ++i) {
354 const history::URLResult& result = (*results)[i];
356 HistoryItem* item = new HistoryItem;
357 item->title = result.title();
358 item->url = result.url();
360 // Need to explicitly get the favicon for each row.
361 GetFaviconForHistoryItem(item);
363 // This will add |item| to the |menu_item_map_|, which takes ownership.
364 AddItemToMenu(item, HistoryMenu(), kVisited, top_item + i);
367 // We are already invalid by the time we finished, darn.
371 create_in_progress_ = false;
374 HistoryMenuBridge::HistoryItem* HistoryMenuBridge::HistoryItemForTab(
375 const TabRestoreService::Tab& entry) {
376 DCHECK(!entry.navigations.empty());
378 const sessions::SerializedNavigationEntry& current_navigation =
379 entry.navigations.at(entry.current_navigation_index);
380 HistoryItem* item = new HistoryItem();
381 item->title = current_navigation.title();
382 item->url = current_navigation.virtual_url();
383 item->session_id = entry.id;
385 // Tab navigations don't come with icons, so we always have to request them.
386 GetFaviconForHistoryItem(item);
391 void HistoryMenuBridge::GetFaviconForHistoryItem(HistoryItem* item) {
392 favicon::FaviconService* service = FaviconServiceFactory::GetForProfile(
393 profile_, ServiceAccessType::EXPLICIT_ACCESS);
394 base::CancelableTaskTracker::TaskId task_id =
395 service->GetFaviconImageForPageURL(
398 &HistoryMenuBridge::GotFaviconData, base::Unretained(this), item),
399 &cancelable_task_tracker_);
400 item->icon_task_id = task_id;
401 item->icon_requested = true;
404 void HistoryMenuBridge::GotFaviconData(
406 const favicon_base::FaviconImageResult& image_result) {
407 // Since we're going to do Cocoa-y things, make sure this is the main thread.
408 DCHECK([NSThread isMainThread]);
411 item->icon_requested = false;
412 item->icon_task_id = base::CancelableTaskTracker::kBadTaskId;
414 NSImage* image = image_result.image.AsNSImage();
416 item->icon.reset([image retain]);
417 [item->menu_item setImage:item->icon.get()];
421 void HistoryMenuBridge::CancelFaviconRequest(HistoryItem* item) {
423 if (item->icon_requested) {
424 cancelable_task_tracker_.TryCancel(item->icon_task_id);
425 item->icon_requested = false;
426 item->icon_task_id = base::CancelableTaskTracker::kBadTaskId;
430 void HistoryMenuBridge::OnURLVisited(history::HistoryService* history_service,
431 ui::PageTransition transition,
432 const history::URLRow& row,
433 const history::RedirectList& redirects,
434 base::Time visit_time) {
438 void HistoryMenuBridge::OnURLsModified(history::HistoryService* history_service,
439 const history::URLRows& changed_urls) {
443 void HistoryMenuBridge::OnURLsDeleted(history::HistoryService* history_service,
446 const history::URLRows& deleted_rows,
447 const std::set<GURL>& favicon_urls) {
451 void HistoryMenuBridge::OnHistoryServiceLoaded(
452 history::HistoryService* history_service) {
453 history_service_ = history_service;