tab_helper.h revision e5d81f57cb97b3b6b7fccc9c5610d21eb81db09d
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_TAB_HELPER_H_
6#define CHROME_BROWSER_EXTENSIONS_TAB_HELPER_H_
7
8#include <map>
9#include <set>
10#include <string>
11#include <vector>
12
13#include "base/memory/ref_counted.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/memory/weak_ptr.h"
16#include "base/observer_list.h"
17#include "chrome/browser/extensions/active_tab_permission_granter.h"
18#include "chrome/common/web_application_info.h"
19#include "content/public/browser/notification_observer.h"
20#include "content/public/browser/notification_registrar.h"
21#include "content/public/browser/web_contents_observer.h"
22#include "content/public/browser/web_contents_user_data.h"
23#include "extensions/browser/extension_function_dispatcher.h"
24#include "extensions/common/stack_frame.h"
25#include "third_party/skia/include/core/SkBitmap.h"
26
27class FaviconDownloader;
28
29namespace content {
30struct LoadCommittedDetails;
31}
32
33namespace gfx {
34class Image;
35}
36
37namespace extensions {
38class BookmarkAppHelper;
39class Extension;
40class LocationBarController;
41class ScriptExecutor;
42class WebstoreInlineInstallerFactory;
43
44// Per-tab extension helper. Also handles non-extension apps.
45class TabHelper : public content::WebContentsObserver,
46                  public extensions::ExtensionFunctionDispatcher::Delegate,
47                  public base::SupportsWeakPtr<TabHelper>,
48                  public content::NotificationObserver,
49                  public content::WebContentsUserData<TabHelper> {
50 public:
51  // Different types of action when web app info is available.
52  // OnDidGetApplicationInfo uses this to dispatch calls.
53  enum WebAppAction {
54    NONE,              // No action at all.
55    CREATE_SHORTCUT,   // Bring up create application shortcut dialog.
56    CREATE_HOSTED_APP, // Create and install a hosted app.
57    UPDATE_SHORTCUT    // Update icon for app shortcut.
58  };
59
60  // Observer base class for classes that need to be notified when content
61  // scripts and/or tabs.executeScript calls run on a page.
62  class ScriptExecutionObserver {
63   public:
64    // Map of extensions IDs to the executing script paths.
65    typedef std::map<std::string, std::set<std::string> > ExecutingScriptsMap;
66
67    // Automatically observes and unobserves |tab_helper| on construction
68    // and destruction. |tab_helper| must outlive |this|.
69    explicit ScriptExecutionObserver(TabHelper* tab_helper);
70    ScriptExecutionObserver();
71
72    // Called when script(s) have executed on a page.
73    //
74    // |executing_scripts_map| contains all extensions that are executing
75    // scripts, mapped to the paths for those scripts. This may be an empty set
76    // if the script has no path associated with it (e.g. in the case of
77    // tabs.executeScript).
78    virtual void OnScriptsExecuted(
79        const content::WebContents* web_contents,
80        const ExecutingScriptsMap& executing_scripts_map,
81        int32 on_page_id,
82        const GURL& on_url) = 0;
83
84   protected:
85    virtual ~ScriptExecutionObserver();
86
87    TabHelper* tab_helper_;
88  };
89
90  virtual ~TabHelper();
91
92  void AddScriptExecutionObserver(ScriptExecutionObserver* observer) {
93    script_execution_observers_.AddObserver(observer);
94  }
95
96  void RemoveScriptExecutionObserver(ScriptExecutionObserver* observer) {
97    script_execution_observers_.RemoveObserver(observer);
98  }
99
100  void CreateApplicationShortcuts();
101  void CreateHostedAppFromWebContents();
102  bool CanCreateApplicationShortcuts() const;
103
104  void set_pending_web_app_action(WebAppAction action) {
105    pending_web_app_action_ = action;
106  }
107
108  // App extensions ------------------------------------------------------------
109
110  // Sets the extension denoting this as an app. If |extension| is non-null this
111  // tab becomes an app-tab. WebContents does not listen for unload events for
112  // the extension. It's up to consumers of WebContents to do that.
113  //
114  // NOTE: this should only be manipulated before the tab is added to a browser.
115  // TODO(sky): resolve if this is the right way to identify an app tab. If it
116  // is, than this should be passed in the constructor.
117  void SetExtensionApp(const Extension* extension);
118
119  // Convenience for setting the app extension by id. This does nothing if
120  // |extension_app_id| is empty, or an extension can't be found given the
121  // specified id.
122  void SetExtensionAppById(const std::string& extension_app_id);
123
124  // Set just the app icon, used by panels created by an extension.
125  void SetExtensionAppIconById(const std::string& extension_app_id);
126
127  const Extension* extension_app() const { return extension_app_; }
128  bool is_app() const { return extension_app_ != NULL; }
129  const WebApplicationInfo& web_app_info() const {
130    return web_app_info_;
131  }
132
133  // If an app extension has been explicitly set for this WebContents its icon
134  // is returned.
135  //
136  // NOTE: the returned icon is larger than 16x16 (its size is
137  // extension_misc::EXTENSION_ICON_SMALLISH).
138  SkBitmap* GetExtensionAppIcon();
139
140  content::WebContents* web_contents() const {
141    return content::WebContentsObserver::web_contents();
142  }
143
144  ScriptExecutor* script_executor() {
145    return script_executor_.get();
146  }
147
148  LocationBarController* location_bar_controller() {
149    return location_bar_controller_.get();
150  }
151
152  ActiveTabPermissionGranter* active_tab_permission_granter() {
153    return active_tab_permission_granter_.get();
154  }
155
156  // Sets a non-extension app icon associated with WebContents and fires an
157  // INVALIDATE_TYPE_TITLE navigation state change to trigger repaint of title.
158  void SetAppIcon(const SkBitmap& app_icon);
159
160  // Sets the factory used to create inline webstore item installers.
161  // Used for testing. Takes ownership of the factory instance.
162  void SetWebstoreInlineInstallerFactoryForTests(
163      WebstoreInlineInstallerFactory* factory);
164
165 private:
166  explicit TabHelper(content::WebContents* web_contents);
167  friend class content::WebContentsUserData<TabHelper>;
168
169  // Displays UI for completion of creating a bookmark hosted app.
170  void FinishCreateBookmarkApp(const extensions::Extension* extension,
171                               const WebApplicationInfo& web_app_info);
172
173  // content::WebContentsObserver overrides.
174  virtual void RenderViewCreated(
175      content::RenderViewHost* render_view_host) OVERRIDE;
176  virtual void DidNavigateMainFrame(
177      const content::LoadCommittedDetails& details,
178      const content::FrameNavigateParams& params) OVERRIDE;
179  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
180  virtual void DidCloneToNewWebContents(
181      content::WebContents* old_web_contents,
182      content::WebContents* new_web_contents) OVERRIDE;
183
184  // extensions::ExtensionFunctionDispatcher::Delegate overrides.
185  virtual extensions::WindowController* GetExtensionWindowController()
186      const OVERRIDE;
187  virtual content::WebContents* GetAssociatedWebContents() const OVERRIDE;
188
189  // Message handlers.
190  void OnDidGetApplicationInfo(int32 page_id, const WebApplicationInfo& info);
191  void OnInlineWebstoreInstall(int install_id,
192                               int return_route_id,
193                               const std::string& webstore_item_id,
194                               const GURL& requestor_url,
195                               int listeners_mask);
196  void OnGetAppInstallState(const GURL& requestor_url,
197                            int return_route_id,
198                            int callback_id);
199  void OnRequest(const ExtensionHostMsg_Request_Params& params);
200  void OnContentScriptsExecuting(
201      const ScriptExecutionObserver::ExecutingScriptsMap& extension_ids,
202      int32 page_id,
203      const GURL& on_url);
204  void OnWatchedPageChange(const std::vector<std::string>& css_selectors);
205  void OnDetailedConsoleMessageAdded(const base::string16& message,
206                                     const base::string16& source,
207                                     const StackTrace& stack_trace,
208                                     int32 severity_level);
209
210  // App extensions related methods:
211
212  // Resets app_icon_ and if |extension| is non-null uses ImageLoader to load
213  // the extension's image asynchronously.
214  void UpdateExtensionAppIcon(const Extension* extension);
215
216  const Extension* GetExtension(const std::string& extension_app_id);
217
218  void OnImageLoaded(const gfx::Image& image);
219
220  // WebstoreStandaloneInstaller::Callback.
221  virtual void OnInlineInstallComplete(int install_id,
222                                       int return_route_id,
223                                       bool success,
224                                       const std::string& error);
225
226  // content::NotificationObserver.
227  virtual void Observe(int type,
228                       const content::NotificationSource& source,
229                       const content::NotificationDetails& details) OVERRIDE;
230
231  // Requests application info for the specified page. This is an asynchronous
232  // request. The delegate is notified by way of OnDidGetApplicationInfo when
233  // the data is available.
234  void GetApplicationInfo(int32 page_id);
235
236  // Sends our tab ID to |render_view_host|.
237  void SetTabId(content::RenderViewHost* render_view_host);
238
239  // Data for app extensions ---------------------------------------------------
240
241  // Our content script observers. Declare at top so that it will outlive all
242  // other members, since they might add themselves as observers.
243  ObserverList<ScriptExecutionObserver> script_execution_observers_;
244
245  // If non-null this tab is an app tab and this is the extension the tab was
246  // created for.
247  const Extension* extension_app_;
248
249  // Icon for extension_app_ (if non-null) or a manually-set icon for
250  // non-extension apps.
251  SkBitmap extension_app_icon_;
252
253  // Process any extension messages coming from the tab.
254  extensions::ExtensionFunctionDispatcher extension_function_dispatcher_;
255
256  // Cached web app info data.
257  WebApplicationInfo web_app_info_;
258
259  // Which deferred action to perform when OnDidGetApplicationInfo is notified
260  // from a WebContents.
261  WebAppAction pending_web_app_action_;
262
263  content::NotificationRegistrar registrar_;
264
265  scoped_ptr<ScriptExecutor> script_executor_;
266
267  scoped_ptr<LocationBarController> location_bar_controller_;
268
269  scoped_ptr<ActiveTabPermissionGranter> active_tab_permission_granter_;
270
271  scoped_ptr<BookmarkAppHelper> bookmark_app_helper_;
272
273  Profile* profile_;
274
275  // Vend weak pointers that can be invalidated to stop in-progress loads.
276  base::WeakPtrFactory<TabHelper> image_loader_ptr_factory_;
277
278  // Creates WebstoreInlineInstaller instances for inline install triggers.
279  scoped_ptr<WebstoreInlineInstallerFactory> webstore_inline_installer_factory_;
280
281  DISALLOW_COPY_AND_ASSIGN(TabHelper);
282};
283
284}  // namespace extensions
285
286#endif  // CHROME_BROWSER_EXTENSIONS_TAB_HELPER_H_
287