aboutsummaryrefslogtreecommitdiffhomepage
path: root/platform_tools/android/skp_gen/android_skp_capture.py
blob: 3045b9f97d815d88cd6cd44abd137854f66bf627 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python

# Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


from __future__ import with_statement

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

import ast
import os
import subprocess
import time


# Time to wait between performing UI actions and capturing the SKP.
WAIT_FOR_SKP_CAPTURE = 1


class DragAction:
  """Action describing a touch drag."""
  def __init__(self, start, end, duration, points):
    self.start = start
    self.end = end
    self.duration = duration
    self.points = points

  def run(self, device):
    """Perform the action."""
    return device.drag(self.start, self.end, self.duration, self.points)


class PressAction:
  """Action describing a button press."""
  def __init__(self, button, press_type):
    self.button = button
    self.press_type = press_type

  def run(self, device):
    """Perform the action."""
    return device.press(self.button, self.press_type)


def parse_action(action_dict):
  """Parse a dict describing an action and return an Action object."""
  if action_dict['type'] == 'drag':
    return DragAction(tuple(action_dict['start']),
                      tuple(action_dict['end']),
                      action_dict['duration'],
                      action_dict['points'])
  elif action_dict['type'] == 'press':
    return PressAction(action_dict['button'], action_dict['press_type'])
  else:
    raise TypeError('Unsupported action type: %s' % action_dict['type'])


class App:
  """Class which describes an app to launch and actions to run."""
  def __init__(self, name, package, activity, app_launch_delay, actions):
    self.name = name
    self.package = package
    self.activity = activity
    self.app_launch_delay = app_launch_delay
    self.run_component = '%s/%s' % (self.package, self.activity)
    self.actions = [parse_action(a) for a in actions]

  def launch(self, device):
    """Launch the app on the device."""
    device.startActivity(component=self.run_component)
    time.sleep(self.app_launch_delay)

  def kill(self):
    """Kill the app."""
    adb_shell('am force-stop %s' % self.package)


def check_output(cmd):
  """Convenience implementation of subprocess.check_output."""
  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  if proc.wait() != 0:
    raise Exception('Command failed: %s' % ' '.join(cmd))
  return proc.communicate()[0]


def adb_shell(cmd):
  """Run the given ADB shell command and emulate the exit code."""
  output = check_output(['adb', 'shell', cmd + '; echo $?']).strip()
  lines = output.splitlines()
  if lines[-1] != '0':
    raise Exception('ADB command failed: %s\n\nOutput:\n%s' % (cmd, output))
  return '\n'.join(lines[:-1])


def remote_file_exists(filename):
  """Return True if the given file exists on the device and False otherwise."""
  try:
    adb_shell('test -f %s' % filename)
    return True
  except Exception:
    return False


def capture_skp(skp_file, package, device):
  """Capture an SKP."""
  remote_path = '/data/data/%s/cache/%s' % (package, os.path.basename(skp_file))
  try:
    adb_shell('rm %s' % remote_path)
  except Exception:
    if remote_file_exists(remote_path):
      raise

  adb_shell('setprop debug.hwui.capture_frame_as_skp %s' % remote_path)
  try:
    # Spin, wait for the SKP to be written.
    timeout = 10  # Seconds
    start = time.time()
    device.drag((300, 300), (300, 350), 1, 10)  # Dummy action to force a draw.
    while not remote_file_exists(remote_path):
      if time.time() - start > timeout:
        raise Exception('Timed out waiting for SKP capture.')
      time.sleep(1)

    # Pull the SKP from the device.
    cmd = ['adb', 'pull', remote_path, skp_file]
    check_output(cmd)

  finally:
    adb_shell('setprop debug.hwui.capture_frame_as_skp ""')


def load_app(filename):
  """Load the JSON file describing an app and return an App instance."""
  with open(filename) as f:
    app_dict = ast.literal_eval(f.read())
  return App(app_dict['name'],
             app_dict['package'],
             app_dict['activity'],
             app_dict['app_launch_delay'],
             app_dict['actions'])


def main():
  """Capture SKPs for all apps."""
  device = MonkeyRunner.waitForConnection()

  # TODO(borenet): Kill all apps.
  device.wake()
  device.drag((600, 600), (10, 10), 0.2, 10)

  apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'apps')
  app_files = [os.path.join(apps_dir, app) for app in os.listdir(apps_dir)]

  for app_file in app_files:
    app = load_app(app_file)
    print app.name
    print '  Package %s' % app.package
    app.launch(device)
    print '  Launched activity %s' % app.activity

    for action in app.actions:
      print '  %s' % action.__class__.__name__
      action.run(device)

    time.sleep(WAIT_FOR_SKP_CAPTURE)
    print '  Capturing SKP.'
    skp_file = '%s.skp' % app.name
    capture_skp(skp_file, app.package, device)
    print '  Wrote SKP to %s' % skp_file
    print
    app.kill()


if __name__ == '__main__':
  main()