1# Copyright 2013 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. 4import os 5 6from telemetry.page.actions import gesture_action 7from telemetry.page.actions import page_action 8 9class SwipeAction(gesture_action.GestureAction): 10 def __init__(self, attributes=None): 11 super(SwipeAction, self).__init__(attributes) 12 self._SetTimelineMarkerBaseName('SwipeAction::RunAction') 13 14 def WillRunAction(self, page, tab): 15 for js_file in ['gesture_common.js', 'swipe.js']: 16 with open(os.path.join(os.path.dirname(__file__), js_file)) as f: 17 js = f.read() 18 tab.ExecuteJavaScript(js) 19 20 # Fail if browser doesn't support synthetic swipe gestures. 21 if not tab.EvaluateJavaScript('window.__SwipeAction_SupportedByBrowser()'): 22 raise page_action.PageActionNotSupported( 23 'Synthetic swipe not supported for this browser') 24 25 # TODO(dominikg): Query synthetic gesture target to check if touch is 26 # supported. 27 28 done_callback = 'function() { window.__swipeActionDone = true; }' 29 tab.ExecuteJavaScript(""" 30 window.__swipeActionDone = false; 31 window.__swipeAction = new __SwipeAction(%s);""" 32 % (done_callback)) 33 34 def RunGesture(self, page, tab, previous_action): 35 left_start_percentage = 0.5 36 top_start_percentage = 0.5 37 direction = 'left' 38 distance = 100 39 if hasattr(self, 'left_start_percentage'): 40 left_start_percentage = self.left_start_percentage 41 if hasattr(self, 'top_start_percentage'): 42 top_start_percentage = self.top_start_percentage 43 if hasattr(self, 'direction'): 44 direction = self.direction 45 if direction not in ['down', 'up', 'left', 'right']: 46 raise page_action.PageActionNotSupported( 47 'Invalid swipe direction: %s' % direction) 48 if hasattr(self, 'distance'): 49 distance = self.distance 50 if hasattr(self, 'element_function'): 51 tab.ExecuteJavaScript(""" 52 (%s)(function(element) { window.__swipeAction.start( 53 { element: element, 54 left_start_percentage: %s, 55 top_start_percentage: %s, 56 direction: '%s', 57 distance: %s }) 58 });""" % (self.element_function, 59 left_start_percentage, 60 top_start_percentage, 61 direction, 62 distance)) 63 else: 64 tab.ExecuteJavaScript(""" 65 window.__swipeAction.start( 66 { element: document.body, 67 left_start_percentage: %s, 68 top_start_percentage: %s, 69 direction: '%s', 70 distance: %s });""" 71 % (left_start_percentage, 72 top_start_percentage, 73 direction, 74 distance)) 75 76 tab.WaitForJavaScriptExpression('window.__swipeActionDone', 60) 77 78 def CanBeBound(self): 79 return True 80 81 def BindMeasurementJavaScript(self, tab, start_js, stop_js): 82 # Make the swipe action start and stop measurement automatically. 83 tab.ExecuteJavaScript(""" 84 window.__swipeAction.beginMeasuringHook = function() { %s }; 85 window.__swipeAction.endMeasuringHook = function() { %s }; 86 """ % (start_js, stop_js)) 87