Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(386)

Side by Side Diff: chrome/browser/extensions/extension_offscreen_tabs_module.cc

Issue 7720002: Chrome Extensions chrome.experimental.offscreenTabs.* API implementation, docs, and test. (Closed) Base URL: http://src.chromium.org/svn/trunk/src/
Patch Set: '' Created 9 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 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_offscreen_tabs_module.h"
6
7 #include <algorithm>
8 #include <vector>
9
10 #include "base/base64.h"
11 #include "base/json/json_writer.h"
12 #include "base/memory/ref_counted_memory.h"
13 #include "base/stl_util.h"
14 #include "base/string_number_conversions.h"
15 #include "base/string_util.h"
16 #include "base/values.h"
17 #include "chrome/browser/extensions/extension_event_router.h"
18 #include "chrome/browser/extensions/extension_function_dispatcher.h"
19 #include "chrome/browser/extensions/extension_host.h"
20 #include "chrome/browser/extensions/extension_message_service.h"
21 #include "chrome/browser/extensions/extension_offscreen_tabs_module_constants.h"
22 #include "chrome/browser/extensions/extension_service.h"
23 #include "chrome/browser/extensions/extension_tabs_module.h"
24 #include "chrome/browser/net/url_fixer_upper.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/ui/browser.h"
27 #include "chrome/browser/ui/browser_navigator.h"
28 #include "chrome/browser/ui/browser_window.h"
29 #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
30 #include "chrome/browser/ui/window_sizer.h"
31 #include "chrome/common/chrome_notification_types.h"
32 #include "chrome/common/extensions/extension.h"
33 #include "chrome/common/extensions/extension_error_utils.h"
34 #include "chrome/common/extensions/extension_messages.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/common/url_constants.h"
37 #include "content/browser/renderer_host/backing_store.h"
38 #include "content/browser/renderer_host/render_view_host.h"
39 #include "content/browser/renderer_host/render_view_host_delegate.h"
40 #include "content/browser/tab_contents/navigation_entry.h"
41 #include "content/browser/tab_contents/tab_contents.h"
42 #include "content/browser/tab_contents/tab_contents_view.h"
43 #include "content/common/content_client.h"
44 #include "content/common/notification_service.h"
45 #include "skia/ext/image_operations.h"
46 #include "skia/ext/platform_canvas.h"
47 #include "third_party/skia/include/core/SkBitmap.h"
48 #include "ui/gfx/codec/jpeg_codec.h"
49 #include "ui/gfx/codec/png_codec.h"
50
51 using WebKit::WebInputEvent;
52
53 namespace keys = extension_offscreen_tabs_module_constants;
54
55 namespace {
56
57 class Tab;
58
59 // Offscreen Tab ---------------------------------------------------------------
60
61 // This class is responsible for the creation and destruction of offscreen tabs,
62 // as well as dispatching an onUpdated event.
63 class OffscreenTab : public NotificationObserver {
64 public:
65 OffscreenTab();
66 virtual ~OffscreenTab();
67 void Init(const GURL& url,
68 const int width,
69 const int height,
70 Profile* profile);
71
72 TabContents* contents();
73 Tab* parent_tab() { return parent_tab_; }
74 DictionaryValue* CreateValue(); // The caller owns the returned value.
75
76 void SetURL(const GURL& url);
77 void SetSize(int width, int height);
78 void SetParentTab(Tab* tab);
79
80 private:
81 virtual void Observe(int type,
82 const NotificationSource& source,
83 const NotificationDetails& details) OVERRIDE;
84
85 NotificationRegistrar registrar_;
86
87 scoped_ptr<TabContentsWrapper> tab_; // TabContentsWrapper associated with
88 // this offscreen tab.
89 Tab* parent_tab_;
90
91 DISALLOW_COPY_AND_ASSIGN(OffscreenTab);
92 };
93
94 typedef std::vector<OffscreenTab*> TabVector;
95 typedef TabVector::iterator TabIterator;
96
97 // Tab -------------------------------------------------------------------------
98
99 // Holds info about a tab that has spawned at least one offscreen tab.
100 // Each Tab keeps track of its child offscreen tabs. The Tab is also responsible
101 // for killing its children when it navigates away or gets closed.
102 class Tab : public NotificationObserver {
103 public:
104 Tab();
105 virtual ~Tab();
106 void Init(TabContents* tab_contents, const std::string& extension_id);
107
108 TabContents* contents();
109 const TabVector& offscreen_tabs() { return offscreen_tabs_; }
110 const std::string& extension_id() const { return extension_id_; }
111
112 // Tab takes ownership of OffscreenTab.
113 void AddOffscreenTab(OffscreenTab *tab);
114 // Caller assumes ownership of OffscreenTab.
115 void RemoveOffscreenTab(OffscreenTab *tab);
116
117 private:
118 virtual void Observe(int type,
119 const NotificationSource& source,
120 const NotificationDetails& details) OVERRIDE;
121
122 NotificationRegistrar registrar_;
123
124 TabContentsWrapper* tab_; // TabContentsWrapper associated with this tab.
125 TabVector offscreen_tabs_; // Offscreen tabs spawned by this tab.
126 std::string extension_id_; // Id of the extension running in this tab.
127
128 DISALLOW_COPY_AND_ASSIGN(Tab);
129 };
130
131 // Map -------------------------------------------------------------------------
132
133 // This map keeps track of all tabs that are happy parents of offscreen tabs.
134 class Map {
135 public:
136 Map();
137 ~Map();
138
139 // Gets an offscreen tab by ID.
140 bool GetOffscreenTab(const int tab_id,
141 ExtensionFunctionDispatcher* dispatcher,
142 Profile* profile,
143 OffscreenTab** offscreen_tab,
144 std::string* error_message);
145 // Gets a parent tab by ID.
146 bool GetTab(const int tab_id,
147 Tab** tab,
148 std::string* error_message);
149 // Creates a mapping between a parent tab and an offscreen tab.
150 bool AddOffscreenTab(OffscreenTab* offscreen_tab,
151 ExtensionFunctionDispatcher* dispatcher,
152 Profile* profile,
153 const std::string& ext_id,
154 std::string* error_message);
155 // Removes the mapping between a parent tab and an offscreen tab.
156 bool RemoveOffscreenTab(const int tab_id,
157 ExtensionFunctionDispatcher* dispatcher,
158 Profile* profile,
159 std::string* error_message);
160 // Removes a parent tab from the map along with its child offscreen tabs.
161 bool RemoveTab(const int tab_id, std::string* error_message);
162
163 private:
164 typedef base::hash_map<int, Tab*> TabMap;
165 TabMap map;
166
167 DISALLOW_COPY_AND_ASSIGN(Map);
168 };
169
170 // Variables -------------------------------------------------------------------
171
172 Map* map = NULL;
173
174 // We are assuming that offscreen tabs will not be created by background pages
175 // with the exception of the API test background page. We keep track of the
176 // offscreen tabs associated with the test API background page via this variable
177 // These tab contents are created just for convenience and do not do anything.
178 // TODO(alexbost): Think about handling multiple background pages each spawning
179 // offscreen tabs. Would background pages want to spawn offscreen tabs?
180 TabContents* background_page_tab_contents = NULL;
181
182 // Util ------------------------------------------------------------------------
183
184 // Gets the map of parent tabs to offscreen tabs.
185 Map* GetMap() {
186 if (map == NULL)
187 map = new Map();
188
189 return map;
190 }
191
192 // Gets the TabContents associated with the test API background page.
193 TabContents* GetBackgroundPageTabContents(Profile* profile) {
194 if (profile && background_page_tab_contents == NULL) {
195 background_page_tab_contents =
196 new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
197 new TabContentsWrapper(background_page_tab_contents);
198 }
199
200 return background_page_tab_contents;
201 }
202
203 // Gets the contents of the tab that instantiated the extension API call.
204 // In the case of background pages we use tab contents created by us.
205 bool GetCurrentTab(ExtensionFunctionDispatcher* dispatcher,
206 Profile* profile,
207 TabContents** tab_contents,
208 std::string* error_message) {
209 *tab_contents = dispatcher->delegate()->GetAssociatedTabContents();
210
211 // Background page (no associated tab contents).
212 if (!*tab_contents)
213 *tab_contents = GetBackgroundPageTabContents(profile);
214
215 if (*tab_contents)
216 return true;
217
218 *error_message = keys::kCurrentTabNotFound;
219 return false;
220 }
221
222 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
223 // Takes |url_string| and returns a GURL which is either valid and absolute
224 // or invalid. If |url_string| is not directly interpretable as a valid (it is
225 // likely a relative URL) an attempt is made to resolve it. |extension| is
226 // provided so it can be resolved relative to its extension base
227 // (chrome-extension://<id>/). Using the source frame url would be more correct,
228 // but because the api shipped with urls resolved relative to their extension
229 // base, we decided it wasn't worth breaking existing extensions to fix.
230 GURL ResolvePossiblyRelativeURL(const std::string& url_string,
231 const Extension* extension) {
232 GURL url = GURL(url_string);
233 if (!url.is_valid())
234 url = extension->GetResourceURL(url_string);
235
236 return url;
237 }
238
239 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
240 bool IsCrashURL(const GURL& url) {
241 // Check a fixed-up URL, to normalize the scheme and parse hosts correctly.
242 GURL fixed_url =
243 URLFixerUpper::FixupURL(url.possibly_invalid_spec(), std::string());
244 return (fixed_url.SchemeIs(chrome::kChromeUIScheme) &&
245 (fixed_url.host() == chrome::kChromeUIBrowserCrashHost ||
246 fixed_url.host() == chrome::kChromeUICrashHost));
247 }
248
249 // Offscreen Tab ---------------------------------------------------------------
250
251 OffscreenTab::OffscreenTab() {}
252 OffscreenTab::~OffscreenTab() {}
253
254 void OffscreenTab::Init(const GURL& url,
255 const int width,
256 const int height,
257 Profile* profile) {
258 // Create the offscreen tab.
259 TabContents* tab_contents = new TabContents(
260 profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
261 tab_.reset(new TabContentsWrapper(tab_contents));
262
263 SetSize(width, height); // Setting the size starts the renderer.
264 SetURL(url);
265
266 // Register for tab notifications.
267 registrar_.Add(this,
268 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
269 Source<NavigationController>(&contents()->controller()));
270 }
271
272 TabContents* OffscreenTab::contents() {
273 return tab_.get()->tab_contents();
274 }
275
276 DictionaryValue* OffscreenTab::CreateValue() {
277 DictionaryValue* result = new DictionaryValue();
278
279 result->SetInteger(keys::kIdKey, ExtensionTabUtil::GetTabId(contents()));
280 result->SetString(keys::kUrlKey, contents()->GetURL().spec());
281 result->SetInteger(keys::kWidthKey,
282 TabContentsWrapper::GetCurrentWrapperForContents(contents())->
283 view()->GetContainerSize().width());
284 result->SetInteger(keys::kHeightKey,
285 TabContentsWrapper::GetCurrentWrapperForContents(contents())->
286 view()->GetContainerSize().height());
287
288 return result;
289 }
290
291 void OffscreenTab::SetURL(const GURL& url) {
292 contents()->controller().LoadURL(
293 url, GURL(), PageTransition::LINK, std::string());
294 }
295
296 void OffscreenTab::SetSize(int width, int height) {
297 contents()->view()->SizeContents(gfx::Size(width, height));
298 }
299
300 void OffscreenTab::SetParentTab(Tab* tab) {
301 parent_tab_ = tab;
302 }
303
304 void OffscreenTab::Observe(int type,
305 const NotificationSource& source,
306 const NotificationDetails& details) {
307 CHECK_EQ(content::NOTIFICATION_NAV_ENTRY_COMMITTED, type);
308
309 DictionaryValue* changed_properties = new DictionaryValue();
310 changed_properties->SetString(keys::kUrlKey, contents()->GetURL().spec());
311
312 ListValue args;
313 args.Append(
314 Value::CreateIntegerValue(ExtensionTabUtil::GetTabId(contents())));
315 args.Append(changed_properties);
316 args.Append(CreateValue());
317 std::string json_args;
318 base::JSONWriter::Write(&args, false, &json_args);
319
320 ListValue event_args;
321 event_args.Set(0, Value::CreateStringValue(keys::kEventOnUpdated));
322 event_args.Set(1, Value::CreateStringValue(json_args));
323
324 // Dispatch an onUpdated event.
325 // The primary use case for broadcasting the event is
326 // when the offscreen tab is generated by a test API background page.
327 if (parent_tab_->contents() == GetBackgroundPageTabContents(NULL)) {
328 Profile* profile = TabContentsWrapper::GetCurrentWrapperForContents(
329 parent_tab_->contents())->profile();
330 profile->GetExtensionEventRouter()->DispatchEventToRenderers(
331 keys::kEventOnUpdated, json_args, profile, GURL());
332 } else {
333 // Send a routed event directly to the parent tab.
334 parent_tab_->contents()->render_view_host()->process()->Send(
335 new ExtensionMsg_MessageInvoke(
336 parent_tab_->contents()->render_view_host()->routing_id(),
337 parent_tab_->extension_id(),
338 keys::kDispatchEvent,
339 event_args,
340 GURL()));
341 }
342 }
343
344 // Tab -------------------------------------------------------------------------
345
346 Tab::Tab() {
347 tab_ = NULL;
348 }
349
350 Tab::~Tab() {
351 // Kill child offscreen tabs.
352 STLDeleteElements(&offscreen_tabs_);
353
354 bool removed = GetMap()->RemoveTab(
355 ExtensionTabUtil::GetTabId(contents()), new std::string());
356 CHECK(removed);
357 }
358
359 void Tab::Init(TabContents* tab_contents, const std::string& extension_id) {
360 tab_ = TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
361 extension_id_ = extension_id;
362
363 // Register for tab notifications.
364 registrar_.Add(this,
365 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
366 Source<NavigationController>(&contents()->controller()));
367
368 registrar_.Add(this,
369 content::NOTIFICATION_TAB_CONTENTS_DESTROYED,
370 Source<TabContents>(contents()));
371 }
372
373 TabContents* Tab::contents() {
374 return tab_->tab_contents();
375 }
376
377 void Tab::AddOffscreenTab(OffscreenTab *tab) {
378 offscreen_tabs_.push_back(tab);
379 }
380
381 void Tab::RemoveOffscreenTab(OffscreenTab *tab) {
382 TabIterator it_tab = std::find(
383 offscreen_tabs_.begin(), offscreen_tabs_.end(), tab);
384 offscreen_tabs_.erase(it_tab);
385 }
386
387 void Tab::Observe(int type,
388 const NotificationSource& source,
389 const NotificationDetails& details) {
390 CHECK(type == content::NOTIFICATION_NAV_ENTRY_COMMITTED ||
391 type == content::NOTIFICATION_TAB_CONTENTS_DESTROYED);
392
393 delete this;
394 }
395
396 // Map -------------------------------------------------------------------------
397
398 Map::Map() {}
399 Map::~Map() {}
400
401 bool Map::GetOffscreenTab(const int tab_id,
402 ExtensionFunctionDispatcher* dispatcher,
403 Profile* profile,
404 OffscreenTab** offscreen_tab,
405 std::string* error_message) {
406 // Ensure that the current tab is the parent of the offscreen tab.
407 TabContents* tab_contents = NULL;
408 if (!GetCurrentTab(dispatcher, profile, &tab_contents, error_message))
409 return false;
410
411 Tab* tab = NULL;
412 if (!GetTab(ExtensionTabUtil::GetTabId(tab_contents), &tab, error_message))
413 return false;
414 TabVector offscreen_tabs = tab->offscreen_tabs();
415
416 for (TabIterator it = offscreen_tabs.begin();
417 it != offscreen_tabs.end(); ++it) {
418 if (ExtensionTabUtil::GetTabId((*it)->contents()) == tab_id) {
419 *offscreen_tab = *it;
420 return true;
421 }
422 }
423
424 *error_message = ExtensionErrorUtils::FormatErrorMessage(
425 keys::kOffscreenTabNotFoundError, base::IntToString(tab_id));
426 return false;
427 }
428
429 bool Map::GetTab(const int tab_id, Tab** tab, std::string* error_message) {
430 TabMap::iterator it = map.find(tab_id);
431
432 if (it == map.end()) {
433 *error_message = ExtensionErrorUtils::FormatErrorMessage(
434 keys::kTabNotFoundError, base::IntToString(tab_id));
435 return false;
436 }
437
438 *tab = it->second;
439
440 return true;
441 }
442
443 bool Map::AddOffscreenTab(OffscreenTab* offscreen_tab,
444 ExtensionFunctionDispatcher* dispatcher,
445 Profile* profile,
446 const std::string& ext_id,
447 std::string* error_message) {
448 // Get parent tab.
449 TabContents* tab_contents = NULL;
450 if (!GetCurrentTab(dispatcher, profile, &tab_contents, error_message))
451 return false;
452 int tab_id = ExtensionTabUtil::GetTabId(tab_contents);
453
454 Tab* tab = NULL;
455 if (!GetTab(tab_id, &tab, error_message)) {
456 tab = map[tab_id] = new Tab();
457 tab->Init(tab_contents, ext_id);
458 }
459
460 // Add child to parent.
461 tab->AddOffscreenTab(offscreen_tab);
462 // Add parent to child.
463 offscreen_tab->SetParentTab(tab);
464
465 return true;
466 }
467
468 bool Map::RemoveOffscreenTab(const int tab_id,
469 ExtensionFunctionDispatcher* dispatcher,
470 Profile* profile,
471 std::string* error_message) {
472 OffscreenTab* offscreen_tab = NULL;
473 if (!GetOffscreenTab(tab_id, dispatcher, profile,
474 &offscreen_tab, error_message))
475 return false;
476
477 Tab* tab = offscreen_tab->parent_tab();
478
479 tab->RemoveOffscreenTab(offscreen_tab);
480
481 // If this was the last offscreen tab for the parent tab, remove the parent.
482 if (tab->offscreen_tabs().empty())
483 map.erase(ExtensionTabUtil::GetTabId(tab->contents()));
484
485 return true;
486 }
487
488 bool Map::RemoveTab(const int tab_id, std::string* error_message) {
489 if (map.find(tab_id) == map.end()) {
490 *error_message = ExtensionErrorUtils::FormatErrorMessage(
491 keys::kTabNotFoundError, base::IntToString(tab_id));
492 return false;
493 }
494
495 map.erase(tab_id);
496
497 return true;
498 }
499
500 } // namespace
501
502 // API functions ---------------------------------------------------------------
503
504 // create ----------------------------------------------------------------------
505
506 CreateOffscreenTabFunction::CreateOffscreenTabFunction() {}
507 CreateOffscreenTabFunction::~CreateOffscreenTabFunction() {}
508
509 bool CreateOffscreenTabFunction::RunImpl() {
510 DictionaryValue* create_props;
511 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &create_props));
512
513 std::string url_string;
514 GURL url;
515 EXTENSION_FUNCTION_VALIDATE(
516 create_props->GetString(keys::kUrlKey, &url_string));
517 url = ResolvePossiblyRelativeURL(url_string, GetExtension());
518 if (!url.is_valid()) {
519 error_ = ExtensionErrorUtils::FormatErrorMessage(
520 keys::kInvalidUrlError, url_string);
521 return false;
522 }
523 if (IsCrashURL(url)) {
524 error_ = keys::kNoCrashBrowserError;
525 return false;
526 }
527
528 gfx::Rect window_bounds;
529 bool maximized;
530 if (!create_props->HasKey(keys::kWidthKey) ||
531 !create_props->HasKey(keys::kHeightKey)) {
532 Browser* browser = GetCurrentBrowser();
533 if (!browser) {
534 error_ = keys::kNoCurrentWindowError;
535 return false;
536 }
537
538 WindowSizer::GetBrowserWindowBounds(std::string(), gfx::Rect(),
539 browser, &window_bounds,
540 &maximized);
541 }
542
543 int width = window_bounds.width();
544 if (create_props->HasKey(keys::kWidthKey))
545 EXTENSION_FUNCTION_VALIDATE(
546 create_props->GetInteger(keys::kWidthKey, &width));
547
548 int height = window_bounds.height();
549 if (create_props->HasKey(keys::kHeightKey))
550 EXTENSION_FUNCTION_VALIDATE(
551 create_props->GetInteger(keys::kHeightKey, &height));
552
553 OffscreenTab* tab = new OffscreenTab();
554 tab->Init(url, width, height, profile_);
555
556 // Add the offscreen tab to the map so we don't lose track of it.
557 if (!GetMap()->AddOffscreenTab(tab, dispatcher(), profile_,
558 extension_id(), &error_)) {
559 delete tab; // Prevent leaking of offscreen tab.
560 return false;
561 }
562
563 if (has_callback()) {
564 result_.reset(tab->CreateValue());
565 SendResponse(true);
566 }
567
568 return true;
569 }
570
571 // get -------------------------------------------------------------------------
572
573 GetOffscreenTabFunction::GetOffscreenTabFunction() {}
574 GetOffscreenTabFunction::~GetOffscreenTabFunction() {}
575
576 bool GetOffscreenTabFunction::RunImpl() {
577 int tab_id;
578 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
579
580 OffscreenTab* tab = NULL;
581 if (!GetMap()->
582 GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_)) {
583 error_ = ExtensionErrorUtils::FormatErrorMessage(
584 keys::kOffscreenTabNotFoundError, base::IntToString(tab_id));
585 return false;
586 }
587
588 result_.reset(tab->CreateValue());
589 SendResponse(true);
590
591 return true;
592 }
593
594 // getAll ----------------------------------------------------------------------
595
596 GetAllOffscreenTabFunction::GetAllOffscreenTabFunction() {}
597 GetAllOffscreenTabFunction::~GetAllOffscreenTabFunction() {}
598
599 bool GetAllOffscreenTabFunction::RunImpl() {
600 TabContents* tab_contents = NULL;
601 if (!GetCurrentTab(dispatcher(), profile_, &tab_contents, &error_))
602 return false;
603
604 Tab* tab = NULL;
605 if (!GetMap()->
606 GetTab(ExtensionTabUtil::GetTabId(tab_contents), &tab, &error_))
607 return false;
608
609 TabVector offscreen_tabs = tab->offscreen_tabs();
610
611 ListValue* tab_list = new ListValue();
612 for (TabIterator it_tab = offscreen_tabs.begin();
613 it_tab != offscreen_tabs.end(); ++it_tab)
614 tab_list->Append((*it_tab)->CreateValue());
615
616 result_.reset(tab_list);
617 SendResponse(true);
618
619 return true;
620 }
621
622 // remove ----------------------------------------------------------------------
623
624 RemoveOffscreenTabFunction::RemoveOffscreenTabFunction() {}
625 RemoveOffscreenTabFunction::~RemoveOffscreenTabFunction() {}
626
627 bool RemoveOffscreenTabFunction::RunImpl() {
628 int tab_id;
629 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
630
631 OffscreenTab* tab = NULL;
632 if (!GetMap()->GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_))
633 return false;
634
635 if (!GetMap()->RemoveOffscreenTab(tab_id, dispatcher(), profile_, &error_))
636 return false;
637
638 delete tab;
639
640 return true;
641 }
642
643 // sendKeyboardEvent -----------------------------------------------------------
644
645 SendKeyboardEventOffscreenTabFunction::
646 SendKeyboardEventOffscreenTabFunction() {}
647 SendKeyboardEventOffscreenTabFunction::
648 ~SendKeyboardEventOffscreenTabFunction() {}
649
650 bool SendKeyboardEventOffscreenTabFunction::RunImpl() {
651 int tab_id;
652 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
653
654 OffscreenTab* tab = NULL;
655 if (!GetMap()->GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_))
656 return false;
657
658 // JavaScript KeyboardEvent.
659 DictionaryValue* js_keyboard_event = NULL;
660 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &js_keyboard_event));
661
662 NativeWebKeyboardEvent keyboard_event;
663
664 std::string type;
665 if (js_keyboard_event->HasKey(keys::kKeyboardEventTypeKey)) {
666 EXTENSION_FUNCTION_VALIDATE(
667 js_keyboard_event->GetString(keys::kKeyboardEventTypeKey, &type));
668 } else {
669 error_ = keys::kInvalidKeyboardEventObjectError;
670 return false;
671 }
672
673 if (type.compare(keys::kKeyboardEventTypeValueKeypress) == 0) {
674 keyboard_event.type = WebInputEvent::Char;
675 } else if (type.compare(keys::kKeyboardEventTypeValueKeydown) == 0) {
676 keyboard_event.type = WebInputEvent::KeyDown;
677 } else if (type.compare(keys::kKeyboardEventTypeValueKeyup) == 0) {
678 keyboard_event.type = WebInputEvent::KeyUp;
679 } else {
680 error_ = keys::kInvalidKeyboardEventObjectError;
681 return false;
682 }
683
684 int key_code;
685 if (js_keyboard_event->HasKey(keys::kKeyboardEventKeyCodeKey)) {
686 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
687 GetInteger(keys::kKeyboardEventKeyCodeKey, &key_code));
688 } else {
689 error_ = keys::kInvalidKeyboardEventObjectError;
690 return false;
691 }
692
693 keyboard_event.nativeKeyCode = key_code;
694 keyboard_event.windowsKeyCode = key_code;
695 keyboard_event.setKeyIdentifierFromWindowsKeyCode();
696
697 // Keypress = type character
698 if (type.compare(keys::kKeyboardEventTypeValueKeypress) == 0) {
699 int char_code;
700 if (js_keyboard_event->HasKey(keys::kKeyboardEventCharCodeKey)) {
701 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
702 GetInteger(keys::kKeyboardEventCharCodeKey, &char_code));
703 keyboard_event.text[0] = char_code;
704 keyboard_event.unmodifiedText[0] = char_code;
705 } else {
706 error_ = keys::kInvalidKeyboardEventObjectError;
707 return false;
708 }
709 }
710
711 bool alt_key;
712 if (js_keyboard_event->HasKey(keys::kKeyboardEventAltKeyKey))
713 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
714 GetBoolean(keys::kKeyboardEventAltKeyKey, &alt_key));
715 if (alt_key)
716 keyboard_event.modifiers |= WebInputEvent::AltKey;
717
718 bool ctrl_key;
719 if (js_keyboard_event->HasKey(keys::kKeyboardEventCtrlKeyKey))
720 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
721 GetBoolean(keys::kKeyboardEventCtrlKeyKey, &ctrl_key));
722 if (ctrl_key)
723 keyboard_event.modifiers |= WebInputEvent::ControlKey;
724
725 bool meta_key = false;
726 if (js_keyboard_event->HasKey(keys::kMouseEventMetaKeyKey))
727 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
728 GetBoolean(keys::kMouseEventMetaKeyKey, &meta_key));
729 if (meta_key)
730 keyboard_event.modifiers |= WebInputEvent::MetaKey;
731
732 bool shift_key;
733 if (js_keyboard_event->HasKey(keys::kKeyboardEventShiftKeyKey))
734 EXTENSION_FUNCTION_VALIDATE(js_keyboard_event->
735 GetBoolean(keys::kKeyboardEventShiftKeyKey, &shift_key));
736 if (shift_key)
737 keyboard_event.modifiers |= WebInputEvent::ShiftKey;
738
739 // Forward the event.
740 tab->contents()->render_view_host()->
741 ForwardKeyboardEvent(keyboard_event);
742
743 if (has_callback()) {
744 result_.reset(tab->CreateValue());
745 SendResponse(true);
746 }
747
748 return true;
749 }
750
751 // sendMouseEvent --------------------------------------------------------------
752
753 SendMouseEventOffscreenTabFunction::SendMouseEventOffscreenTabFunction() {}
754 SendMouseEventOffscreenTabFunction::~SendMouseEventOffscreenTabFunction() {}
755
756 bool SendMouseEventOffscreenTabFunction::RunImpl() {
757 int tab_id;
758 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
759
760 OffscreenTab* tab = NULL;
761 if (!GetMap()->GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_))
762 return false;
763
764 // JavaScript MouseEvent.
765 DictionaryValue* js_mouse_event = NULL;
766 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &js_mouse_event));
767
768 std::string type;
769 if (js_mouse_event->HasKey(keys::kMouseEventTypeKey)) {
770 EXTENSION_FUNCTION_VALIDATE(
771 js_mouse_event->GetString(keys::kMouseEventTypeKey, &type));
772 } else {
773 error_ = keys::kInvalidMouseEventObjectError;
774 return false;
775 }
776
777 if (type.compare(keys::kMouseEventTypeValueMousewheel) == 0) {
778 WebKit::WebMouseWheelEvent wheel_event;
779
780 wheel_event.type = WebInputEvent::MouseWheel;
781
782 if (js_mouse_event->HasKey(keys::kMouseEventWheelDeltaXKey) &&
783 js_mouse_event->HasKey(keys::kMouseEventWheelDeltaYKey)) {
784 int delta_x, delta_y;
785 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
786 GetInteger(keys::kMouseEventWheelDeltaXKey, &delta_x));
787 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
788 GetInteger(keys::kMouseEventWheelDeltaYKey, &delta_y));
789 wheel_event.deltaX = delta_x;
790 wheel_event.deltaY = delta_y;
791 } else {
792 error_ = keys::kInvalidMouseEventObjectError;
793 return false;
794 }
795
796 // Forward the event.
797 tab->contents()->render_view_host()->ForwardWheelEvent(wheel_event);
798 } else {
799 WebKit::WebMouseEvent mouse_event;
800
801 if (type.compare(keys::kMouseEventTypeValueMousedown) == 0 ||
802 type.compare(keys::kMouseEventTypeValueClick) == 0) {
803 mouse_event.type = WebKit::WebInputEvent::MouseDown;
804 } else if (type.compare(keys::kMouseEventTypeValueMouseup) == 0) {
805 mouse_event.type = WebKit::WebInputEvent::MouseUp;
806 } else if (type.compare(keys::kMouseEventTypeValueMousemove) == 0) {
807 mouse_event.type = WebKit::WebInputEvent::MouseMove;
808 } else {
809 error_ = keys::kInvalidMouseEventObjectError;
810 return false;
811 }
812
813 int button;
814 if (js_mouse_event->HasKey(keys::kMouseEventButtonKey)) {
815 EXTENSION_FUNCTION_VALIDATE(
816 js_mouse_event->GetInteger(keys::kMouseEventButtonKey, &button));
817 } else {
818 error_ = keys::kInvalidMouseEventObjectError;
819 return false;
820 }
821
822 if (button == keys::kMouseEventButtonValueLeft) {
823 mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
824 } else if (button == keys::kMouseEventButtonValueMiddle) {
825 mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;
826 } else if (button == keys::kMouseEventButtonValueRight) {
827 mouse_event.button = WebKit::WebMouseEvent::ButtonRight;
828 } else {
829 error_ = keys::kInvalidMouseEventObjectError;
830 return false;
831 }
832
833 if (HasOptionalArgument(2) && HasOptionalArgument(3)) {
834 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(2, &mouse_event.x));
835 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(3, &mouse_event.y));
836 } else {
837 error_ = keys::kNoMouseCoordinatesError;
838 return false;
839 }
840
841 bool alt_key = false;
842 if (js_mouse_event->HasKey(keys::kMouseEventAltKeyKey))
843 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
844 GetBoolean(keys::kMouseEventAltKeyKey, &alt_key));
845 if (alt_key)
846 mouse_event.modifiers |= WebInputEvent::AltKey;
847
848 bool ctrl_key = false;
849 if (js_mouse_event->HasKey(keys::kMouseEventCtrlKeyKey))
850 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
851 GetBoolean(keys::kMouseEventCtrlKeyKey, &ctrl_key));
852 if (ctrl_key)
853 mouse_event.modifiers |= WebInputEvent::ControlKey;
854
855 bool meta_key = false;
856 if (js_mouse_event->HasKey(keys::kMouseEventMetaKeyKey))
857 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
858 GetBoolean(keys::kMouseEventMetaKeyKey, &meta_key));
859 if (meta_key)
860 mouse_event.modifiers |= WebInputEvent::MetaKey;
861
862 bool shift_key = false;
863 if (js_mouse_event->HasKey(keys::kMouseEventShiftKeyKey))
864 EXTENSION_FUNCTION_VALIDATE(js_mouse_event->
865 GetBoolean(keys::kMouseEventShiftKeyKey, &shift_key));
866 if (shift_key)
867 mouse_event.modifiers |= WebInputEvent::ShiftKey;
868
869 mouse_event.clickCount = 1;
870
871 // Forward the event.
872 tab->contents()->render_view_host()->ForwardMouseEvent(mouse_event);
873
874 // If the event is a click,
875 // fire a mouseup event in addition to the mousedown.
876 if (type.compare(keys::kMouseEventTypeValueClick) == 0) {
877 mouse_event.type = WebKit::WebInputEvent::MouseUp;
878 tab->contents()->render_view_host()->ForwardMouseEvent(mouse_event);
879 }
880 }
881
882 if (has_callback()) {
883 result_.reset(tab->CreateValue());
884 SendResponse(true);
885 }
886
887 return true;
888 }
889
890 // toDataUrl -------------------------------------------------------------------
891
892 ToDataUrlOffscreenTabFunction::ToDataUrlOffscreenTabFunction() {}
893 ToDataUrlOffscreenTabFunction::~ToDataUrlOffscreenTabFunction() {}
894
895 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
896 // TODO(alexbost): We want to optimize this function in order to get more image
897 // updates on the browser side. One improvement would be to implement another
898 // hash map in order to get offscreen tabs in O(1).
899 bool ToDataUrlOffscreenTabFunction::RunImpl() {
900 int tab_id;
901 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
902
903 OffscreenTab* tab = NULL;
904 if (!GetMap()->GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_))
905 return false;
906
907 image_format_ = FORMAT_JPEG; // Default format is JPEG.
908 image_quality_ = kDefaultQuality; // Default quality setting.
909
910 if (HasOptionalArgument(1)) {
911 DictionaryValue* options;
912 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options));
913
914 if (options->HasKey(keys::kFormatKey)) {
915 std::string format;
916 EXTENSION_FUNCTION_VALIDATE(
917 options->GetString(keys::kFormatKey, &format));
918
919 if (format == keys::kFormatValueJpeg) {
920 image_format_ = FORMAT_JPEG;
921 } else if (format == keys::kFormatValuePng) {
922 image_format_ = FORMAT_PNG;
923 } else {
924 // Schema validation should make this unreachable.
925 EXTENSION_FUNCTION_VALIDATE(0);
926 }
927 }
928
929 if (options->HasKey(keys::kQualityKey)) {
930 EXTENSION_FUNCTION_VALIDATE(
931 options->GetInteger(keys::kQualityKey, &image_quality_));
932 }
933 }
934
935 // captureVisibleTab() can return an image containing sensitive information
936 // that the browser would otherwise protect. Ensure the extension has
937 // permission to do this.
938 if (!GetExtension()->
939 CanCaptureVisiblePage(tab->contents()->GetURL(), &error_))
940 return false;
941
942 // The backing store approach works on Linux but not on Mac.
943 // TODO(alexbost): Test on Windows
944 #if !defined(OS_MACOSX)
945 RenderViewHost* render_view_host = tab->contents()->render_view_host();
946
947 // If a backing store is cached for the tab we want to capture,
948 // and it can be copied into a bitmap, then use it to generate the image.
949 BackingStore* backing_store = render_view_host->GetBackingStore(false);
950 if (backing_store && CaptureSnapshotFromBackingStore(backing_store))
951 return true;
952 #endif
953
954 // Ask the renderer for a snapshot of the tab.
955 TabContentsWrapper* tab_wrapper =
956 TabContentsWrapper::GetCurrentWrapperForContents(tab->contents());
957 tab_wrapper->CaptureSnapshot();
958 registrar_.Add(this,
959 chrome::NOTIFICATION_TAB_SNAPSHOT_TAKEN,
960 Source<TabContentsWrapper>(tab_wrapper));
961
962 AddRef(); // Balanced in ToDataUrlOffscreenTabFunction::Observe().
963
964 return true;
965 }
966
967 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
968 // Build the image of a tab's contents out of a backing store.
969 // This may fail if we can not copy a backing store into a bitmap.
970 // For example, some uncommon X11 visual modes are not supported by
971 // CopyFromBackingStore().
972 bool ToDataUrlOffscreenTabFunction::CaptureSnapshotFromBackingStore(
973 BackingStore* backing_store) {
974
975 skia::PlatformCanvas temp_canvas;
976 if (!backing_store->CopyFromBackingStore(gfx::Rect(backing_store->size()),
977 &temp_canvas)) {
978 return false;
979 }
980 VLOG(1) << "captureVisibleTab() got image from backing store.";
981
982 SendResultFromBitmap(
983 skia::GetTopDevice(temp_canvas)->accessBitmap(false));
984 return true;
985 }
986
987 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
988 void ToDataUrlOffscreenTabFunction::Observe(int type,
989 const NotificationSource& source,
990 const NotificationDetails& details) {
991 CHECK(type == chrome::NOTIFICATION_TAB_SNAPSHOT_TAKEN);
992
993 const SkBitmap *screen_capture = Details<const SkBitmap>(details).ptr();
994 const bool error = screen_capture->empty();
995
996 if (error) {
997 error_ = keys::kInternalVisibleTabCaptureError;
998 SendResponse(false);
999 } else {
1000 VLOG(1) << "Got image from renderer.";
1001 SendResultFromBitmap(*screen_capture);
1002 }
1003
1004 Release(); // Balanced in ToDataUrlOffscreenTabFunction::RunImpl().
1005 }
1006
1007 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1008 // Turn a bitmap of the screen into an image, set that image as the result,
1009 // and call SendResponse().
1010 void ToDataUrlOffscreenTabFunction::SendResultFromBitmap(
1011 const SkBitmap& screen_capture) {
1012 std::vector<unsigned char> data;
1013 SkAutoLockPixels screen_capture_lock(screen_capture);
1014 bool encoded = false;
1015 std::string mime_type;
1016 switch (image_format_) {
1017 case FORMAT_JPEG:
1018 encoded = gfx::JPEGCodec::Encode(
1019 reinterpret_cast<unsigned char*>(screen_capture.getAddr32(0, 0)),
1020 gfx::JPEGCodec::FORMAT_SkBitmap,
1021 screen_capture.width(),
1022 screen_capture.height(),
1023 static_cast<int>(screen_capture.rowBytes()),
1024 image_quality_,
1025 &data);
1026 mime_type = keys::kMimeTypeJpeg;
1027 break;
1028 case FORMAT_PNG:
1029 encoded = gfx::PNGCodec::EncodeBGRASkBitmap(
1030 screen_capture,
1031 true, // Discard transparency.
1032 &data);
1033 mime_type = keys::kMimeTypePng;
1034 break;
1035 default:
1036 NOTREACHED() << "Invalid image format.";
1037 }
1038
1039 if (!encoded) {
1040 error_ = keys::kInternalVisibleTabCaptureError;
1041 SendResponse(false);
1042 return;
1043 }
1044
1045 std::string base64_result;
1046 base::StringPiece stream_as_string(
1047 reinterpret_cast<const char*>(vector_as_array(&data)), data.size());
1048
1049 base::Base64Encode(stream_as_string, &base64_result);
1050 base64_result.insert(0, base::StringPrintf("data:%s;base64,",
1051 mime_type.c_str()));
1052 result_.reset(new StringValue(base64_result));
1053 SendResponse(true);
1054 }
1055
1056 // update ----------------------------------------------------------------------
1057
1058 UpdateOffscreenTabFunction::UpdateOffscreenTabFunction() {}
1059 UpdateOffscreenTabFunction::~UpdateOffscreenTabFunction() {}
1060
1061 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1062 bool UpdateOffscreenTabFunction::RunImpl() {
1063 int tab_id;
1064 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
1065
1066 OffscreenTab* tab = NULL;
1067 if (!GetMap()->GetOffscreenTab(tab_id, dispatcher(), profile_, &tab, &error_))
1068 return false;
1069
1070 DictionaryValue* update_props;
1071 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &update_props));
1072
1073 // Url
1074 if (update_props->HasKey(keys::kUrlKey)) {
1075 std::string url_string;
1076 GURL url;
1077 EXTENSION_FUNCTION_VALIDATE(
1078 update_props->GetString(keys::kUrlKey, &url_string));
1079 url = ResolvePossiblyRelativeURL(url_string, GetExtension());
1080 if (!url.is_valid()) {
1081 error_ = ExtensionErrorUtils::FormatErrorMessage(
1082 keys::kInvalidUrlError, url_string);
1083 return false;
1084 }
1085 if (IsCrashURL(url)) {
1086 error_ = keys::kNoCrashBrowserError;
1087 return false;
1088 }
1089
1090 // JavaScript URLs can do the same kinds of things as cross-origin XHR, so
1091 // we need to check host permissions before allowing them.
1092 if (url.SchemeIs(chrome::kJavaScriptScheme)) {
1093 if (!GetExtension()->CanExecuteScriptOnPage(
1094 tab->contents()->GetURL(), NULL, &error_)) {
1095 return false;
1096 }
1097
1098 ExtensionMsg_ExecuteCode_Params params;
1099 params.request_id = request_id();
1100 params.extension_id = extension_id();
1101 params.is_javascript = true;
1102 params.code = url.path();
1103 params.all_frames = false;
1104 params.in_main_world = true;
1105
1106 RenderViewHost* render_view_host =
1107 tab->contents()->render_view_host();
1108 render_view_host->Send(
1109 new ExtensionMsg_ExecuteCode(render_view_host->routing_id(),
1110 params));
1111
1112 Observe(tab->contents());
1113 AddRef(); // balanced in Observe()
1114
1115 return true;
1116 }
1117
1118 tab->SetURL(url);
1119
1120 // The URL of a tab contents never actually changes to a JavaScript URL, so
1121 // this check only makes sense in other cases.
1122 if (!url.SchemeIs(chrome::kJavaScriptScheme))
1123 CHECK_EQ(url.spec(), tab->contents()->GetURL().spec());
1124 }
1125
1126 // Width and height
1127 if (update_props->HasKey(keys::kWidthKey) ||
1128 update_props->HasKey(keys::kHeightKey)) {
1129 int width;
1130 if (update_props->HasKey(keys::kWidthKey))
1131 EXTENSION_FUNCTION_VALIDATE(
1132 update_props->GetInteger(keys::kWidthKey, &width));
1133 else
1134 TabContentsWrapper::GetCurrentWrapperForContents(
1135 tab->contents())->view()->GetContainerSize().width();
1136
1137 int height;
1138 if (update_props->HasKey(keys::kHeightKey))
1139 EXTENSION_FUNCTION_VALIDATE(
1140 update_props->GetInteger(keys::kHeightKey, &height));
1141 else
1142 TabContentsWrapper::GetCurrentWrapperForContents(
1143 tab->contents())->view()->GetContainerSize().height();
1144
1145 tab->SetSize(width, height);
1146 }
1147
1148 // Callback
1149 if (has_callback()) {
1150 result_.reset(tab->CreateValue());
1151 SendResponse(true);
1152 }
1153
1154 return true;
1155 }
1156
1157 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1158 bool UpdateOffscreenTabFunction::OnMessageReceived(
1159 const IPC::Message& message) {
1160 if (message.type() != ExtensionHostMsg_ExecuteCodeFinished::ID)
1161 return false;
1162
1163 int message_request_id;
1164 void* iter = NULL;
1165 if (!message.ReadInt(&iter, &message_request_id)) {
1166 NOTREACHED() << "malformed extension message";
1167 return true;
1168 }
1169
1170 if (message_request_id != request_id())
1171 return false;
1172
1173 IPC_BEGIN_MESSAGE_MAP(UpdateOffscreenTabFunction, message)
1174 IPC_MESSAGE_HANDLER(ExtensionHostMsg_ExecuteCodeFinished,
1175 OnExecuteCodeFinished)
1176 IPC_END_MESSAGE_MAP()
1177 return true;
1178 }
1179
1180 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1181 void UpdateOffscreenTabFunction::
1182 OnExecuteCodeFinished(int request_id,
1183 bool success,
1184 const std::string& error) {
1185 if (!error.empty()) {
1186 CHECK(!success);
1187 error_ = error;
1188 }
1189
1190 SendResponse(success);
1191
1192 Observe(NULL);
1193 Release(); // balanced in Execute()
1194 }
1195
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698