Debian Codegraph @

src/pyj/read_book/touch.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from gettext import gettext as _
6
7 from read_book.globals import get_boss, ltr_page_progression, ui_operations
8 from read_book.settings import opts
9 from read_book.viewport import get_unit_size_in_pixels, scroll_viewport
10
11 HOLD_THRESHOLD = 750 # milliseconds
12 TAP_THRESHOLD = 8 # pixels
13 SWIPE_THRESHOLD = 64 # pixels
14 TAP_LINK_THRESHOLD = 5 # pixels
15 PINCH_THRESHOLD = 20 # pixels
16 GESTURE = {k: k for k in v"""[
17 'back_zone_tap',
18 'forward_zone_tap',
19 'control_zone_tap',
20 'long_tap',
21 'two_finger_tap',
22 'pinch_in',
23 'pinch_out',
24
25 'flick_inline_backward',
26 'flick_inline_forward',
27 'flick_block_backward',
28 'flick_block_forward',
29
30 'swipe_inline_backward_in_progress',
31 'swipe_inline_forward_in_progress',
32 'swipe_block_backward_in_progress',
33 'swipe_block_forward_in_progress',
34
35 'swipe_inline_backward_hold',
36 'swipe_inline_forward_hold',
37 'swipe_block_backward_hold',
38 'swipe_block_forward_hold',
39
40 'tap',
41 'swipe',
42 'pinch',
43 ]"""}
44
45
46 def GESTURE_NAMES():
47 ans = GESTURE_NAMES.ans
48 if not ans:
49 GESTURE_NAMES.ans = ans = {
50 'back_zone_tap': _('Tap on back zone'),
51 'forward_zone_tap': _('Tap on forward zone'),
52 'control_zone_tap': _('Tap in the controls zone'),
53 'long_tap': _('Long tap'),
54 'two_finger_tap': _('Two finger tap'),
55 'pinch_in': _('Pinch in'),
56 'pinch_out': _('Pinch out'),
57 'flick_inline_backward': _('Flick in writing direction, to go back'),
58 'flick_inline_forward': _('Flick in writing direction, to go forward'),
59 'flick_block_backward': _('Flick perpendicular to writing direction, to go forward'),
60 'flick_block_forward': _('Flick perpendicular to writing direction, to go back'),
61 'swipe_inline_backward_in_progress': _('Drag finger in writing direction, to go back'),
62 'swipe_inline_forward_in_progress': _('Drag finger in writing direction, to go forward'),
63 'swipe_block_backward_in_progress': _('Drag finger perpendicular to writing direction, to go back'),
64 'swipe_block_forward_in_progress': _('Drag finger perpendicular to writing direction, to go forward'),
65 'swipe_inline_backward_hold': _('Drag and hold finger in writing direction, to go back'),
66 'swipe_inline_forward_hold': _('Drag and hold finger in writing direction, to go forward'),
67 'swipe_block_backward_hold': _('Drag and hold finger perpendicular to writing direction, to go back'),
68 'swipe_block_forward_hold': _('Drag and hold finger perpendicular to writing direction, to go forward'),
69 }
70 return ans
71
72 gesture_id = 0
73
74
75 def touch_id(touch):
76 # On Safari using touch.identifier as dict key yields a key of "NaN" for some reason
77 return touch.identifier + ''
78
79
80 def copy_touch(t):
81 now = window.performance.now()
82 return {
83 'identifier': touch_id(t),
84 'page_x': [t.pageX], 'page_y': [t.pageY], 'viewport_x': [t.clientX], 'viewport_y': [t.clientY],
85 'active': True, 'mtimes': [now], 'ctime': now, 'is_held': False, 'x_velocity': 0, 'y_velocity': 0
86 }
87
88
89 def update_touch(t, touch):
90 now = window.performance.now()
91 t.mtimes.push(now)
92 t.page_x.push(touch.pageX), t.page_y.push(touch.pageY)
93 t.viewport_x.push(touch.clientX), t.viewport_y.push(touch.clientY)
94
95
96 def max_displacement(points):
97 ans = 0
98 first = points[0]
99 if not first?:
100 return ans
101 for p in points:
102 delta = abs(p - first)
103 if delta > ans:
104 ans = delta
105 return ans
106
107
108 def interpret_single_gesture(touch, gesture_id):
109 max_x_displacement = max_displacement(touch.viewport_x)
110 max_y_displacement = max_displacement(touch.viewport_y)
111 ans = {'active': touch.active, 'is_held': touch.is_held, 'id': gesture_id, 'start_time': touch.ctime}
112 if max(max_x_displacement, max_y_displacement) < TAP_THRESHOLD:
113 ans.type = GESTURE.tap
114 ans.viewport_x = touch.viewport_x[0]
115 ans.viewport_y = touch.viewport_y[0]
116 return ans
117 if touch.viewport_y.length < 2:
118 return ans
119 delta_x = abs(touch.viewport_x[-1] - touch.viewport_x[0])
120 delta_y = abs(touch.viewport_y[-1] - touch.viewport_y[0])
121 max_disp = max(delta_y, delta_x)
122 if max_disp > SWIPE_THRESHOLD and min(delta_x, delta_y) / max_disp < 0.35:
123 ans.type = GESTURE.swipe
124 ans.axis = 'vertical' if delta_y > delta_x else 'horizontal'
125 ans.points = pts = touch.viewport_y if ans.axis is 'vertical' else touch.viewport_x
126 ans.times = touch.mtimes
127 positive = pts[-1] > pts[0]
128 if ans.axis is 'vertical':
129 ans.direction = 'down' if positive else 'up'
130 ans.velocity = touch.y_velocity
131 else:
132 ans.direction = 'right' if positive else 'left'
133 ans.velocity = touch.x_velocity
134 return ans
135 return ans
136
137
138 def interpret_double_gesture(touch1, touch2, gesture_id):
139 ans = {'active': touch1.active or touch2.active, 'is_held': touch1.is_held or touch2.is_held, 'id': gesture_id}
140 max_x_displacement1 = max_displacement(touch1.viewport_x)
141 max_x_displacement2 = max_displacement(touch2.viewport_x)
142 max_y_displacement1 = max_displacement(touch1.viewport_y)
143 max_y_displacement2 = max_displacement(touch2.viewport_y)
144 if max(max_x_displacement1, max_y_displacement1) < TAP_THRESHOLD and max(max_x_displacement2, max_y_displacement2) < TAP_THRESHOLD:
145 ans.type = GESTURE.two_finger_tap
146 ans.viewport_x1 = touch1.viewport_x[0]
147 ans.viewport_y1 = touch1.viewport_y[0]
148 ans.viewport_x2 = touch2.viewport_x[0]
149 ans.viewport_y2 = touch2.viewport_y[0]
150 return ans
151 initial_distance = Math.sqrt((touch1.viewport_x[0] - touch2.viewport_x[0]) ** 2 + (touch1.viewport_y[0] - touch2.viewport_y[0]) ** 2)
152 final_distance = Math.sqrt((touch1.viewport_x[-1] - touch2.viewport_x[-1]) ** 2 + (touch1.viewport_y[-1] - touch2.viewport_y[-1]) ** 2)
153 distance = abs(final_distance - initial_distance)
154 if distance > PINCH_THRESHOLD:
155 ans.type = GESTURE.pinch
156 ans.direction = 'in' if final_distance < initial_distance else 'out'
157 ans.distance = distance
158 return ans
159 return ans
160
161
162 def element_from_point(x, y):
163 # This does not currently support detecting links inside iframes, but since
164 # iframes are not common in books, I am going to ignore that for now
165 return document.elementFromPoint(x, y)
166
167
168 def find_link(x, y):
169 p = element_from_point(x, y)
170 while p:
171 if p.tagName and p.tagName.toLowerCase() is 'a' and p.hasAttribute('href'):
172 return p
173 p = p.parentNode
174
175
176 def tap_on_link(gesture):
177 for delta_x in [0, TAP_LINK_THRESHOLD, -TAP_LINK_THRESHOLD]:
178 for delta_y in [0, TAP_LINK_THRESHOLD, -TAP_LINK_THRESHOLD]:
179 x = gesture.viewport_x + delta_x
180 y = gesture.viewport_y + delta_y
181 link = find_link(x, y)
182 if link:
183 link.click()
184 return True
185 return False
186
187
188 class TouchHandler:
189 def __init__(self):
190 self.ongoing_touches = {}
191 self.gesture_id = None
192 self.hold_timer = None
193 self.handled_tap_hold = False
194
195 def prune_expired_touches(self):
196 now = window.performance.now()
197 expired = []
198 for tid in self.ongoing_touches:
199 t = self.ongoing_touches[tid]
200 if t.active:
201 if now - t.mtimes[-1] > 3000:
202 expired.push(touch_id(t))
203 for tid in expired:
204 v'delete self.ongoing_touches[tid]'
205
206 @property
207 def has_active_touches(self):
208 for tid in self.ongoing_touches:
209 t = self.ongoing_touches[tid]
210 if t.active:
211 return True
212 return False
213
214 def reset_handlers(self):
215 self.stop_hold_timer()
216 self.ongoing_touches = {}
217 self.gesture_id = None
218 self.handled_tap_hold = False
219
220 def start_hold_timer(self):
221 self.stop_hold_timer()
222 self.hold_timer = window.setTimeout(self.check_for_hold, 50)
223
224 def stop_hold_timer(self):
225 if self.hold_timer is not None:
226 window.clearTimeout(self.hold_timer)
227 self.hold_timer = None
228
229 def check_for_hold(self):
230 if len(self.ongoing_touches) > 0:
231 now = window.performance.now()
232 found_hold = False
233 for touchid in self.ongoing_touches:
234 touch = self.ongoing_touches[touchid]
235 if touch.active and now - touch.mtimes[-1] > HOLD_THRESHOLD:
236 touch.is_held = True
237 found_hold = True
238 if found_hold:
239 self.dispatch_gesture()
240 self.start_hold_timer()
241
242 def handle_touchstart(self, ev):
243 if jstype(ev.cancelable) is not 'boolean' or ev.cancelable:
244 ev.preventDefault()
245 ev.stopPropagation()
246 self.prune_expired_touches()
247 for touch in ev.changedTouches:
248 self.ongoing_touches[touch_id(touch)] = copy_touch(touch)
249 if self.gesture_id is None:
250 nonlocal gesture_id
251 gesture_id += 1
252 self.gesture_id = gesture_id
253 self.handled_tap_hold = False
254 if len(self.ongoing_touches) > 0:
255 self.start_hold_timer()
256
257 def handle_touchmove(self, ev):
258 if jstype(ev.cancelable) is not 'boolean' or ev.cancelable:
259 ev.preventDefault()
260 ev.stopPropagation()
261 for touch in ev.changedTouches:
262 t = self.ongoing_touches[touch_id(touch)]
263 if t:
264 update_touch(t, touch)
265 self.dispatch_gesture()
266
267 def handle_touchend(self, ev):
268 if jstype(ev.cancelable) is not 'boolean' or ev.cancelable:
269 ev.preventDefault()
270 ev.stopPropagation()
271 for touch in ev.changedTouches:
272 t = self.ongoing_touches[touch_id(touch)]
273 if t:
274 t.active = False
275 update_touch(t, touch)
276 self.prune_expired_touches()
277 if not self.has_active_touches:
278 self.dispatch_gesture()
279 self.reset_handlers()
280
281 def handle_touchcancel(self, ev):
282 if jstype(ev.cancelable) is not 'boolean' or ev.cancelable:
283 ev.preventDefault()
284 ev.stopPropagation()
285 for touch in ev.changedTouches:
286 tid = touch_id(touch) # noqa: unused-local
287 v'delete self.ongoing_touches[tid]'
288 self.gesture_id = None
289 self.handled_tap_hold = False
290
291 def dispatch_gesture(self):
292 touches = self.ongoing_touches
293 num = len(touches)
294 gesture = {}
295 if num is 1:
296 gesture = interpret_single_gesture(touches[Object.keys(touches)[0]], self.gesture_id)
297 elif num is 2:
298 t = Object.keys(touches)
299 gesture = interpret_double_gesture(touches[t[0]], touches[t[1]], self.gesture_id)
300 if not gesture?.type:
301 return
302 self.handle_gesture(gesture)
303
304
305 def inch_in_pixels():
306 ans = inch_in_pixels.ans
307 if not ans:
308 ans = inch_in_pixels.ans = max(2, get_unit_size_in_pixels('in'))
309 return ans
310
311
312 class BookTouchHandler(TouchHandler):
313 def __init__(self, for_side_margin=None):
314 self.for_side_margin = for_side_margin
315 TouchHandler.__init__(self)
316
317 def handle_gesture(self, gesture):
318 if gesture.type is GESTURE.tap:
319 if gesture.is_held:
320 if not self.for_side_margin and not self.handled_tap_hold and window.performance.now() - gesture.start_time >= HOLD_THRESHOLD:
321 self.handled_tap_hold = True
322 gesture.type = GESTURE.long_tap
323 get_boss().handle_gesture(gesture)
324 return
325 if not gesture.active:
326 if self.for_side_margin or not tap_on_link(gesture):
327 inch = inch_in_pixels()
328 if gesture.viewport_y < min(100, scroll_viewport.height() / 4):
329 gesture.type = GESTURE.control_zone_tap
330 else:
331 limit = inch
332 # default, books that go left to right.
333 if ltr_page_progression() and not opts.reverse_page_turn_zones:
334 if gesture.viewport_x < min(limit, scroll_viewport.width() / 4):
335 gesture.type = GESTURE.back_zone_tap
336 else:
337 gesture.type = GESTURE.forward_zone_tap
338 # We swap the sizes in RTL mode, so that going to the next page is always the bigger touch region.
339 else:
340 # The "going back" area should not be more than limit units big,
341 # even if 1/4 of the scroll viewport is more than limit units.
342 # Checking against the larger of the width minus the limit units and 3/4 of the width will accomplish that.
343 if gesture.viewport_x > max(scroll_viewport.width() - limit, scroll_viewport.width() * (3 / 4)):
344 gesture.type = GESTURE.back_zone_tap
345 else:
346 gesture.type = GESTURE.forward_zone_tap
347 elif gesture.type is GESTURE.pinch:
348 if gesture.active:
349 return
350 gesture.type = GESTURE.pinch_in if gesture.direction is 'in' else GESTURE.pinch_out
351 elif gesture.type is GESTURE.two_finger_tap:
352 if gesture.active:
353 return
354 elif gesture.type is 'swipe':
355 backward_dir = 'down' if gesture.axis is 'vertical' else ('right' if ltr_page_progression() else 'left')
356 direction = 'backward' if gesture.direction is backward_dir else 'forward'
357 inline_dir = 'vertical' if scroll_viewport.vertical_writing_mode else 'horizontal'
358 axis = 'inline' if gesture.axis is inline_dir else 'block'
359 if gesture.active:
360 gesture.type = GESTURE[f'swipe_{axis}_{direction}' + ('_hold' if gesture.is_held else '_in_progress')]
361 elif not gesture.is_held:
362 gesture.type = GESTURE[f'flick_{axis}_{direction}']
363 if self.for_side_margin:
364 ui_operations.forward_gesture(gesture)
365 else:
366 get_boss().handle_gesture(gesture)
367
368 def __repr__(self):
369 return 'BookTouchHandler:for_side_margin:' + self.for_side_margin
370
371 main_touch_handler = BookTouchHandler()
372 left_margin_handler = BookTouchHandler('left')
373 right_margin_handler = BookTouchHandler('right')
374
375
376 def install_handlers(elem, handler, passive):
377 options = {'capture': True, 'passive': v'!!passive'}
378 elem.addEventListener('touchstart', handler.handle_touchstart, options)
379 elem.addEventListener('touchmove', handler.handle_touchmove, options)
380 elem.addEventListener('touchend', handler.handle_touchend, options)
381 elem.addEventListener('touchcancel', handler.handle_touchcancel, options)
382
383
384 def create_handlers():
385 # Safari does not work if we register the handler
386 # on window instead of document
387 install_handlers(document, main_touch_handler)
388 # See https://github.com/kovidgoyal/calibre/pull/1101
389 # for why we need touchAction none
390 document.body.style.touchAction = 'none'
391
392
393 def reset_handlers():
394 main_touch_handler.reset_handlers()
395
396
397 def set_left_margin_handler(elem):
398 install_handlers(elem, left_margin_handler)
399
400
401 def set_right_margin_handler(elem):
402 install_handlers(elem, right_margin_handler)