1# Copyright 2014 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
5import collections
6
7from telemetry.internal.backends.chrome_inspector import inspector_backend_list
8from telemetry.internal.browser import extension_page
9
10
11class ExtensionBackendList(inspector_backend_list.InspectorBackendList):
12  """A dynamic sequence of extension_page.ExtensionPages."""
13
14  def __init__(self, browser_backend):
15    super(ExtensionBackendList, self).__init__(browser_backend)
16
17  def ShouldIncludeContext(self, context):
18    return context['url'].startswith('chrome-extension://')
19
20  def CreateWrapper(self, inspector_backend):
21    return extension_page.ExtensionPage(inspector_backend)
22
23class ExtensionBackendDict(collections.Mapping):
24  """A dynamic mapping of extension_id to extension_page.ExtensionPages."""
25
26  def __init__(self, browser_backend):
27    self._extension_backend_list = ExtensionBackendList(browser_backend)
28
29  def __getitem__(self, extension_id):
30    extensions = []
31    for context_id in self._extension_backend_list.IterContextIds():
32      if self.ContextIdToExtensionId(context_id) == extension_id:
33        extensions.append(
34            self._extension_backend_list.GetBackendFromContextId(context_id))
35    if not extensions:
36      raise KeyError('Cannot find an extension with id=%s' % extension_id)
37    return extensions
38
39  def __iter__(self):
40    for context_id in self._extension_backend_list.IterContextIds():
41      yield self._extension_backend_list.GetBackendFromContextId(context_id)
42
43  def __len__(self):
44    return len(self._extension_backend_list)
45
46  def ContextIdToExtensionId(self, context_id):
47    context = self._extension_backend_list.GetContextInfo(context_id)
48    return extension_page.UrlToExtensionId(context['url'])
49