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 #ifndef CHROME_BROWSER_EXTENSIONS_MENU_MANAGER_H_ 6 #define CHROME_BROWSER_EXTENSIONS_MENU_MANAGER_H_ 7 8 #include <map> 9 #include <set> 10 #include <string> 11 #include <vector> 12 13 #include "base/basictypes.h" 14 #include "base/compiler_specific.h" 15 #include "base/gtest_prod_util.h" 16 #include "base/memory/scoped_ptr.h" 17 #include "base/memory/weak_ptr.h" 18 #include "base/scoped_observer.h" 19 #include "base/strings/string16.h" 20 #include "base/values.h" 21 #include "chrome/browser/extensions/extension_icon_manager.h" 22 #include "components/keyed_service/core/keyed_service.h" 23 #include "content/public/browser/notification_observer.h" 24 #include "content/public/browser/notification_registrar.h" 25 #include "extensions/browser/extension_registry_observer.h" 26 #include "extensions/common/url_pattern_set.h" 27 28 class SkBitmap; 29 30 namespace content { 31 class BrowserContext; 32 class WebContents; 33 struct ContextMenuParams; 34 } 35 36 namespace extensions { 37 class Extension; 38 class ExtensionRegistry; 39 class StateStore; 40 41 // Represents a menu item added by an extension. 42 class MenuItem { 43 public: 44 // A list of MenuItems. 45 typedef std::vector<MenuItem*> List; 46 47 // Key used to identify which extension a menu item belongs to. 48 // A menu item can also belong to a <webview> inside an extension, 49 // only in that case |webview_instance_id| would be 50 // non-zero (i.e. != guestview::kInstanceIDNone). 51 struct ExtensionKey { 52 std::string extension_id; 53 int webview_instance_id; 54 55 ExtensionKey(); 56 ExtensionKey(const std::string& extension_id, int webview_instance_id); 57 explicit ExtensionKey(const std::string& extension_id); 58 59 bool operator==(const ExtensionKey& other) const; 60 bool operator!=(const ExtensionKey& other) const; 61 bool operator<(const ExtensionKey& other) const; 62 63 bool empty() const; 64 }; 65 66 // An Id uniquely identifies a context menu item registered by an extension. 67 struct Id { 68 Id(); 69 // Since the unique ID (uid or string_uid) is parsed from API arguments, 70 // the normal usage is to set the uid or string_uid immediately after 71 // construction. 72 Id(bool incognito, const ExtensionKey& extension_key); 73 ~Id(); 74 75 bool operator==(const Id& other) const; 76 bool operator!=(const Id& other) const; 77 bool operator<(const Id& other) const; 78 79 bool incognito; 80 ExtensionKey extension_key; 81 // Only one of uid or string_uid will be defined. 82 int uid; 83 std::string string_uid; 84 }; 85 86 // For context menus, these are the contexts where an item can appear. 87 enum Context { 88 ALL = 1, 89 PAGE = 2, 90 SELECTION = 4, 91 LINK = 8, 92 EDITABLE = 16, 93 IMAGE = 32, 94 VIDEO = 64, 95 AUDIO = 128, 96 FRAME = 256, 97 LAUNCHER = 512, 98 BROWSER_ACTION = 1024, 99 PAGE_ACTION = 2048 100 }; 101 102 // An item can be only one of these types. 103 enum Type { 104 NORMAL, 105 CHECKBOX, 106 RADIO, 107 SEPARATOR 108 }; 109 110 // A list of Contexts for an item. 111 class ContextList { 112 public: 113 ContextList() : value_(0) {} 114 explicit ContextList(Context context) : value_(context) {} 115 ContextList(const ContextList& other) : value_(other.value_) {} 116 117 void operator=(const ContextList& other) { 118 value_ = other.value_; 119 } 120 121 bool operator==(const ContextList& other) const { 122 return value_ == other.value_; 123 } 124 125 bool operator!=(const ContextList& other) const { 126 return !(*this == other); 127 } 128 129 bool Contains(Context context) const { 130 return (value_ & context) > 0; 131 } 132 133 void Add(Context context) { 134 value_ |= context; 135 } 136 137 scoped_ptr<base::Value> ToValue() const { 138 return scoped_ptr<base::Value>( 139 new base::FundamentalValue(static_cast<int>(value_))); 140 } 141 142 bool Populate(const base::Value& value) { 143 int int_value; 144 if (!value.GetAsInteger(&int_value) || int_value < 0) 145 return false; 146 value_ = int_value; 147 return true; 148 } 149 150 private: 151 uint32 value_; // A bitmask of Context values. 152 }; 153 154 MenuItem(const Id& id, 155 const std::string& title, 156 bool checked, 157 bool enabled, 158 Type type, 159 const ContextList& contexts); 160 virtual ~MenuItem(); 161 162 // Simple accessor methods. 163 bool incognito() const { return id_.incognito; } 164 const std::string& extension_id() const { 165 return id_.extension_key.extension_id; 166 } 167 const std::string& title() const { return title_; } 168 const List& children() { return children_; } 169 const Id& id() const { return id_; } 170 Id* parent_id() const { return parent_id_.get(); } 171 int child_count() const { return children_.size(); } 172 const ContextList& contexts() const { return contexts_; } 173 Type type() const { return type_; } 174 bool checked() const { return checked_; } 175 bool enabled() const { return enabled_; } 176 const URLPatternSet& document_url_patterns() const { 177 return document_url_patterns_; 178 } 179 const URLPatternSet& target_url_patterns() const { 180 return target_url_patterns_; 181 } 182 183 // Simple mutator methods. 184 void set_title(const std::string& new_title) { title_ = new_title; } 185 void set_contexts(ContextList contexts) { contexts_ = contexts; } 186 void set_type(Type type) { type_ = type; } 187 void set_enabled(bool enabled) { enabled_ = enabled; } 188 void set_document_url_patterns(const URLPatternSet& patterns) { 189 document_url_patterns_ = patterns; 190 } 191 void set_target_url_patterns(const URLPatternSet& patterns) { 192 target_url_patterns_ = patterns; 193 } 194 195 // Returns the title with any instances of %s replaced by |selection|. The 196 // result will be no longer than |max_length|. 197 base::string16 TitleWithReplacement(const base::string16& selection, 198 size_t max_length) const; 199 200 // Sets the checked state to |checked|. Returns true if successful. 201 bool SetChecked(bool checked); 202 203 // Converts to Value for serialization to preferences. 204 scoped_ptr<base::DictionaryValue> ToValue() const; 205 206 // Returns a new MenuItem created from |value|, or NULL if there is 207 // an error. The caller takes ownership of the MenuItem. 208 static MenuItem* Populate(const std::string& extension_id, 209 const base::DictionaryValue& value, 210 std::string* error); 211 212 // Sets any document and target URL patterns from |properties|. 213 bool PopulateURLPatterns(std::vector<std::string>* document_url_patterns, 214 std::vector<std::string>* target_url_patterns, 215 std::string* error); 216 217 protected: 218 friend class MenuManager; 219 220 // Takes ownership of |item| and sets its parent_id_. 221 void AddChild(MenuItem* item); 222 223 // Takes the child item from this parent. The item is returned and the caller 224 // then owns the pointer. 225 MenuItem* ReleaseChild(const Id& child_id, bool recursive); 226 227 // Recursively appends all descendant items (children, grandchildren, etc.) 228 // to the output |list|. 229 void GetFlattenedSubtree(MenuItem::List* list); 230 231 // Recursively removes all descendant items (children, grandchildren, etc.), 232 // returning the ids of the removed items. 233 std::set<Id> RemoveAllDescendants(); 234 235 private: 236 // The unique id for this item. 237 Id id_; 238 239 // What gets shown in the menu for this item. 240 std::string title_; 241 242 Type type_; 243 244 // This should only be true for items of type CHECKBOX or RADIO. 245 bool checked_; 246 247 // If the item is enabled or not. 248 bool enabled_; 249 250 // In what contexts should the item be shown? 251 ContextList contexts_; 252 253 // If this item is a child of another item, the unique id of its parent. If 254 // this is a top-level item with no parent, this will be NULL. 255 scoped_ptr<Id> parent_id_; 256 257 // Patterns for restricting what documents this item will appear for. This 258 // applies to the frame where the click took place. 259 URLPatternSet document_url_patterns_; 260 261 // Patterns for restricting where items appear based on the src/href 262 // attribute of IMAGE/AUDIO/VIDEO/LINK tags. 263 URLPatternSet target_url_patterns_; 264 265 // Any children this item may have. 266 List children_; 267 268 DISALLOW_COPY_AND_ASSIGN(MenuItem); 269 }; 270 271 // This class keeps track of menu items added by extensions. 272 class MenuManager : public content::NotificationObserver, 273 public base::SupportsWeakPtr<MenuManager>, 274 public KeyedService, 275 public ExtensionRegistryObserver { 276 public: 277 static const char kOnContextMenus[]; 278 static const char kOnWebviewContextMenus[]; 279 280 MenuManager(content::BrowserContext* context, StateStore* store_); 281 virtual ~MenuManager(); 282 283 // Convenience function to get the MenuManager for a browser context. 284 static MenuManager* Get(content::BrowserContext* context); 285 286 // Returns the keys of extensions which have menu items registered. 287 std::set<MenuItem::ExtensionKey> ExtensionIds(); 288 289 // Returns a list of all the *top-level* menu items (added via AddContextItem) 290 // for the given extension specified by |extension_key|, *not* including child 291 // items (added via AddChildItem); although those can be reached via the 292 // top-level items' children. A view can then decide how to display these, 293 // including whether to put them into a submenu if there are more than 1. 294 const MenuItem::List* MenuItems(const MenuItem::ExtensionKey& extension_key); 295 296 // Adds a top-level menu item for an extension, requiring the |extension| 297 // pointer so it can load the icon for the extension. Takes ownership of 298 // |item|. Returns a boolean indicating success or failure. 299 bool AddContextItem(const Extension* extension, MenuItem* item); 300 301 // Add an item as a child of another item which has been previously added, and 302 // takes ownership of |item|. Returns a boolean indicating success or failure. 303 bool AddChildItem(const MenuItem::Id& parent_id, 304 MenuItem* child); 305 306 // Makes existing item with |child_id| a child of the item with |parent_id|. 307 // If the child item was already a child of another parent, this will remove 308 // it from that parent first. It is an error to try and move an item to be a 309 // child of one of its own descendants. It is legal to pass NULL for 310 // |parent_id|, which means the item should be moved to the top-level. 311 bool ChangeParent(const MenuItem::Id& child_id, 312 const MenuItem::Id* parent_id); 313 314 // Removes a context menu item with the given id (whether it is a top-level 315 // item or a child of some other item), returning true if the item was found 316 // and removed or false otherwise. 317 bool RemoveContextMenuItem(const MenuItem::Id& id); 318 319 // Removes all items for the given extension specified by |extension_key|. 320 void RemoveAllContextItems(const MenuItem::ExtensionKey& extension_key); 321 322 // Returns the item with the given |id| or NULL. 323 MenuItem* GetItemById(const MenuItem::Id& id) const; 324 325 // Notify the MenuManager that an item has been updated not through 326 // an explicit call into MenuManager. For example, if an item is 327 // acquired by a call to GetItemById and changed, then this should be called. 328 // Returns true if the item was found or false otherwise. 329 bool ItemUpdated(const MenuItem::Id& id); 330 331 // Called when a menu item is clicked on by the user. 332 void ExecuteCommand(content::BrowserContext* context, 333 content::WebContents* web_contents, 334 const content::ContextMenuParams& params, 335 const MenuItem::Id& menu_item_id); 336 337 // This returns a bitmap of width/height kFaviconSize, loaded either from an 338 // entry specified in the extension's 'icon' section of the manifest, or a 339 // default extension icon. 340 const SkBitmap& GetIconForExtension(const std::string& extension_id); 341 342 // content::NotificationObserver implementation. 343 virtual void Observe(int type, const content::NotificationSource& source, 344 const content::NotificationDetails& details) OVERRIDE; 345 346 // ExtensionRegistryObserver implementation. 347 virtual void OnExtensionLoaded(content::BrowserContext* browser_context, 348 const Extension* extension) OVERRIDE; 349 virtual void OnExtensionUnloaded( 350 content::BrowserContext* browser_context, 351 const Extension* extension, 352 UnloadedExtensionInfo::Reason reason) OVERRIDE; 353 354 // Stores the menu items for the extension in the state storage. 355 void WriteToStorage(const Extension* extension, 356 const MenuItem::ExtensionKey& extension_key); 357 358 // Reads menu items for the extension from the state storage. Any invalid 359 // items are ignored. 360 void ReadFromStorage(const std::string& extension_id, 361 scoped_ptr<base::Value> value); 362 363 // Removes all "incognito" "split" mode context items. 364 void RemoveAllIncognitoContextItems(); 365 366 private: 367 FRIEND_TEST_ALL_PREFIXES(MenuManagerTest, DeleteParent); 368 FRIEND_TEST_ALL_PREFIXES(MenuManagerTest, RemoveOneByOne); 369 370 // This is a helper function which takes care of de-selecting any other radio 371 // items in the same group (i.e. that are adjacent in the list). 372 void RadioItemSelected(MenuItem* item); 373 374 // Make sure that there is only one radio item selected at once in any run. 375 // If there are no radio items selected, then the first item in the run 376 // will get selected. If there are multiple radio items selected, then only 377 // the last one will get selcted. 378 void SanitizeRadioList(const MenuItem::List& item_list); 379 380 // Returns true if item is a descendant of an item with id |ancestor_id|. 381 bool DescendantOf(MenuItem* item, const MenuItem::Id& ancestor_id); 382 383 // We keep items organized by mapping ExtensionKey to a list of items. 384 typedef std::map<MenuItem::ExtensionKey, MenuItem::List> MenuItemMap; 385 MenuItemMap context_items_; 386 387 // This lets us make lookup by id fast. It maps id to MenuItem* for 388 // all items the menu manager knows about, including all children of top-level 389 // items. 390 std::map<MenuItem::Id, MenuItem*> items_by_id_; 391 392 content::NotificationRegistrar registrar_; 393 394 // Listen to extension load, unloaded notifications. 395 ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> 396 extension_registry_observer_; 397 398 ExtensionIconManager icon_manager_; 399 400 content::BrowserContext* browser_context_; 401 402 // Owned by ExtensionSystem. 403 StateStore* store_; 404 405 DISALLOW_COPY_AND_ASSIGN(MenuManager); 406 }; 407 408 } // namespace extensions 409 410 #endif // CHROME_BROWSER_EXTENSIONS_MENU_MANAGER_H_ 411