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