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