1# Copyright 2015 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
5from telemetry.internal.backends.chrome_inspector import devtools_client_backend
6from telemetry.internal.browser import web_contents
7
8try:
9  from devil.android import ports
10except ImportError:
11  ports = None
12
13class WebViewNotFoundException(Exception):
14  pass
15
16class AndroidProcess(object):
17  """Represents a single android process."""
18
19  def __init__(self, app_backend, pid, name):
20    self._app_backend = app_backend
21    self._pid = pid
22    self._name = name
23    self._local_port = ports.AllocateTestServerPort()
24    self._devtools_client = None
25
26  @property
27  def pid(self):
28    return self._pid
29
30  @property
31  def name(self):
32    return self._name
33
34  @property
35  def _remote_devtools_port(self):
36    return 'localabstract:webview_devtools_remote_%s' % str(self.pid)
37
38  def _UpdateDevToolsClient(self):
39    if self._devtools_client is None:
40      self._app_backend.platform_backend.ForwardHostToDevice(
41          self._local_port, self._remote_devtools_port)
42      if devtools_client_backend.IsDevToolsAgentAvailable(
43          self._local_port, self._app_backend):
44        self._devtools_client = devtools_client_backend.DevToolsClientBackend(
45            self._local_port, self._remote_devtools_port, self._app_backend)
46
47  def GetWebViews(self):
48    webviews = []
49    self._UpdateDevToolsClient()
50    if self._devtools_client is not None:
51      devtools_context_map = (
52          self._devtools_client.GetUpdatedInspectableContexts())
53      for context in devtools_context_map.contexts:
54        webviews.append(web_contents.WebContents(
55            devtools_context_map.GetInspectorBackend(context['id'])))
56    return webviews
57