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. 4 5import os 6 7from telemetry.page.actions import page_action 8 9 10class TapAction(page_action.PageAction): 11 def __init__(self, selector=None, text=None, element_function=None, 12 left_position_percentage=0.5, top_position_percentage=0.5, 13 duration_ms=50): 14 super(TapAction, self).__init__() 15 self.selector = selector 16 self.text = text 17 self.element_function = element_function 18 self.left_position_percentage = left_position_percentage 19 self.top_position_percentage = top_position_percentage 20 self.duration_ms = duration_ms 21 22 def WillRunAction(self, tab): 23 for js_file in ['gesture_common.js', 'tap.js']: 24 with open(os.path.join(os.path.dirname(__file__), js_file)) as f: 25 js = f.read() 26 tab.ExecuteJavaScript(js) 27 28 # Fail if browser doesn't support synthetic tap gestures. 29 if not tab.EvaluateJavaScript('window.__TapAction_SupportedByBrowser()'): 30 raise page_action.PageActionNotSupported( 31 'Synthetic tap not supported for this browser') 32 33 done_callback = 'function() { window.__tapActionDone = true; }' 34 tab.ExecuteJavaScript(""" 35 window.__tapActionDone = false; 36 window.__tapAction = new __TapAction(%s);""" 37 % (done_callback)) 38 39 def HasElementSelector(self): 40 return (self.element_function is not None or self.selector is not None or 41 self.text is not None) 42 43 def RunAction(self, tab): 44 if not self.HasElementSelector(): 45 self.element_function = 'document.body' 46 gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab) 47 48 tap_cmd = (''' 49 window.__tapAction.start({ 50 element: element, 51 left_position_percentage: %s, 52 top_position_percentage: %s, 53 duration_ms: %s, 54 gesture_source_type: %s 55 });''' 56 % (self.left_position_percentage, 57 self.top_position_percentage, 58 self.duration_ms, 59 gesture_source_type)) 60 code = ''' 61 function(element, errorMsg) { 62 if (!element) { 63 throw Error('Cannot find element: ' + errorMsg); 64 } 65 %s; 66 }''' % tap_cmd 67 68 page_action.EvaluateCallbackWithElement( 69 tab, code, selector=self.selector, text=self.text, 70 element_function=self.element_function) 71 tab.WaitForJavaScriptExpression('window.__tapActionDone', 60) 72