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

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, 4 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 <hash_map>
9 #include <vector>
10
11 #include "base/base64.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/stringprintf.h"
17 #include "base/utf_string_conversions.h"
18 #include "chrome/browser/extensions/extension_function_dispatcher.h"
19 #include "chrome/browser/extensions/extension_host.h"
20 #include "chrome/browser/extensions/extension_offscreen_tabs_module_constants.h"
21 #include "chrome/browser/extensions/extension_service.h"
22 #include "chrome/browser/extensions/extension_tabs_module.h"
23 #include "chrome/browser/net/url_fixer_upper.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/sessions/restore_tab_helper.h"
26 #include "chrome/browser/tabs/tab_strip_model.h"
27 #include "chrome/browser/translate/translate_tab_helper.h"
28 #include "chrome/browser/ui/browser.h"
29 #include "chrome/browser/ui/browser_list.h"
30 #include "chrome/browser/ui/browser_navigator.h"
31 #include "chrome/browser/ui/browser_window.h"
32 #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
33 #include "chrome/browser/ui/window_sizer.h"
34 #include "chrome/common/chrome_notification_types.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/extensions/extension.h"
37 #include "chrome/common/extensions/extension_error_utils.h"
38 #include "chrome/common/extensions/extension_messages.h"
39 #include "chrome/common/pref_names.h"
40 #include "chrome/common/url_constants.h"
41 #include "content/browser/renderer_host/backing_store.h"
42 #include "content/browser/renderer_host/render_view_host.h"
43 #include "content/browser/renderer_host/render_view_host_delegate.h"
44 #include "content/browser/tab_contents/navigation_entry.h"
45 #include "content/browser/tab_contents/tab_contents.h"
46 #include "content/browser/tab_contents/tab_contents_view.h"
47 #include "content/common/notification_service.h"
48 #include "skia/ext/image_operations.h"
49 #include "skia/ext/platform_canvas.h"
50 #include "third_party/skia/include/core/SkBitmap.h"
51 #include "ui/gfx/codec/jpeg_codec.h"
52 #include "ui/gfx/codec/png_codec.h"
53
54 using WebKit::WebInputEvent;
55
56 namespace keys = extension_offscreen_tabs_module_constants;
57
58 const int ToDataUrlOffscreenTabFunction::kDefaultQuality = 90;
59
60 namespace {
61
62 typedef base::hash_map<int, std::vector<TabContents*> > OffscreenTabsMap;
63 OffscreenTabsMap* tabs_map = NULL;
64
65 OffscreenTabsEventManager* event_manager = NULL;
66
67 OffscreenTabsMap* GetOffscreenTabsMap() {
68 if (tabs_map == NULL)
69 tabs_map = new OffscreenTabsMap();
70
71 return tabs_map;
72 }
73
74 OffscreenTabsEventManager* GetOffscreenTabsEventManager() {
75 if (event_manager == NULL)
76 event_manager = new OffscreenTabsEventManager();
77
78 return event_manager;
79 }
80
81 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
82 // Takes |url_string| and returns a GURL which is either valid and absolute
83 // or invalid. If |url_string| is not directly interpretable as a valid (it is
84 // likely a relative URL) an attempt is made to resolve it. |extension| is
85 // provided so it can be resolved relative to its extension base
86 // (chrome-extension://<id>/). Using the source frame url would be more correct,
87 // but because the api shipped with urls resolved relative to their extension
88 // base, we decided it wasn't worth breaking existing extensions to fix.
89 GURL ResolvePossiblyRelativeURL(const std::string& url_string,
90 const Extension* extension) {
91 GURL url = GURL(url_string);
92 if (!url.is_valid())
93 url = extension->GetResourceURL(url_string);
94
95 return url;
96 }
97
98 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
99 bool IsCrashURL(const GURL& url) {
100 // Check a fixed-up URL, to normalize the scheme and parse hosts correctly.
101 GURL fixed_url =
102 URLFixerUpper::FixupURL(url.possibly_invalid_spec(), std::string());
103 return (fixed_url.SchemeIs(chrome::kChromeUIScheme) &&
104 (fixed_url.host() == chrome::kChromeUIBrowserCrashHost ||
105 fixed_url.host() == chrome::kChromeUICrashHost));
106 }
107
108 bool GetCurrentTab(TabContents** tab_contents,
109 ExtensionFunctionDispatcher* dispatcher,
110 const Browser* browser,
111 std::string error_message) {
112 *tab_contents = dispatcher->delegate()->GetAssociatedTabContents();
113
114 // This is useful when there is no associated tab contents
115 // i.e. when running an automated API test
116 if (!*tab_contents)
117 *tab_contents = browser->GetSelectedTabContents();
118
119 if (tab_contents)
120 return true;
121
122 error_message = keys::kCurrentTabNotFound;
123 return false;
124 }
125
126 bool GetOffscreenTabById(const int tab_id,
127 TabContentsWrapper** offscreen_tab,
128 const TabContents* tab_contents,
129 std::string* error_message) {
130 std::vector<TabContents*> offscreen_tab_contents_vector =
131 (*GetOffscreenTabsMap())[ExtensionTabUtil::GetTabId(tab_contents)];
132
133 for (std::vector<TabContents*>::iterator
134 it_offscreen_tab_contents = offscreen_tab_contents_vector.begin();
135 it_offscreen_tab_contents != offscreen_tab_contents_vector.end();
136 ++it_offscreen_tab_contents)
137 if (ExtensionTabUtil::GetTabId(*it_offscreen_tab_contents) == tab_id) {
138 *offscreen_tab = TabContentsWrapper::GetCurrentWrapperForContents(
139 *it_offscreen_tab_contents);
140
141 return true;
142 }
143
144 *error_message = ExtensionErrorUtils::FormatErrorMessage(
145 keys::kOffscreenTabNotFoundError, base::IntToString(tab_id));
146 return false;
147 }
148
149 bool GetTabById(const int tab_id,
150 Browser* browser,
151 TabContents** tab_contents,
152 std::string* error_message) {
153 TabStripModel* tab_strip = browser->tabstrip_model();
154 for (int i = 0; i <tab_strip->count(); ++i) {
155 *tab_contents = tab_strip->GetTabContentsAt(i)->tab_contents();
156
157 if (ExtensionTabUtil::GetTabId(*tab_contents) == tab_id)
158 return true;
159 }
160
161 *error_message = ExtensionErrorUtils::FormatErrorMessage(
162 keys::kTabNotFoundError, base::IntToString(tab_id));
163 return false;
164 }
165
166 std::string GetTabUrl(const TabContents* tab_contents) {
167 return tab_contents->GetURL().spec();
168 }
169
170 int GetTabWidth(const TabContents* tab_contents) {
171 const TabContentsWrapper* tab =
172 TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
173
174 return tab ? tab->view()->GetContainerSize().width() : -1;
175 }
176
177 int GetTabHeight(const TabContents* tab_contents) {
178 const TabContentsWrapper* tab =
179 TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
180
181 return tab ? tab->view()->GetContainerSize().height() : -1;
182 }
183
184 void CloseOffscreenTab(TabContents* tab_contents) {
185 // TODO(alexbost): Is this the best way to close an offscreen tab?
186 delete TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
187 }
188
189 DictionaryValue* CreateOffscreenTabValue(const TabContentsWrapper* tab) {
190 DictionaryValue* result = new DictionaryValue();
191 result->SetInteger(keys::kIdKey,
192 ExtensionTabUtil::GetTabId(tab->tab_contents()));
193 result->SetString(keys::kUrlKey, GetTabUrl(tab->tab_contents()));
194 result->SetInteger(keys::kWidthKey, GetTabWidth(tab->tab_contents()));
195 result->SetInteger(keys::kHeightKey, GetTabHeight(tab->tab_contents()));
196
197 return result;
198 }
199
200 } // namespace
201
202 // Event Manager ---------------------------------------------------------------
203
204 OffscreenTabsEventManager::OffscreenTabsEventManager() {}
205 OffscreenTabsEventManager::~OffscreenTabsEventManager() {}
206
207 void OffscreenTabsEventManager::RegisterForTabNotifications(
208 const TabContents* tab_contents) {
209 registrar_.Add(this,
210 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
211 Source<NavigationController>(&tab_contents->controller()));
212
213 registrar_.Add(this,
214 content::NOTIFICATION_TAB_CONTENTS_DESTROYED,
215 Source<TabContents>(tab_contents));
216 }
217
218 void OffscreenTabsEventManager::UnregisterForTabNotifications(
219 const TabContents* tab_contents) {
220 registrar_.Remove(this,
221 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
222 Source<NavigationController>(&tab_contents->controller()));
223
224 registrar_.Remove(this,
225 content::NOTIFICATION_TAB_CONTENTS_DESTROYED,
226 Source<TabContents>(tab_contents));
227 }
228
229 void OffscreenTabsEventManager::Observe(const int type,
230 const NotificationSource& source,
231 const NotificationDetails& details) {
232 TabContents* tab_contents;
233
234 if (type == content::NOTIFICATION_TAB_CONTENTS_DESTROYED)
235 tab_contents = Source<TabContents>(source).ptr();
236 else if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED)
237 tab_contents = Source<NavigationController>(source).ptr()->tab_contents();
238 else
239 return;
240
241 DCHECK(tab_contents);
242
243 // Close all offscreen tabs spawned by this tab
244 std::vector<TabContents*> offscreen_tab_contents_vector =
245 (*GetOffscreenTabsMap())[ExtensionTabUtil::GetTabId(tab_contents)];
246 for (std::vector<TabContents*>::iterator
247 it_offscreen_tab_contents = offscreen_tab_contents_vector.begin();
248 it_offscreen_tab_contents != offscreen_tab_contents_vector.end();
249 ++it_offscreen_tab_contents)
250 CloseOffscreenTab(*it_offscreen_tab_contents);
251
252 GetOffscreenTabsMap()->erase(ExtensionTabUtil::GetTabId(tab_contents));
253
254 GetOffscreenTabsEventManager()->UnregisterForTabNotifications(tab_contents);
255 }
256
257 // create ----------------------------------------------------------------------
258
259 CreateOffscreenTabFunction::CreateOffscreenTabFunction() {}
260 CreateOffscreenTabFunction::~CreateOffscreenTabFunction() {}
261
262 bool CreateOffscreenTabFunction::RunImpl() {
263 Browser* browser = GetCurrentBrowser();
264 if (!browser) {
265 error_ = keys::kNoCurrentWindowError;
266 return false;
267 }
268
269 DictionaryValue* create_props;
270 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &create_props));
271
272 // Url
273 std::string url_string;
274 GURL url;
275 EXTENSION_FUNCTION_VALIDATE(
276 create_props->GetString(keys::kUrlKey, &url_string));
277 url = ResolvePossiblyRelativeURL(url_string, GetExtension());
278 if (!url.is_valid()) {
279 error_ = ExtensionErrorUtils::FormatErrorMessage(
280 keys::kInvalidUrlError, url_string);
281 return false;
282 }
283 if (IsCrashURL(url)) {
284 error_ = keys::kNoCrashBrowserError;
285 return false;
286 }
287
288 // Width and height
289 gfx::Rect window_bounds;
290 bool maximized;
291 if (!create_props->HasKey(keys::kWidthKey) ||
292 !create_props->HasKey(keys::kHeightKey))
293 WindowSizer::GetBrowserWindowBounds(std::string(), gfx::Rect(),
294 browser, &window_bounds,
295 &maximized);
296
297 int width;
298 if (create_props->HasKey(keys::kWidthKey))
299 EXTENSION_FUNCTION_VALIDATE(
300 create_props->GetInteger(keys::kWidthKey, &width));
301 else
302 width = window_bounds.width();
303
304 int height;
305 if (create_props->HasKey(keys::kHeightKey))
306 EXTENSION_FUNCTION_VALIDATE(
307 create_props->GetInteger(keys::kHeightKey, &height));
308 else
309 height = window_bounds.height();
310
311 // New offscreen tab
312 TabContents* offscreen_tab_contents =
313 new TabContents(profile_, NULL, MSG_ROUTING_NONE, NULL, NULL);
314 TabContentsWrapper* offscreen_tab =
315 new TabContentsWrapper(offscreen_tab_contents);
316
317 // Setting the size starts the renderer
318 offscreen_tab_contents->view()->SizeContents(gfx::Size(width, height));
319
320 // Navigate
321 offscreen_tab_contents->controller().LoadURL(
322 url, GURL(), PageTransition::LINK);
323
324 // Map the offscreen tab to the tab that spawned it
325 TabContents* tab_contents;
326 if (!GetCurrentTab(&tab_contents, dispatcher(), browser, error_))
327 return false;
328
329 (*GetOffscreenTabsMap())[ExtensionTabUtil::GetTabId(tab_contents)].
330 push_back(offscreen_tab_contents);
331
332 // Register for tab notifications
333 // if this is the first offscreen tab spawned by the tab
334 if ((*GetOffscreenTabsMap())[ExtensionTabUtil::GetTabId(tab_contents)].
335 size() == 1) {
336 GetOffscreenTabsEventManager()->RegisterForTabNotifications(tab_contents);
337 }
338
339 // Callback
340 if (has_callback()) {
341 result_.reset(CreateOffscreenTabValue(offscreen_tab));
342 SendResponse(true);
343 }
344
345 return true;
346 }
347
348 // get -------------------------------------------------------------------------
349
350 GetOffscreenTabFunction::GetOffscreenTabFunction() {}
351 GetOffscreenTabFunction::~GetOffscreenTabFunction() {}
352
353 bool GetOffscreenTabFunction::RunImpl() {
354 int tab_id;
355 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
356
357 Browser* browser = GetCurrentBrowser();
358 if (!browser) {
359 error_ = keys::kNoCurrentWindowError;
360 return false;
361 }
362 TabContents* current_tab_contents;
363 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
364 return false;
365 TabContentsWrapper* tab = NULL;
366 if (!GetOffscreenTabById(tab_id, &tab, current_tab_contents, &error_))
367 return false;
368
369 result_.reset(CreateOffscreenTabValue(tab));
370 SendResponse(true);
371
372 return true;
373 }
374
375 // getAll ----------------------------------------------------------------------
376
377 GetAllOffscreenTabFunction::GetAllOffscreenTabFunction() {}
378 GetAllOffscreenTabFunction::~GetAllOffscreenTabFunction() {}
379
380 bool GetAllOffscreenTabFunction::RunImpl() {
381 Browser* browser = GetCurrentBrowser();
382 if (!browser) {
383 error_ = keys::kNoCurrentWindowError;
384 return false;
385 }
386 TabContents* current_tab_contents;
387 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
388 return false;
389
390 std::vector<TabContents*> offscreen_tab_contents_vector =
391 (*GetOffscreenTabsMap())[ExtensionTabUtil::GetTabId(current_tab_contents)];
392
393 ListValue* tab_list = new ListValue();
394
395 for (std::vector<TabContents*>::iterator
396 it_offscreen_tab_contents = offscreen_tab_contents_vector.begin();
397 it_offscreen_tab_contents != offscreen_tab_contents_vector.end();
398 ++it_offscreen_tab_contents)
399 tab_list->Append(CreateOffscreenTabValue(TabContentsWrapper::
400 GetCurrentWrapperForContents(*it_offscreen_tab_contents)));
401
402 result_.reset(tab_list);
403 SendResponse(true);
404
405 return true;
406 }
407
408 // remove ----------------------------------------------------------------------
409
410 RemoveOffscreenTabFunction::RemoveOffscreenTabFunction() {}
411 RemoveOffscreenTabFunction::~RemoveOffscreenTabFunction() {}
412
413 bool RemoveOffscreenTabFunction::RunImpl() {
414 int tab_id;
415 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
416
417 for (OffscreenTabsMap::iterator it = GetOffscreenTabsMap()->begin();
418 it != GetOffscreenTabsMap()->end(); ++it)
419 for (std::vector<TabContents*>::iterator it_offscreen_tab_contents =
420 it->second.begin();
421 it_offscreen_tab_contents != it->second.end();
422 ++it_offscreen_tab_contents)
423 if (ExtensionTabUtil::GetTabId(*it_offscreen_tab_contents) == tab_id) {
424 TabContents* tab_contents;
425 if (!GetTabById(
426 it->first, GetCurrentBrowser(), &tab_contents, &error_))
427 return false;
428
429 CloseOffscreenTab(*it_offscreen_tab_contents);
430
431 it->second.erase(it_offscreen_tab_contents);
432
433 // If this was the last offscreen tab for the tab,
434 // unregister the tab for notifications and remove it from the map
435 if (it->second.empty()) {
436 GetOffscreenTabsEventManager()->
437 UnregisterForTabNotifications(tab_contents);
438 GetOffscreenTabsMap()->erase(it);
439 }
440
441 return true;
442 }
443
444 error_ = ExtensionErrorUtils::FormatErrorMessage(
445 keys::kOffscreenTabNotFoundError, base::IntToString(tab_id));
446 return false;
447 }
448
449 // sendKeyboardEvent -----------------------------------------------------------
450
451 SendKeyboardEventOffscreenTabFunction::
452 SendKeyboardEventOffscreenTabFunction() {}
453 SendKeyboardEventOffscreenTabFunction::
454 ~SendKeyboardEventOffscreenTabFunction() {}
455
456 bool SendKeyboardEventOffscreenTabFunction::RunImpl() {
457 int tab_id;
458 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
459
460 Browser* browser = GetCurrentBrowser();
461 if (!browser) {
462 error_ = keys::kNoCurrentWindowError;
463 return false;
464 }
465 TabContents* current_tab_contents;
466 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
467 return false;
468 TabContentsWrapper* tab = NULL;
469 if (!GetOffscreenTabById(tab_id, &tab, current_tab_contents, &error_))
470 return false;
471
472 // JavaScript KeyboardEvent
473 DictionaryValue* dict;
474 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &dict));
475
476 NativeWebKeyboardEvent keyboard_event;
477
478 // Type
479 std::string type;
480 if (dict->HasKey(keys::kKeyboardEventTypeKey)) {
481 EXTENSION_FUNCTION_VALIDATE(
482 dict->GetString(keys::kKeyboardEventTypeKey, &type));
483 } else {
484 error_ = keys::kInvalidKeyboardEventObjectError;
485 return false;
486 }
487
488 if (type.compare(keys::kKeyboardEventTypeValueKeypress) == 0) {
489 keyboard_event.type = WebInputEvent::Char;
490 } else if (type.compare(keys::kKeyboardEventTypeValueKeydown) == 0) {
491 keyboard_event.type = WebInputEvent::KeyDown;
492 } else if (type.compare(keys::kKeyboardEventTypeValueKeyup) == 0) {
493 keyboard_event.type = WebInputEvent::KeyUp;
494 } else {
495 error_ = keys::kInvalidKeyboardEventObjectError;
496 return false;
497 }
498
499 // Key code
500 int key_code;
501 if (dict->HasKey(keys::kKeyboardEventKeyCodeKey)) {
502 EXTENSION_FUNCTION_VALIDATE(
503 dict->GetInteger(keys::kKeyboardEventKeyCodeKey, &key_code));
504 } else {
505 error_ = keys::kInvalidKeyboardEventObjectError;
506 return false;
507 }
508
509 keyboard_event.nativeKeyCode = key_code;
510 keyboard_event.windowsKeyCode = key_code;
511
512 // Key identifier
513 keyboard_event.setKeyIdentifierFromWindowsKeyCode();
514
515 // Keypress = type character
516 if (type.compare(keys::kKeyboardEventTypeValueKeypress) == 0) {
517 int char_code;
518 if (dict->HasKey(keys::kKeyboardEventCharCodeKey)) {
519 EXTENSION_FUNCTION_VALIDATE(
520 dict->GetInteger(keys::kKeyboardEventCharCodeKey, &char_code));
521 keyboard_event.text[0] = char_code;
522 keyboard_event.unmodifiedText[0] = char_code;
523 } else {
524 error_ = keys::kInvalidKeyboardEventObjectError;
525 return false;
526 }
527 }
528
529 // Modifiers
530 bool alt_key;
531 if (dict->HasKey(keys::kKeyboardEventAltKeyKey))
532 EXTENSION_FUNCTION_VALIDATE(
533 dict->GetBoolean(keys::kKeyboardEventAltKeyKey, &alt_key));
534 if (alt_key)
535 keyboard_event.modifiers |= WebInputEvent::AltKey;
536
537 bool ctrl_key;
538 if (dict->HasKey(keys::kKeyboardEventCtrlKeyKey))
539 EXTENSION_FUNCTION_VALIDATE(
540 dict->GetBoolean(keys::kKeyboardEventCtrlKeyKey, &ctrl_key));
541 if (ctrl_key)
542 keyboard_event.modifiers |= WebInputEvent::ControlKey;
543
544 bool meta_key = false;
545 if (dict->HasKey(keys::kMouseEventMetaKeyKey))
546 EXTENSION_FUNCTION_VALIDATE(
547 dict->GetBoolean(keys::kMouseEventMetaKeyKey, &meta_key));
548 if (meta_key)
549 keyboard_event.modifiers |= WebInputEvent::MetaKey;
550
551 bool shift_key;
552 if (dict->HasKey(keys::kKeyboardEventShiftKeyKey))
553 EXTENSION_FUNCTION_VALIDATE(
554 dict->GetBoolean(keys::kKeyboardEventShiftKeyKey, &shift_key));
555 if (shift_key)
556 keyboard_event.modifiers |= WebInputEvent::ShiftKey;
557
558 // Forward event
559 tab->tab_contents()->render_view_host()->
560 ForwardKeyboardEvent(keyboard_event);
561
562 // Callback
563 if (has_callback()) {
564 result_.reset(CreateOffscreenTabValue(tab));
565 SendResponse(true);
566 }
567
568 return true;
569 }
570
571 // sendMouseEvent --------------------------------------------------------------
572
573 SendMouseEventOffscreenTabFunction::SendMouseEventOffscreenTabFunction() {}
574 SendMouseEventOffscreenTabFunction::~SendMouseEventOffscreenTabFunction() {}
575
576 bool SendMouseEventOffscreenTabFunction::RunImpl() {
577 int tab_id;
578 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
579
580 Browser* browser = GetCurrentBrowser();
581 if (!browser) {
582 error_ = keys::kNoCurrentWindowError;
583 return false;
584 }
585 TabContents* current_tab_contents;
586 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
587 return false;
588 TabContentsWrapper* tab = NULL;
589 if (!GetOffscreenTabById(tab_id, &tab, current_tab_contents, &error_))
590 return false;
591
592 // JavaScript MouseEvent
593 DictionaryValue* dict;
594 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &dict));
595
596 std::string type;
597 if (dict->HasKey(keys::kMouseEventTypeKey)) {
598 EXTENSION_FUNCTION_VALIDATE(
599 dict->GetString(keys::kMouseEventTypeKey, &type));
600 } else {
601 error_ = keys::kInvalidMouseEventObjectError;
602 return false;
603 }
604
605 if (type.compare(keys::kMouseEventTypeValueMousewheel) == 0) {
606 WebKit::WebMouseWheelEvent wheel_event;
607
608 // Type
609 wheel_event.type = WebInputEvent::MouseWheel;
610
611 // deltaX, deltaY
612 if (dict->HasKey(keys::kMouseEventWheelDeltaXKey) &&
613 dict->HasKey(keys::kMouseEventWheelDeltaYKey)) {
614 int delta_x, delta_y;
615 EXTENSION_FUNCTION_VALIDATE(
616 dict->GetInteger(keys::kMouseEventWheelDeltaXKey, &delta_x));
617 EXTENSION_FUNCTION_VALIDATE(
618 dict->GetInteger(keys::kMouseEventWheelDeltaYKey, &delta_y));
619 wheel_event.deltaX = delta_x;
620 wheel_event.deltaY = delta_y;
621 } else {
622 error_ = keys::kInvalidMouseEventObjectError;
623 return false;
624 }
625
626 // Forward the event
627 tab->tab_contents()->render_view_host()->ForwardWheelEvent(wheel_event);
628 } else {
629 WebKit::WebMouseEvent mouse_event;
630
631 // Type
632 if (type.compare(keys::kMouseEventTypeValueMousedown) == 0 ||
633 type.compare(keys::kMouseEventTypeValueClick) == 0) {
634 mouse_event.type = WebKit::WebInputEvent::MouseDown;
635 } else if (type.compare(keys::kMouseEventTypeValueMouseup) == 0) {
636 mouse_event.type = WebKit::WebInputEvent::MouseUp;
637 } else if (type.compare(keys::kMouseEventTypeValueMousemove) == 0) {
638 mouse_event.type = WebKit::WebInputEvent::MouseMove;
639 } else {
640 error_ = keys::kInvalidMouseEventObjectError;
641 return false;
642 }
643
644 // Button
645 int button;
646 if (dict->HasKey(keys::kMouseEventButtonKey)) {
647 EXTENSION_FUNCTION_VALIDATE(
648 dict->GetInteger(keys::kMouseEventButtonKey, &button));
649 } else {
650 error_ = keys::kInvalidMouseEventObjectError;
651 return false;
652 }
653
654 if (button == keys::kMouseEventButtonValueLeft) {
655 mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
656 } else if (button == keys::kMouseEventButtonValueMiddle) {
657 mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;
658 } else if (button == keys::kMouseEventButtonValueRight) {
659 mouse_event.button = WebKit::WebMouseEvent::ButtonRight;
660 } else {
661 error_ = keys::kInvalidMouseEventObjectError;
662 return false;
663 }
664
665 // x, y
666 if (HasOptionalArgument(2) && HasOptionalArgument(3)) {
667 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(2, &mouse_event.x));
668 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(3, &mouse_event.y));
669 } else {
670 error_ = keys::kNoMouseCoordinatesError;
671 return false;
672 }
673
674 // Modifiers
675 bool alt_key = false;
676 if (dict->HasKey(keys::kMouseEventAltKeyKey))
677 EXTENSION_FUNCTION_VALIDATE(
678 dict->GetBoolean(keys::kMouseEventAltKeyKey, &alt_key));
679 if (alt_key)
680 mouse_event.modifiers |= WebInputEvent::AltKey;
681
682 bool ctrl_key = false;
683 if (dict->HasKey(keys::kMouseEventCtrlKeyKey))
684 EXTENSION_FUNCTION_VALIDATE(
685 dict->GetBoolean(keys::kMouseEventCtrlKeyKey, &ctrl_key));
686 if (ctrl_key)
687 mouse_event.modifiers |= WebInputEvent::ControlKey;
688
689 bool meta_key = false;
690 if (dict->HasKey(keys::kMouseEventMetaKeyKey))
691 EXTENSION_FUNCTION_VALIDATE(
692 dict->GetBoolean(keys::kMouseEventMetaKeyKey, &meta_key));
693 if (meta_key)
694 mouse_event.modifiers |= WebInputEvent::MetaKey;
695
696 bool shift_key = false;
697 if (dict->HasKey(keys::kMouseEventShiftKeyKey))
698 EXTENSION_FUNCTION_VALIDATE(
699 dict->GetBoolean(keys::kMouseEventShiftKeyKey, &shift_key));
700 if (shift_key)
701 mouse_event.modifiers |= WebInputEvent::ShiftKey;
702
703 // Click count
704 mouse_event.clickCount = 1;
705
706 // Forward the event
707 tab->tab_contents()->render_view_host()->ForwardMouseEvent(mouse_event);
708
709 // If the event is a click,
710 // fire a mouseup event in addition to the mousedown
711 if (type.compare(keys::kMouseEventTypeValueClick) == 0) {
712 mouse_event.type = WebKit::WebInputEvent::MouseUp;
713 tab->tab_contents()->render_view_host()->ForwardMouseEvent(mouse_event);
714 }
715 }
716
717 // Callback
718 if (has_callback()) {
719 result_.reset(CreateOffscreenTabValue(tab));
720 SendResponse(true);
721 }
722
723 return true;
724 }
725
726 // toDataUrl -------------------------------------------------------------------
727
728 ToDataUrlOffscreenTabFunction::ToDataUrlOffscreenTabFunction() {}
729 ToDataUrlOffscreenTabFunction::~ToDataUrlOffscreenTabFunction() {}
730
731 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
732 // TODO(alexbost): We want to optimize this function in order to get more image
733 // updates on the browser side. One improvement would be to implement another
734 // hash map to get offscreen tabs in O(1).
735 bool ToDataUrlOffscreenTabFunction::RunImpl() {
736 int tab_id;
737 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
738
739 Browser* browser = GetCurrentBrowser();
740 if (!browser) {
741 error_ = keys::kNoCurrentWindowError;
742 return false;
743 }
744 TabContents* current_tab_contents;
745 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
746 return false;
747 TabContentsWrapper* tab = NULL;
748 if (!GetOffscreenTabById(tab_id, &tab, current_tab_contents, &error_))
749 return false;
750
751 image_format_ = FORMAT_JPEG; // Default format is JPEG.
752 image_quality_ = kDefaultQuality; // Default quality setting.
753
754 if (HasOptionalArgument(1)) {
755 DictionaryValue* options;
756 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options));
757
758 if (options->HasKey(keys::kFormatKey)) {
759 std::string format;
760 EXTENSION_FUNCTION_VALIDATE(
761 options->GetString(keys::kFormatKey, &format));
762
763 if (format == keys::kFormatValueJpeg) {
764 image_format_ = FORMAT_JPEG;
765 } else if (format == keys::kFormatValuePng) {
766 image_format_ = FORMAT_PNG;
767 } else {
768 // Schema validation should make this unreachable.
769 EXTENSION_FUNCTION_VALIDATE(0);
770 }
771 }
772
773 if (options->HasKey(keys::kQualityKey)) {
774 EXTENSION_FUNCTION_VALIDATE(
775 options->GetInteger(keys::kQualityKey, &image_quality_));
776 }
777 }
778
779 // captureVisibleTab() can return an image containing sensitive information
780 // that the browser would otherwise protect. Ensure the extension has
781 // permission to do this.
782 if (!GetExtension()->
783 CanCaptureVisiblePage(tab->tab_contents()->GetURL(), &error_))
784 return false;
785
786 // The backing store approach does not work on Mac
787 // TODO(alexbost): Test on Windows
788 #if !defined(OS_MACOSX)
789 RenderViewHost* render_view_host = tab->tab_contents()->render_view_host();
790
791 // If a backing store is cached for the tab we want to capture,
792 // and it can be copied into a bitmap, then use it to generate the image.
793 BackingStore* backing_store = render_view_host->GetBackingStore(false);
794 if (backing_store && CaptureSnapshotFromBackingStore(backing_store))
795 return true;
796 #endif
797
798 // Ask the renderer for a snapshot of the tab.
799 tab->CaptureSnapshot();
800 registrar_.Add(this,
801 chrome::NOTIFICATION_TAB_SNAPSHOT_TAKEN,
802 Source<TabContentsWrapper>(tab));
803
804 AddRef(); // Balanced in ToDataUrlOffscreenTabFunction::Observe().
805
806 return true;
807 }
808
809 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
810 // Build the image of a tab's contents out of a backing store.
811 // This may fail if we can not copy a backing store into a bitmap.
812 // For example, some uncommon X11 visual modes are not supported by
813 // CopyFromBackingStore().
814 bool ToDataUrlOffscreenTabFunction::CaptureSnapshotFromBackingStore(
815 BackingStore* backing_store) {
816
817 skia::PlatformCanvas temp_canvas;
818 if (!backing_store->CopyFromBackingStore(gfx::Rect(backing_store->size()),
819 &temp_canvas)) {
820 return false;
821 }
822 VLOG(1) << "captureVisibleTab() got image from backing store.";
823
824 SendResultFromBitmap(
825 skia::GetTopDevice(temp_canvas)->accessBitmap(false));
826 return true;
827 }
828
829 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
830 void ToDataUrlOffscreenTabFunction::Observe(const int type,
831 const NotificationSource& source,
832 const NotificationDetails& details) {
833 DCHECK(type == chrome::NOTIFICATION_TAB_SNAPSHOT_TAKEN);
834
835 const SkBitmap *screen_capture = Details<const SkBitmap>(details).ptr();
836 const bool error = screen_capture->empty();
837
838 if (error) {
839 error_ = keys::kInternalVisibleTabCaptureError;
840 SendResponse(false);
841 } else {
842 VLOG(1) << "Got image from renderer.";
843 SendResultFromBitmap(*screen_capture);
844 }
845
846 Release(); // Balanced in ToDataUrlOffscreenTabFunction::RunImpl().
847 }
848
849 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
850 // Turn a bitmap of the screen into an image, set that image as the result,
851 // and call SendResponse().
852 void ToDataUrlOffscreenTabFunction::SendResultFromBitmap(
853 const SkBitmap& screen_capture) {
854 std::vector<unsigned char> data;
855 SkAutoLockPixels screen_capture_lock(screen_capture);
856 bool encoded = false;
857 std::string mime_type;
858 switch (image_format_) {
859 case FORMAT_JPEG:
860 encoded = gfx::JPEGCodec::Encode(
861 reinterpret_cast<unsigned char*>(screen_capture.getAddr32(0, 0)),
862 gfx::JPEGCodec::FORMAT_SkBitmap,
863 screen_capture.width(),
864 screen_capture.height(),
865 static_cast<int>(screen_capture.rowBytes()),
866 image_quality_,
867 &data);
868 mime_type = keys::kMimeTypeJpeg;
869 break;
870 case FORMAT_PNG:
871 encoded = gfx::PNGCodec::EncodeBGRASkBitmap(
872 screen_capture,
873 true, // Discard transparency.
874 &data);
875 mime_type = keys::kMimeTypePng;
876 break;
877 default:
878 NOTREACHED() << "Invalid image format.";
879 }
880
881 if (!encoded) {
882 error_ = keys::kInternalVisibleTabCaptureError;
883 SendResponse(false);
884 return;
885 }
886
887 std::string base64_result;
888 base::StringPiece stream_as_string(
889 reinterpret_cast<const char*>(vector_as_array(&data)), data.size());
890
891 base::Base64Encode(stream_as_string, &base64_result);
892 base64_result.insert(0, base::StringPrintf("data:%s;base64,",
893 mime_type.c_str()));
894 result_.reset(new StringValue(base64_result));
895 SendResponse(true);
896 }
897
898 // update ----------------------------------------------------------------------
899
900 UpdateOffscreenTabFunction::UpdateOffscreenTabFunction() {}
901 UpdateOffscreenTabFunction::~UpdateOffscreenTabFunction() {}
902
903 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
904 bool UpdateOffscreenTabFunction::RunImpl() {
905 int tab_id;
906 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
907
908 Browser* browser = GetCurrentBrowser();
909 if (!browser) {
910 error_ = keys::kNoCurrentWindowError;
911 return false;
912 }
913 TabContents* current_tab_contents;
914 if (!GetCurrentTab(&current_tab_contents, dispatcher(), browser, error_))
915 return false;
916 TabContentsWrapper* tab = NULL;
917 if (!GetOffscreenTabById(tab_id, &tab, current_tab_contents, &error_))
918 return false;
919
920 DictionaryValue* update_props;
921 EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &update_props));
922
923 // Url
924 if (update_props->HasKey(keys::kUrlKey)) {
925 std::string url_string;
926 GURL url;
927 EXTENSION_FUNCTION_VALIDATE(
928 update_props->GetString(keys::kUrlKey, &url_string));
929 url = ResolvePossiblyRelativeURL(url_string, GetExtension());
930 if (!url.is_valid()) {
931 error_ = ExtensionErrorUtils::FormatErrorMessage(
932 keys::kInvalidUrlError, url_string);
933 return false;
934 }
935 if (IsCrashURL(url)) {
936 error_ = keys::kNoCrashBrowserError;
937 return false;
938 }
939
940 // JavaScript URLs can do the same kinds of things as cross-origin XHR, so
941 // we need to check host permissions before allowing them.
942 if (url.SchemeIs(chrome::kJavaScriptScheme)) {
943 if (!GetExtension()->CanExecuteScriptOnPage(
944 tab->tab_contents()->GetURL(), NULL, &error_)) {
945 return false;
946 }
947
948 ExtensionMsg_ExecuteCode_Params params;
949 params.request_id = request_id();
950 params.extension_id = extension_id();
951 params.is_javascript = true;
952 params.code = url.path();
953 params.all_frames = false;
954 params.in_main_world = true;
955
956 RenderViewHost* render_view_host =
957 tab->tab_contents()->render_view_host();
958 render_view_host->Send(
959 new ExtensionMsg_ExecuteCode(render_view_host->routing_id(),
960 params));
961
962 Observe(tab->tab_contents());
963 AddRef(); // balanced in Observe()
964
965 return true;
966 }
967
968 tab->tab_contents()->controller().
969 LoadURL(url, GURL(), PageTransition::LINK);
970
971 // The URL of a tab contents never actually changes to a JavaScript URL, so
972 // this check only makes sense in other cases.
973 if (!url.SchemeIs(chrome::kJavaScriptScheme))
974 DCHECK_EQ(url.spec(), tab->tab_contents()->GetURL().spec());
975 }
976
977 // Width and height
978 if (update_props->HasKey(keys::kWidthKey) ||
979 update_props->HasKey(keys::kHeightKey)) {
980 int width;
981 if (update_props->HasKey(keys::kWidthKey))
982 EXTENSION_FUNCTION_VALIDATE(
983 update_props->GetInteger(keys::kWidthKey, &width));
984 else
985 GetTabWidth(tab->tab_contents());
986
987 int height;
988 if (update_props->HasKey(keys::kHeightKey))
989 EXTENSION_FUNCTION_VALIDATE(
990 update_props->GetInteger(keys::kHeightKey, &height));
991 else
992 GetTabHeight(tab->tab_contents());
993
994 tab->tab_contents()->view()->SizeContents(gfx::Size(width, height));
995 }
996
997 // Callback
998 if (has_callback()) {
999 result_.reset(CreateOffscreenTabValue(tab));
1000 SendResponse(true);
1001 }
1002
1003 return true;
1004 }
1005
1006 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1007 bool UpdateOffscreenTabFunction::OnMessageReceived(
1008 const IPC::Message& message) {
1009 if (message.type() != ExtensionHostMsg_ExecuteCodeFinished::ID)
1010 return false;
1011
1012 int message_request_id;
1013 void* iter = NULL;
1014 if (!message.ReadInt(&iter, &message_request_id)) {
1015 NOTREACHED() << "malformed extension message";
1016 return true;
1017 }
1018
1019 if (message_request_id != request_id())
1020 return false;
1021
1022 IPC_BEGIN_MESSAGE_MAP(UpdateOffscreenTabFunction, message)
1023 IPC_MESSAGE_HANDLER(ExtensionHostMsg_ExecuteCodeFinished,
1024 OnExecuteCodeFinished)
1025 IPC_END_MESSAGE_MAP()
1026 return true;
1027 }
1028
1029 // TODO(alexbost): Needs refactoring. Similar method in extension_tabs_module.
1030 void UpdateOffscreenTabFunction::OnExecuteCodeFinished(int request_id,
1031 bool success,
1032 const std::string& error) {
1033 if (!error.empty()) {
1034 CHECK(!success);
1035 error_ = error;
1036 }
1037
1038 SendResponse(success);
1039
1040 Observe(NULL);
1041 Release(); // balanced in Execute()
1042 }
1043
1044
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698