extension_web_ui.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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. 4 5#include "chrome/browser/extensions/extension_web_ui.h" 6 7#include <set> 8#include <vector> 9 10#include "base/command_line.h" 11#include "base/prefs/pref_service.h" 12#include "base/string_util.h" 13#include "base/utf_string_conversions.h" 14#include "chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h" 15#include "chrome/browser/extensions/extension_service.h" 16#include "chrome/browser/extensions/extension_tab_util.h" 17#include "chrome/browser/extensions/image_loader.h" 18#include "chrome/browser/favicon/favicon_util.h" 19#include "chrome/browser/prefs/scoped_user_pref_update.h" 20#include "chrome/browser/profiles/profile.h" 21#include "chrome/common/chrome_switches.h" 22#include "chrome/common/extensions/extension.h" 23#include "chrome/common/extensions/extension_constants.h" 24#include "chrome/common/extensions/extension_icon_set.h" 25#include "chrome/common/extensions/incognito_handler.h" 26#include "chrome/common/extensions/manifest_handlers/icons_handler.h" 27#include "chrome/common/url_constants.h" 28#include "components/user_prefs/pref_registry_syncable.h" 29#include "content/public/browser/navigation_controller.h" 30#include "content/public/browser/web_contents.h" 31#include "content/public/browser/web_ui.h" 32#include "content/public/common/bindings_policy.h" 33#include "content/public/common/page_transition_types.h" 34#include "extensions/common/extension_resource.h" 35#include "net/base/file_stream.h" 36#include "third_party/skia/include/core/SkBitmap.h" 37#include "ui/gfx/codec/png_codec.h" 38#include "ui/gfx/favicon_size.h" 39#include "ui/gfx/image/image_skia.h" 40 41using content::WebContents; 42using extensions::Extension; 43using extensions::URLOverrides; 44 45namespace { 46 47// De-dupes the items in |list|. Assumes the values are strings. 48void CleanUpDuplicates(ListValue* list) { 49 std::set<std::string> seen_values; 50 51 // Loop backwards as we may be removing items. 52 for (size_t i = list->GetSize() - 1; (i + 1) > 0; --i) { 53 std::string value; 54 if (!list->GetString(i, &value)) { 55 NOTREACHED(); 56 continue; 57 } 58 59 if (seen_values.find(value) == seen_values.end()) 60 seen_values.insert(value); 61 else 62 list->Remove(i, NULL); 63 } 64} 65 66// Reloads the page in |web_contents| if it uses the same profile as |profile| 67// and if the current URL is a chrome URL. 68void UnregisterAndReplaceOverrideForWebContents( 69 const std::string& page, Profile* profile, WebContents* web_contents) { 70 if (Profile::FromBrowserContext(web_contents->GetBrowserContext()) != profile) 71 return; 72 73 GURL url = web_contents->GetURL(); 74 if (!url.SchemeIs(chrome::kChromeUIScheme) || url.host() != page) 75 return; 76 77 // Don't use Reload() since |url| isn't the same as the internal URL that 78 // NavigationController has. 79 web_contents->GetController().LoadURL( 80 url, content::Referrer(url, WebKit::WebReferrerPolicyDefault), 81 content::PAGE_TRANSITION_RELOAD, std::string()); 82} 83 84// Run favicon callbck with image result. If no favicon was available then 85// |image| will be empty. 86void RunFaviconCallbackAsync( 87 const FaviconService::FaviconResultsCallback& callback, 88 const gfx::Image& image) { 89 std::vector<history::FaviconBitmapResult>* favicon_bitmap_results = 90 new std::vector<history::FaviconBitmapResult>(); 91 92 const std::vector<gfx::ImageSkiaRep>& image_reps = 93 image.AsImageSkia().image_reps(); 94 for (size_t i = 0; i < image_reps.size(); ++i) { 95 const gfx::ImageSkiaRep& image_rep = image_reps[i]; 96 scoped_refptr<base::RefCountedBytes> bitmap_data( 97 new base::RefCountedBytes()); 98 if (gfx::PNGCodec::EncodeBGRASkBitmap(image_rep.sk_bitmap(), 99 false, 100 &bitmap_data->data())) { 101 history::FaviconBitmapResult bitmap_result; 102 bitmap_result.bitmap_data = bitmap_data; 103 bitmap_result.pixel_size = gfx::Size(image_rep.pixel_width(), 104 image_rep.pixel_height()); 105 // Leave |bitmap_result|'s icon URL as the default of GURL(). 106 bitmap_result.icon_type = history::FAVICON; 107 108 favicon_bitmap_results->push_back(bitmap_result); 109 } else { 110 NOTREACHED() << "Could not encode extension favicon"; 111 } 112 } 113 114 base::MessageLoopProxy::current()->PostTask( 115 FROM_HERE, 116 base::Bind(&FaviconService::FaviconResultsCallbackRunner, 117 callback, 118 base::Owned(favicon_bitmap_results))); 119} 120 121} // namespace 122 123const char ExtensionWebUI::kExtensionURLOverrides[] = 124 "extensions.chrome_url_overrides"; 125 126ExtensionWebUI::ExtensionWebUI(content::WebUI* web_ui, const GURL& url) 127 : WebUIController(web_ui), 128 url_(url) { 129 Profile* profile = Profile::FromWebUI(web_ui); 130 ExtensionService* service = profile->GetExtensionService(); 131 const Extension* extension = 132 service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(url)); 133 DCHECK(extension); 134 135 // The base class defaults to enabling WebUI bindings, but we don't need 136 // those (this is also reflected in ChromeWebUIControllerFactory:: 137 // UseWebUIBindingsForURL). 138 int bindings = 0; 139 140 // Bind externalHost to Extension WebUI loaded in Chrome Frame. 141 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); 142 if (browser_command_line.HasSwitch(switches::kChromeFrame)) 143 bindings |= content::BINDINGS_POLICY_EXTERNAL_HOST; 144 web_ui->SetBindings(bindings); 145 146 // Hack: A few things we specialize just for the bookmark manager. 147 if (extension->id() == extension_misc::kBookmarkManagerId) { 148 bookmark_manager_private_event_router_.reset( 149 new extensions::BookmarkManagerPrivateEventRouter( 150 profile, web_ui->GetWebContents())); 151 152 web_ui->SetLinkTransitionType(content::PAGE_TRANSITION_AUTO_BOOKMARK); 153 } 154} 155 156ExtensionWebUI::~ExtensionWebUI() {} 157 158extensions::BookmarkManagerPrivateEventRouter* 159ExtensionWebUI::bookmark_manager_private_event_router() { 160 return bookmark_manager_private_event_router_.get(); 161} 162 163//////////////////////////////////////////////////////////////////////////////// 164// chrome:// URL overrides 165 166// static 167void ExtensionWebUI::RegisterUserPrefs( 168 user_prefs::PrefRegistrySyncable* registry) { 169 registry->RegisterDictionaryPref( 170 kExtensionURLOverrides, 171 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 172} 173 174// static 175bool ExtensionWebUI::HandleChromeURLOverride( 176 GURL* url, content::BrowserContext* browser_context) { 177 if (!url->SchemeIs(chrome::kChromeUIScheme)) 178 return false; 179 180 Profile* profile = Profile::FromBrowserContext(browser_context); 181 const DictionaryValue* overrides = 182 profile->GetPrefs()->GetDictionary(kExtensionURLOverrides); 183 std::string page = url->host(); 184 const ListValue* url_list = NULL; 185 if (!overrides || !overrides->GetList(page, &url_list)) 186 return false; 187 188 ExtensionService* service = profile->GetExtensionService(); 189 190 size_t i = 0; 191 while (i < url_list->GetSize()) { 192 const Value* val = NULL; 193 url_list->Get(i, &val); 194 195 // Verify that the override value is good. If not, unregister it and find 196 // the next one. 197 std::string override; 198 if (!val->GetAsString(&override)) { 199 NOTREACHED(); 200 UnregisterChromeURLOverride(page, profile, val); 201 continue; 202 } 203 204 if (!url->query().empty()) 205 override += "?" + url->query(); 206 if (!url->ref().empty()) 207 override += "#" + url->ref(); 208 GURL extension_url(override); 209 if (!extension_url.is_valid()) { 210 NOTREACHED(); 211 UnregisterChromeURLOverride(page, profile, val); 212 continue; 213 } 214 215 // Verify that the extension that's being referred to actually exists. 216 const Extension* extension = 217 service->extensions()->GetByID(extension_url.host()); 218 if (!extension) { 219 // This can currently happen if you use --load-extension one run, and 220 // then don't use it the next. It could also happen if an extension 221 // were deleted directly from the filesystem, etc. 222 LOG(WARNING) << "chrome URL override present for non-existant extension"; 223 UnregisterChromeURLOverride(page, profile, val); 224 continue; 225 } 226 227 // We can't handle chrome-extension URLs in incognito mode unless the 228 // extension uses split mode. 229 bool incognito_override_allowed = 230 extensions::IncognitoInfo::IsSplitMode(extension) && 231 service->IsIncognitoEnabled(extension->id()); 232 if (profile->IsOffTheRecord() && !incognito_override_allowed) { 233 ++i; 234 continue; 235 } 236 237 *url = extension_url; 238 return true; 239 } 240 return false; 241} 242 243// static 244bool ExtensionWebUI::HandleChromeURLOverrideReverse( 245 GURL* url, content::BrowserContext* browser_context) { 246 Profile* profile = Profile::FromBrowserContext(browser_context); 247 const DictionaryValue* overrides = 248 profile->GetPrefs()->GetDictionary(kExtensionURLOverrides); 249 if (!overrides) 250 return false; 251 252 // Find the reverse mapping based on the given URL. For example this maps the 253 // internal URL 254 // chrome-extension://eemcgdkfndhakfknompkggombfjjjeno/main.html#1 to 255 // chrome://bookmarks/#1 for display in the omnibox. 256 for (DictionaryValue::Iterator it(*overrides); !it.IsAtEnd(); it.Advance()) { 257 const ListValue* url_list = NULL; 258 if (!it.value().GetAsList(&url_list)) 259 continue; 260 261 for (ListValue::const_iterator it2 = url_list->begin(); 262 it2 != url_list->end(); ++it2) { 263 std::string override; 264 if (!(*it2)->GetAsString(&override)) 265 continue; 266 if (StartsWithASCII(url->spec(), override, true)) { 267 GURL original_url(chrome::kChromeUIScheme + std::string("://") + 268 it.key() + url->spec().substr(override.length())); 269 *url = original_url; 270 return true; 271 } 272 } 273 } 274 275 return false; 276} 277 278// static 279void ExtensionWebUI::RegisterChromeURLOverrides( 280 Profile* profile, const URLOverrides::URLOverrideMap& overrides) { 281 if (overrides.empty()) 282 return; 283 284 PrefService* prefs = profile->GetPrefs(); 285 DictionaryPrefUpdate update(prefs, kExtensionURLOverrides); 286 DictionaryValue* all_overrides = update.Get(); 287 288 // For each override provided by the extension, add it to the front of 289 // the override list if it's not already in the list. 290 URLOverrides::URLOverrideMap::const_iterator iter = overrides.begin(); 291 for (; iter != overrides.end(); ++iter) { 292 const std::string& key = iter->first; 293 ListValue* page_overrides = NULL; 294 if (!all_overrides->GetList(key, &page_overrides)) { 295 page_overrides = new ListValue(); 296 all_overrides->Set(key, page_overrides); 297 } else { 298 CleanUpDuplicates(page_overrides); 299 300 // Verify that the override isn't already in the list. 301 ListValue::iterator i = page_overrides->begin(); 302 for (; i != page_overrides->end(); ++i) { 303 std::string override_val; 304 if (!(*i)->GetAsString(&override_val)) { 305 NOTREACHED(); 306 continue; 307 } 308 if (override_val == iter->second.spec()) 309 break; 310 } 311 // This value is already in the list, leave it alone. 312 if (i != page_overrides->end()) 313 continue; 314 } 315 // Insert the override at the front of the list. Last registered override 316 // wins. 317 page_overrides->Insert(0, new StringValue(iter->second.spec())); 318 } 319} 320 321// static 322void ExtensionWebUI::UnregisterAndReplaceOverride(const std::string& page, 323 Profile* profile, 324 ListValue* list, 325 const Value* override) { 326 size_t index = 0; 327 bool found = list->Remove(*override, &index); 328 if (found && index == 0) { 329 // This is the active override, so we need to find all existing 330 // tabs for this override and get them to reload the original URL. 331 base::Callback<void(WebContents*)> callback = 332 base::Bind(&UnregisterAndReplaceOverrideForWebContents, page, profile); 333 ExtensionTabUtil::ForEachTab(callback); 334 } 335} 336 337// static 338void ExtensionWebUI::UnregisterChromeURLOverride(const std::string& page, 339 Profile* profile, 340 const Value* override) { 341 if (!override) 342 return; 343 PrefService* prefs = profile->GetPrefs(); 344 DictionaryPrefUpdate update(prefs, kExtensionURLOverrides); 345 DictionaryValue* all_overrides = update.Get(); 346 ListValue* page_overrides = NULL; 347 if (!all_overrides->GetList(page, &page_overrides)) { 348 // If it's being unregistered, it should already be in the list. 349 NOTREACHED(); 350 return; 351 } else { 352 UnregisterAndReplaceOverride(page, profile, page_overrides, override); 353 } 354} 355 356// static 357void ExtensionWebUI::UnregisterChromeURLOverrides( 358 Profile* profile, const URLOverrides::URLOverrideMap& overrides) { 359 if (overrides.empty()) 360 return; 361 PrefService* prefs = profile->GetPrefs(); 362 DictionaryPrefUpdate update(prefs, kExtensionURLOverrides); 363 DictionaryValue* all_overrides = update.Get(); 364 URLOverrides::URLOverrideMap::const_iterator iter = overrides.begin(); 365 for (; iter != overrides.end(); ++iter) { 366 const std::string& page = iter->first; 367 ListValue* page_overrides = NULL; 368 if (!all_overrides->GetList(page, &page_overrides)) { 369 // If it's being unregistered, it should already be in the list. 370 NOTREACHED(); 371 continue; 372 } else { 373 StringValue override(iter->second.spec()); 374 UnregisterAndReplaceOverride(iter->first, profile, 375 page_overrides, &override); 376 } 377 } 378} 379 380// static 381void ExtensionWebUI::GetFaviconForURL( 382 Profile* profile, 383 const GURL& page_url, 384 const FaviconService::FaviconResultsCallback& callback) { 385 // Even when the extensions service is enabled by default, it's still 386 // disabled in incognito mode. 387 ExtensionService* service = profile->GetExtensionService(); 388 if (!service) { 389 RunFaviconCallbackAsync(callback, gfx::Image()); 390 return; 391 } 392 const Extension* extension = service->extensions()->GetByID(page_url.host()); 393 if (!extension) { 394 RunFaviconCallbackAsync(callback, gfx::Image()); 395 return; 396 } 397 398 // Fetch resources for all supported scale factors for which there are 399 // resources. Load image reps for all supported scale factors (in addition to 400 // 1x) immediately instead of in an as needed fashion to be consistent with 401 // how favicons are requested for chrome:// and page URLs. 402 const std::vector<ui::ScaleFactor>& scale_factors = 403 FaviconUtil::GetFaviconScaleFactors(); 404 std::vector<extensions::ImageLoader::ImageRepresentation> info_list; 405 for (size_t i = 0; i < scale_factors.size(); ++i) { 406 float scale = ui::GetScaleFactorScale(scale_factors[i]); 407 int pixel_size = static_cast<int>(gfx::kFaviconSize * scale); 408 extensions::ExtensionResource icon_resource = 409 extensions::IconsInfo::GetIconResource(extension, 410 pixel_size, 411 ExtensionIconSet::MATCH_BIGGER); 412 413 info_list.push_back( 414 extensions::ImageLoader::ImageRepresentation( 415 icon_resource, 416 extensions::ImageLoader::ImageRepresentation::ALWAYS_RESIZE, 417 gfx::Size(pixel_size, pixel_size), 418 scale_factors[i])); 419 } 420 421 // LoadImagesAsync actually can run callback synchronously. We want to force 422 // async. 423 extensions::ImageLoader::Get(profile)->LoadImagesAsync( 424 extension, info_list, base::Bind(&RunFaviconCallbackAsync, callback)); 425} 426