Debian Codegraph @

tests/autopilot/lomiri_keyboard/emulators/keyboard.py

raw
1 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
2 #
3 # Lomiri Keyboard Test Suite
4 # Copyright (C) 2013, 2015 Canonical
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 from collections import defaultdict
21
22 from lomiri_keyboard.emulators.keypad import KeyPad
23
24 from time import sleep
25 import logging
26 import os
27
28 import lomiriuitoolkit as toolkit
29 from autopilot.input import Pointer, Touch
30 from autopilot.introspection import (
31 get_proxy_object_for_existing_process,
32 ProcessSearchError
33 )
34 from autopilot.introspection.dbus import StateNotFoundError
35
36
37 logger = logging.getLogger(__name__)
38
39
40 class KeyboardState:
41 character = "CHARACTERS"
42 symbol = "SYMBOLS"
43
44
45 class Keyboard(object):
46 """Emulator that provides the OSK as an input backend."""
47
48 _action_to_label = {
49 'SHIFT': 'shift',
50 '\b': 'backspace',
51 'ABC': 'symbols',
52 '?123': 'symbols',
53 ' ': 'space',
54 '\n': 'return',
55 'Enter': 'return',
56 'Backspace': 'backspace',
57 'Space': 'space',
58 'Shift': 'shift',
59 }
60
61 __maliit = None
62
63 def __init__(self, pointer=None):
64 try:
65 self.keyboard = self.maliit.select_single(
66 "QQuickItem",
67 objectName="lomiriKeyboard"
68 )
69 except ValueError as e:
70 e.args += (
71 "There was more than one Keyboard object found, aborting.",
72 )
73 raise
74 except StateNotFoundError:
75 logger.error(
76 "Unable to find the Lomiri Keyboard object within the "
77 "maliit server, aborting."
78 )
79 raise
80
81 self._keyboard_container = self.keyboard.select_single(
82 "KeyboardContainer"
83 )
84
85 self._stored_active_keypad_name = None
86 self._active_keypad = None
87
88 self._keys_position = defaultdict(dict)
89 self._keys_contained = defaultdict(dict)
90
91 if pointer is None:
92 self.pointer = Pointer(Touch.create())
93 else:
94 self.pointer = pointer
95
96 @property
97 def maliit(self):
98 # We cache __mallit_server as a class attribute because
99 # get_proxy_object_for_existing_process clears backends for proxy
100 # objects, this means that if this is called twice within a test the
101 # first keyboard object created has now lost all its _Backends.
102 if Keyboard.__maliit is None:
103 try:
104 Keyboard.__maliit = get_proxy_object_for_existing_process(
105 connection_name='org.maliit.server',
106 emulator_base=toolkit.LomiriUIToolkitCustomProxyObjectBase
107 )
108
109 if Keyboard.__maliit is None:
110 raise RuntimeError("Maliit Server could not be found.")
111 except ProcessSearchError as e:
112 e.args += (
113 "Unable to find maliit-server dbus object. Has it been "
114 "started with introspection enabled?",
115 )
116 raise
117 return Keyboard.__maliit
118
119 def dismiss(self):
120 """Swipe the keyboard down to hide it.
121
122 :raises: *AssertionError* if the state.wait_for fails meaning that the
123 keyboard failed to hide.
124
125 """
126 if self.is_available():
127 x, y, h, w = self._keyboard_container.globalRect
128 x_pos = int(w / 2)
129 start_y = y + int(h / 2.5)
130 end_y = y + h
131 self.pointer.drag(x_pos, start_y, x_pos, end_y)
132
133 self.keyboard.state.wait_for("HIDDEN")
134
135 def is_available(self):
136 """Returns true if the keyboard is shown and ready to use."""
137 return (self.keyboard.state == "SHOWN")
138
139 # Much like is_available, but attempts to wait for the keyboard to be
140 # ready.
141 def wait_for_keyboard_ready(self, timeout=10):
142 """Waits for *timeout* for the keyboard to be ready and returns
143 true. Returns False if the keyboard fails to be considered ready within
144 the alloted time.
145
146 """
147 try:
148 self.keyboard.state.wait_for("SHOWN", timeout=timeout)
149 return True
150 except AssertionError:
151 return False
152
153 def press_key(self, key, capslock_switch=False, long_press=False,
154 slide_offset=None):
155 """Tap on the key with the internal pointer
156
157 :params key: String containing the text of the key to tap.
158
159 :raises: *RuntimeError* if the keyboard is not available and thus not
160 ready to be used.
161 :raises: *ValueError* if the supplied key cannot be found on any of
162 the the current keyboards layouts.
163 """
164 if not self.is_available():
165 raise RuntimeError("Keyboard is not on screen")
166
167 key = self._translate_key(key)
168
169 req_keypad = KeyboardState.character
170 if capslock_switch:
171 req_key_state = "CAPSLOCK"
172 else:
173 req_key_state = self._keypad_contains_key(req_keypad, key)
174 if req_key_state is None:
175 req_keypad = KeyboardState.symbol
176 req_key_state = self._keypad_contains_key(req_keypad, key)
177
178 if req_key_state is None:
179 raise ValueError("Key '%s' was not found on the keyboard" % key)
180
181 key_pos = self._get_key_pos_from_keypad(req_keypad, key)
182 self._show_keypad(req_keypad)
183
184 # Don't attempt to automatically switch to a requested state if the
185 # test is manually pressing the shift key, as this will also change
186 # state.
187 if key != "shift":
188 self._change_keypad_to_state(req_key_state)
189
190 if slide_offset is not None:
191 self._select_extended_key(key_pos, slide_offset)
192 elif long_press:
193 self._long_press_key(key_pos)
194 else:
195 self._tap_key(key_pos)
196
197 def type(self, string, delay=0.1):
198 """Type the string *string* with a delay of *delay* between each key
199 press
200
201 .. note:: The delay provides a minimum delay, it may take longer
202 between each press as the keyboard shifts between states etc.
203
204 Only 'normal' or single characters can be typed this way.
205
206 :raises: *ValueError* if one of the the supplied keys cannot be
207 found on any of the the current keyboards layouts.
208
209 """
210 for char in string:
211 self.press_key(char)
212 sleep(delay)
213
214 def reset(self):
215 """Reconnect to the maliit process. This should be called by any tests
216 which restart unity8 (thus causing the maliit-server process to also
217 be restarted).
218 """
219 Keyboard.__maliit = None
220 # self.maliit is a dynamic property (using the @property decorator),
221 # so this is actually a function call to the maliit() function,
222 # which triggers the maliit reconnection.
223 self.maliit
224 self._keyboard_container = self.keyboard.select_single(
225 "KeyboardContainer"
226 )
227
228 @property
229 def current_state(self):
230 return self.keyboard.state
231
232 @property
233 def active_keypad_state(self):
234 return self._keyboard_container.activeKeypadState
235
236 @property
237 def active_keypad(self):
238 need_to_update = False
239 if self._active_keypad is None:
240 need_to_update = True
241 else:
242 try:
243 # Check if the current keypad object still exists.
244 self._active_keypad.enabled
245 except StateNotFoundError:
246 need_to_update = True
247
248 if (
249 need_to_update or
250 self._stored_active_keypad_name != self._current_keypad_name
251 ):
252 self._stored_active_keypad_name = self._current_keypad_name
253 logger.debug("Keypad lookup")
254 self._active_keypad = self._keypad_loader.select_single(KeyPad)
255 return self._active_keypad
256
257 def send_left_key(self):
258 self.maliit.select_single('Keyboard').slots.sendLeftKey()
259
260 def send_right_key(self):
261 self.maliit.select_single('Keyboard').slots.sendRightKey()
262
263 def send_up_key(self):
264 self.maliit.select_single('Keyboard').slots.sendUpKey()
265
266 def send_down_key(self):
267 self.maliit.select_single('Keyboard').slots.sendDownKey()
268
269 def send_home_key(self):
270 self.maliit.select_single('Keyboard').slots.sendHomeKey()
271
272 def send_end_key(self):
273 self.maliit.select_single('Keyboard').slots.sendEndKey()
274
275 @property
276 def _keypad_loader(self):
277 return self.maliit.select_single(
278 "QQuickLoader", objectName='characterKeyPadLoader')
279
280 @property
281 def _plugin_source(self):
282 return self._keypad_loader.source
283
284 @property
285 def _current_keypad_name(self):
286 return self._keyboard_container.state
287
288 def _update_details_for_keypad(self, keypad_name):
289 self._show_keypad(keypad_name)
290
291 contained, positions = self.active_keypad.get_key_details()
292 layout_state = self.keyboard.layoutId + self._keyboard_container.state
293 self._keys_contained[layout_state] = contained
294 self._keys_position[layout_state] = positions
295
296 def _keypad_contains_key(self, keypad_name, key):
297 """Returns the keypad state that key is found in.
298
299 Returns either a KeyPadState if the key is found on the provided keypad
300 or None if not found.
301
302 """
303 if self._keypad_details_expired(keypad_name):
304 self._update_details_for_keypad(keypad_name)
305
306 layout_state = self.keyboard.layoutId + keypad_name
307 return self._keys_contained[layout_state].get(key, None)
308
309 def _get_key_pos_from_keypad(self, keypad_name, key):
310 """Returns the position of the key if it is found on that keypad or
311 None if it is not.
312
313 """
314 if self._keypad_details_expired(keypad_name):
315 self._update_details_for_keypad(keypad_name)
316
317 layout_state = self.keyboard.layoutId + keypad_name
318 return self._keys_position[layout_state].get(key, None)
319
320 def _show_keypad(self, keypad_name):
321 if self._current_keypad_name == keypad_name:
322 return
323
324 key_pos = self._get_key_pos_from_keypad(
325 self._current_keypad_name,
326 "symbols"
327 )
328 self._tap_key(key_pos)
329 self._current_keypad_name.wait_for(keypad_name)
330 self.active_keypad.opacity.wait_for(1.0)
331
332 def _change_keypad_to_state(self, state):
333 if self._keyboard_container.activeKeypadState == state:
334 return
335
336 key_pos = self._get_key_pos_from_keypad(
337 self._current_keypad_name,
338 "shift"
339 )
340
341 if key_pos is None:
342 # Not all layouts have a shift key
343 return
344
345 self._tap_key(key_pos)
346 self._keyboard_container.activeKeypadState.wait_for(state)
347 self.active_keypad.opacity.wait_for(1.0)
348
349 def _tap_key(self, key_rect, pointer=None):
350 if pointer is None:
351 pointer = Pointer(Touch.create())
352 pointer.click_object(key_rect)
353
354 def _long_press_key(self, key_rect, pointer=None):
355 if pointer is None:
356 pointer = Pointer(Touch.create())
357 pointer.move(
358 key_rect.x + key_rect.w / 2.0, key_rect.y + key_rect.h / 2.0)
359 pointer.press()
360 sleep(0.5)
361 pointer.release()
362
363 def _select_extended_key(self, key_rect, offset, pointer=None):
364 if pointer is None:
365 pointer = Pointer(Touch.create())
366
367 gu = float(os.environ.get('GRID_UNIT_PX', 8))
368
369 pointer.drag(
370 key_rect.x + key_rect.w / 2.0,
371 key_rect.y + key_rect.h / 2.0,
372 key_rect.x + key_rect.w / 2.0 + offset,
373 key_rect.y + key_rect.h / 2.0,
374 rate=2.77 * gu, time_between_events=2)
375
376 def _keypad_details_expired(self, keypad_name):
377 layout_state = self.keyboard.layoutId + keypad_name
378 return (
379 self._keys_contained.get(layout_state) is None
380 )
381
382 def _translate_key(self, label):
383 """Get the label for a 'special key' (i.e. space) so that it can be
384 addressed and clicked.
385
386 """
387 return Keyboard._action_to_label.get(label, label)