How to use focus method in Playwright Python

Best Python code snippet using playwright-python

Focus.js

Source:Focus.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow8 */9import type {10 ReactDOMResponderEvent,11 ReactDOMResponderContext,12 PointerType,13} from 'shared/ReactDOMTypes';14import type {ReactEventResponderListener} from 'shared/ReactTypes';15import * as React from 'react';16import {DiscreteEvent} from 'shared/ReactTypes';17/**18 * Types19 */20type FocusEvent = {|21 isTargetAttached: boolean,22 target: Element | Document,23 type: FocusEventType | FocusWithinEventType,24 pointerType: PointerType,25 timeStamp: number,26 continuePropagation: () => void,27|};28type FocusState = {29 detachedTarget: null | Element | Document,30 focusTarget: null | Element | Document,31 isFocused: boolean,32 isFocusVisible: boolean,33 pointerType: PointerType,34 addedRootEvents?: boolean,35};36type FocusProps = {37 disabled: boolean,38 onBlur: (e: FocusEvent) => void,39 onFocus: (e: FocusEvent) => void,40 onFocusChange: boolean => void,41 onFocusVisibleChange: boolean => void,42 ...43};44type FocusEventType = 'focus' | 'blur' | 'focuschange' | 'focusvisiblechange';45type FocusWithinProps = {46 disabled?: boolean,47 onFocusWithin?: (e: FocusEvent) => void,48 onBeforeBlurWithin?: (e: FocusEvent) => void,49 onBlurWithin?: (e: FocusEvent) => void,50 onFocusWithinChange?: boolean => void,51 onFocusWithinVisibleChange?: boolean => void,52 ...53};54type FocusWithinEventType =55 | 'focuswithinvisiblechange'56 | 'focuswithinchange'57 | 'blurwithin'58 | 'focuswithin'59 | 'beforeblurwithin';60/**61 * Shared between Focus and FocusWithin62 */63let isGlobalFocusVisible = true;64let hasTrackedGlobalFocusVisible = false;65let globalFocusVisiblePointerType = '';66let isEmulatingMouseEvents = false;67const isMac =68 typeof window !== 'undefined' && window.navigator != null69 ? /^Mac/.test(window.navigator.platform)70 : false;71let passiveBrowserEventsSupported = false;72const canUseDOM: boolean = !!(73 typeof window !== 'undefined' &&74 typeof window.document !== 'undefined' &&75 typeof window.document.createElement !== 'undefined'76);77// Check if browser support events with passive listeners78// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support79if (canUseDOM) {80 try {81 const options = {};82 // $FlowFixMe: Ignore Flow complaining about needing a value83 Object.defineProperty(options, 'passive', {84 get: function() {85 passiveBrowserEventsSupported = true;86 },87 });88 window.addEventListener('test', options, options);89 window.removeEventListener('test', options, options);90 } catch (e) {91 passiveBrowserEventsSupported = false;92 }93}94const hasPointerEvents =95 typeof window !== 'undefined' && window.PointerEvent != null;96const focusVisibleEvents = hasPointerEvents97 ? ['keydown', 'keyup', 'pointermove', 'pointerdown', 'pointerup']98 : ['keydown', 'keyup', 'mousedown', 'touchmove', 'touchstart', 'touchend'];99const targetEventTypes = ['focus', 'blur', 'beforeblur', ...focusVisibleEvents];100// Used only for the blur "detachedTarget" logic101const rootEventTypes = ['blur'];102function addWindowEventListener(types, callback, options) {103 types.forEach(type => {104 window.addEventListener(type, callback, options);105 });106}107function trackGlobalFocusVisible() {108 if (!hasTrackedGlobalFocusVisible) {109 hasTrackedGlobalFocusVisible = true;110 addWindowEventListener(111 focusVisibleEvents,112 handleGlobalFocusVisibleEvent,113 passiveBrowserEventsSupported ? {capture: true, passive: true} : true,114 );115 }116}117function handleGlobalFocusVisibleEvent(118 nativeEvent: MouseEvent | TouchEvent | KeyboardEvent,119): void {120 const {type} = nativeEvent;121 switch (type) {122 case 'pointermove':123 case 'pointerdown':124 case 'pointerup': {125 isGlobalFocusVisible = false;126 globalFocusVisiblePointerType = (nativeEvent: any).pointerType;127 break;128 }129 case 'keydown':130 case 'keyup': {131 const {metaKey, altKey, ctrlKey} = nativeEvent;132 const validKey = !(metaKey || (!isMac && altKey) || ctrlKey);133 if (validKey) {134 globalFocusVisiblePointerType = 'keyboard';135 isGlobalFocusVisible = true;136 }137 break;138 }139 // fallbacks for no PointerEvent support140 case 'touchmove':141 case 'touchstart':142 case 'touchend': {143 isEmulatingMouseEvents = true;144 isGlobalFocusVisible = false;145 globalFocusVisiblePointerType = 'touch';146 break;147 }148 case 'mousedown': {149 if (!isEmulatingMouseEvents) {150 isGlobalFocusVisible = false;151 globalFocusVisiblePointerType = 'mouse';152 } else {153 isEmulatingMouseEvents = false;154 }155 break;156 }157 }158}159function isFunction(obj): boolean {160 return typeof obj === 'function';161}162function createFocusEvent(163 context: ReactDOMResponderContext,164 type: FocusEventType | FocusWithinEventType,165 target: Element | Document,166 pointerType: PointerType,167 isTargetAttached: boolean,168): FocusEvent {169 return {170 isTargetAttached,171 target,172 type,173 pointerType,174 timeStamp: context.getTimeStamp(),175 // We don't use stopPropagation, as the default behavior176 // is to not propagate. Plus, there might be confusion177 // using stopPropagation as we don't actually stop178 // native propagation from working, but instead only179 // allow propagation to the others keyboard responders.180 continuePropagation() {181 context.continuePropagation();182 },183 };184}185function handleFocusVisibleTargetEvent(186 event: ReactDOMResponderEvent,187 context: ReactDOMResponderContext,188 state: FocusState,189 callback: boolean => void,190): void {191 const {type} = event;192 isGlobalFocusVisible = false;193 // Focus should stop being visible if a pointer is used on the element194 // after it was focused using a keyboard.195 const focusTarget = state.focusTarget;196 if (197 focusTarget !== null &&198 (type === 'mousedown' || type === 'touchstart' || type === 'pointerdown')199 ) {200 callback(false);201 }202}203function handleFocusVisibleTargetEvents(204 event: ReactDOMResponderEvent,205 context: ReactDOMResponderContext,206 state: FocusState,207 callback: boolean => void,208): void {209 const {type} = event;210 state.pointerType = globalFocusVisiblePointerType;211 switch (type) {212 case 'pointermove':213 case 'pointerdown':214 case 'pointerup': {215 handleFocusVisibleTargetEvent(event, context, state, callback);216 break;217 }218 case 'keydown':219 case 'keyup': {220 const nativeEvent = event.nativeEvent;221 const focusTarget = state.focusTarget;222 const {metaKey, altKey, ctrlKey} = (nativeEvent: any);223 const validKey = !(metaKey || (!isMac && altKey) || ctrlKey);224 if (validKey) {225 if (focusTarget !== null) {226 callback(true);227 }228 }229 break;230 }231 // fallbacks for no PointerEvent support232 case 'touchmove':233 case 'touchstart':234 case 'touchend': {235 handleFocusVisibleTargetEvent(event, context, state, callback);236 break;237 }238 case 'mousedown': {239 if (!isEmulatingMouseEvents) {240 handleFocusVisibleTargetEvent(event, context, state, callback);241 }242 break;243 }244 }245}246/**247 * Focus Responder248 */249function dispatchFocusEvents(250 context: ReactDOMResponderContext,251 props: FocusProps,252 state: FocusState,253) {254 const pointerType = state.pointerType;255 const target = ((state.focusTarget: any): Element | Document);256 const onFocus = props.onFocus;257 if (isFunction(onFocus)) {258 const syntheticEvent = createFocusEvent(259 context,260 'focus',261 target,262 pointerType,263 true,264 );265 context.dispatchEvent(syntheticEvent, onFocus, DiscreteEvent);266 }267 dispatchFocusChange(context, props, true);268 if (state.isFocusVisible) {269 dispatchFocusVisibleChangeEvent(context, props, true);270 }271}272function dispatchBlurEvents(273 context: ReactDOMResponderContext,274 props: FocusProps,275 state: FocusState,276) {277 const pointerType = state.pointerType;278 const target = ((state.focusTarget: any): Element | Document);279 const onBlur = props.onBlur;280 if (isFunction(onBlur)) {281 const syntheticEvent = createFocusEvent(282 context,283 'blur',284 target,285 pointerType,286 true,287 );288 context.dispatchEvent(syntheticEvent, onBlur, DiscreteEvent);289 }290 dispatchFocusChange(context, props, false);291 if (state.isFocusVisible) {292 dispatchFocusVisibleChangeEvent(context, props, false);293 }294}295function dispatchFocusWithinEvents(296 context: ReactDOMResponderContext,297 event: ReactDOMResponderEvent,298 props: FocusWithinProps,299 state: FocusState,300) {301 const pointerType = state.pointerType;302 const target = ((state.focusTarget: any): Element | Document) || event.target;303 const onFocusWithin = (props.onFocusWithin: any);304 if (isFunction(onFocusWithin)) {305 const syntheticEvent = createFocusEvent(306 context,307 'focuswithin',308 target,309 pointerType,310 true,311 );312 context.dispatchEvent(syntheticEvent, onFocusWithin, DiscreteEvent);313 }314}315function dispatchBlurWithinEvents(316 context: ReactDOMResponderContext,317 event: ReactDOMResponderEvent,318 props: FocusWithinProps,319 state: FocusState,320) {321 const pointerType = state.pointerType;322 const target = ((state.focusTarget: any): Element | Document) || event.target;323 const onBlurWithin = (props.onBlurWithin: any);324 const isTargetAttached = state.detachedTarget === null;325 if (isFunction(onBlurWithin)) {326 const syntheticEvent = createFocusEvent(327 context,328 'blurwithin',329 target,330 pointerType,331 isTargetAttached,332 );333 context.dispatchEvent(syntheticEvent, onBlurWithin, DiscreteEvent);334 }335}336function dispatchFocusChange(337 context: ReactDOMResponderContext,338 props: FocusProps,339 value: boolean,340): void {341 const onFocusChange = props.onFocusChange;342 if (isFunction(onFocusChange)) {343 context.dispatchEvent(value, onFocusChange, DiscreteEvent);344 }345}346function dispatchFocusVisibleChangeEvent(347 context: ReactDOMResponderContext,348 props: FocusProps,349 value: boolean,350) {351 const onFocusVisibleChange = props.onFocusVisibleChange;352 if (isFunction(onFocusVisibleChange)) {353 context.dispatchEvent(value, onFocusVisibleChange, DiscreteEvent);354 }355}356function unmountFocusResponder(357 context: ReactDOMResponderContext,358 props: FocusProps,359 state: FocusState,360) {361 if (state.isFocused) {362 dispatchBlurEvents(context, props, state);363 }364}365const focusResponderImpl = {366 targetEventTypes,367 targetPortalPropagation: true,368 getInitialState(): FocusState {369 return {370 detachedTarget: null,371 focusTarget: null,372 isFocused: false,373 isFocusVisible: false,374 pointerType: '',375 addedRootEvents: false,376 };377 },378 onMount() {379 trackGlobalFocusVisible();380 },381 onEvent(382 event: ReactDOMResponderEvent,383 context: ReactDOMResponderContext,384 props: FocusProps,385 state: FocusState,386 ): void {387 const {type, target} = event;388 if (props.disabled) {389 if (state.isFocused) {390 dispatchBlurEvents(context, props, state);391 state.isFocused = false;392 state.focusTarget = null;393 }394 return;395 }396 switch (type) {397 case 'focus': {398 state.focusTarget = context.getResponderNode();399 // Limit focus events to the direct child of the event component.400 // Browser focus is not expected to bubble.401 if (!state.isFocused && state.focusTarget === target) {402 state.isFocused = true;403 state.isFocusVisible = isGlobalFocusVisible;404 dispatchFocusEvents(context, props, state);405 }406 isEmulatingMouseEvents = false;407 break;408 }409 case 'blur': {410 if (state.isFocused) {411 dispatchBlurEvents(context, props, state);412 state.isFocusVisible = isGlobalFocusVisible;413 state.isFocused = false;414 }415 // This covers situations where focus is lost to another document in416 // the same window (e.g., iframes). Any action that restores focus to417 // the document (e.g., touch or click) first causes 'focus' to be418 // dispatched, which means the 'pointerType' we provide is stale419 // (it reflects the *previous* pointer). We cannot determine the420 // 'pointerType' in this case, so a blur with no421 // relatedTarget is used as a signal to reset the 'pointerType'.422 if (event.nativeEvent.relatedTarget == null) {423 state.pointerType = '';424 }425 isEmulatingMouseEvents = false;426 break;427 }428 default:429 handleFocusVisibleTargetEvents(430 event,431 context,432 state,433 isFocusVisible => {434 if (state.isFocused && state.isFocusVisible !== isFocusVisible) {435 state.isFocusVisible = isFocusVisible;436 dispatchFocusVisibleChangeEvent(context, props, isFocusVisible);437 }438 },439 );440 }441 },442 onUnmount(443 context: ReactDOMResponderContext,444 props: FocusProps,445 state: FocusState,446 ) {447 unmountFocusResponder(context, props, state);448 },449};450export const FocusResponder = React.DEPRECATED_createResponder(451 'Focus',452 focusResponderImpl,453);454export function useFocus(455 props: FocusProps,456): ReactEventResponderListener<any, any> {457 return React.DEPRECATED_useResponder(FocusResponder, props);458}459/**460 * FocusWithin Responder461 */462function dispatchFocusWithinChangeEvent(463 context: ReactDOMResponderContext,464 props: FocusWithinProps,465 state: FocusState,466 value: boolean,467) {468 const onFocusWithinChange = (props.onFocusWithinChange: any);469 if (isFunction(onFocusWithinChange)) {470 context.dispatchEvent(value, onFocusWithinChange, DiscreteEvent);471 }472 if (state.isFocusVisible) {473 dispatchFocusWithinVisibleChangeEvent(context, props, state, value);474 }475}476function dispatchFocusWithinVisibleChangeEvent(477 context: ReactDOMResponderContext,478 props: FocusWithinProps,479 state: FocusState,480 value: boolean,481) {482 const onFocusWithinVisibleChange = (props.onFocusWithinVisibleChange: any);483 if (isFunction(onFocusWithinVisibleChange)) {484 context.dispatchEvent(value, onFocusWithinVisibleChange, DiscreteEvent);485 }486}487function unmountFocusWithinResponder(488 context: ReactDOMResponderContext,489 props: FocusWithinProps,490 state: FocusState,491) {492 if (state.isFocused) {493 dispatchFocusWithinChangeEvent(context, props, state, false);494 }495}496const focusWithinResponderImpl = {497 targetEventTypes,498 targetPortalPropagation: true,499 getInitialState(): FocusState {500 return {501 detachedTarget: null,502 focusTarget: null,503 isFocused: false,504 isFocusVisible: false,505 pointerType: '',506 };507 },508 onMount() {509 trackGlobalFocusVisible();510 },511 onEvent(512 event: ReactDOMResponderEvent,513 context: ReactDOMResponderContext,514 props: FocusWithinProps,515 state: FocusState,516 ): void {517 const {nativeEvent, type} = event;518 const relatedTarget = (nativeEvent: any).relatedTarget;519 if (props.disabled) {520 if (state.isFocused) {521 dispatchFocusWithinChangeEvent(context, props, state, false);522 state.isFocused = false;523 state.focusTarget = null;524 }525 return;526 }527 switch (type) {528 case 'focus': {529 state.focusTarget = context.getResponderNode();530 // Limit focus events to the direct child of the event component.531 // Browser focus is not expected to bubble.532 if (!state.isFocused) {533 state.isFocused = true;534 state.isFocusVisible = isGlobalFocusVisible;535 dispatchFocusWithinChangeEvent(context, props, state, true);536 }537 if (!state.isFocusVisible && isGlobalFocusVisible) {538 state.isFocusVisible = isGlobalFocusVisible;539 dispatchFocusWithinVisibleChangeEvent(context, props, state, true);540 }541 dispatchFocusWithinEvents(context, event, props, state);542 break;543 }544 case 'blur': {545 if (546 state.isFocused &&547 !context.isTargetWithinResponder(relatedTarget)548 ) {549 dispatchFocusWithinChangeEvent(context, props, state, false);550 dispatchBlurWithinEvents(context, event, props, state);551 state.isFocused = false;552 }553 break;554 }555 case 'beforeblur': {556 const onBeforeBlurWithin = (props.onBeforeBlurWithin: any);557 if (isFunction(onBeforeBlurWithin)) {558 const syntheticEvent = createFocusEvent(559 context,560 'beforeblurwithin',561 event.target,562 state.pointerType,563 true,564 );565 state.detachedTarget = event.target;566 context.dispatchEvent(567 syntheticEvent,568 onBeforeBlurWithin,569 DiscreteEvent,570 );571 if (!state.addedRootEvents) {572 state.addedRootEvents = true;573 context.addRootEventTypes(rootEventTypes);574 }575 } else {576 // We want to propagate to next focusWithin responder577 // if this responder doesn't handle beforeblur578 context.continuePropagation();579 }580 break;581 }582 default:583 handleFocusVisibleTargetEvents(584 event,585 context,586 state,587 isFocusVisible => {588 if (state.isFocused && state.isFocusVisible !== isFocusVisible) {589 state.isFocusVisible = isFocusVisible;590 dispatchFocusWithinVisibleChangeEvent(591 context,592 props,593 state,594 isFocusVisible,595 );596 }597 },598 );599 }600 },601 onRootEvent(602 event: ReactDOMResponderEvent,603 context: ReactDOMResponderContext,604 props: FocusWithinProps,605 state: FocusState,606 ): void {607 if (event.type === 'blur') {608 const detachedTarget = state.detachedTarget;609 if (detachedTarget !== null && detachedTarget === event.target) {610 dispatchBlurWithinEvents(context, event, props, state);611 state.detachedTarget = null;612 if (state.addedRootEvents) {613 state.addedRootEvents = false;614 context.removeRootEventTypes(rootEventTypes);615 }616 }617 }618 },619 onUnmount(620 context: ReactDOMResponderContext,621 props: FocusWithinProps,622 state: FocusState,623 ) {624 unmountFocusWithinResponder(context, props, state);625 },626};627export const FocusWithinResponder = React.DEPRECATED_createResponder(628 'FocusWithin',629 focusWithinResponderImpl,630);631export function useFocusWithin(632 props: FocusWithinProps,633): ReactEventResponderListener<any, any> {634 return React.DEPRECATED_useResponder(FocusWithinResponder, props);...

Full Screen

Full Screen

focus.py

Source:focus.py Github

copy

Full Screen

...134 grab_found = True135 if not grab_found:136 grab = None137 if (default_focus is not None) and (get_focused() is None):138 change_focus(default_focus, True)139def focus_coordinates():140 """141 :doc: other142 This attempts to find the coordinates of the currently-focused143 displayable. If it can, it will return them as a (x, y, w, h)144 tuple. If not, it will return a (None, None, None, None) tuple.145 """146 current = get_focused()147 for i in focus_list:148 if i.widget == current and i.arg == argument:149 return i.x, i.y, i.w, i.h150 return None, None, None, None151# A map from id(displayable) to the displayable that replaces it.152replaced_by = { }153def before_interact(roots):154 """155 Called before each interaction to choose the focused and grabbed156 displayables.157 """158 global new_grab159 global grab160 # a list of focusable, name, screen tuples.161 fwn = [ ]162 def callback(f, n):163 fwn.append((f, n, renpy.display.screen._current_screen))164 for root in roots:165 root.find_focusable(callback, None)166 # Assign a full name to each focusable.167 namecount = { }168 fwn2 = [ ]169 for fwn_tuple in fwn:170 f, n, screen = fwn_tuple171 serial = namecount.get(n, 0)172 namecount[n] = serial + 1173 if f is None:174 continue175 f.full_focus_name = n, serial176 replaced_by[id(f)] = f177 fwn2.append(fwn_tuple)178 fwn = fwn2179 # We assume id(None) is not in replaced_by.180 replaced_by.pop(None, None)181 # If there's something with the same full name as the current widget,182 # it becomes the new current widget.183 current = get_focused()184 current = replaced_by.get(id(current), current)185 if current is not None:186 current_name = current.full_focus_name187 for f, n, screen in fwn:188 if f.full_focus_name == current_name:189 current = f190 set_focused(f, argument, screen)191 break192 else:193 current = None194 # Otherwise, focus the default widget.195 if current is None:196 defaults = [ ]197 for f, n, screen in fwn:198 if f.default:199 defaults.append((f.default, f, screen))200 if defaults:201 if len(defaults) > 1:202 defaults.sort()203 _, f, screen = defaults[-1]204 current = f205 set_focused(f, None, screen)206 if current is None:207 set_focused(None, None, None)208 # Finally, mark the current widget as the focused widget, and209 # all other widgets as unfocused.210 for f, n, screen in fwn:211 if f is not current:212 renpy.display.screen.push_current_screen(screen)213 try:214 f.unfocus(default=True)215 finally:216 renpy.display.screen.pop_current_screen()217 if current:218 renpy.display.screen.push_current_screen(screen_of_focused)219 try:220 current.focus(default=True)221 finally:222 renpy.display.screen.pop_current_screen()223 # Update the grab.224 grab = replaced_by.get(id(grab), None)225 # Clear replaced_by.226 replaced_by.clear()227# This changes the focus to be the widget contained inside the new228# focus object.229def change_focus(newfocus, default=False):230 rv = None231 if grab:232 return233 if newfocus is None:234 widget = None235 else:236 widget = newfocus.widget237 current = get_focused()238 # Nothing to do.239 if current is widget and (newfocus is None or newfocus.arg == argument):240 return rv241 global focus_type242 focus_type = pending_focus_type243 if current is not None:244 try:245 renpy.display.screen.push_current_screen(screen_of_focused)246 current.unfocus(default=default)247 finally:248 renpy.display.screen.pop_current_screen()249 current = widget250 if newfocus is not None:251 set_focused(current, newfocus.arg, newfocus.screen)252 else:253 set_focused(None, None, None)254 if widget is not None:255 try:256 renpy.display.screen.push_current_screen(screen_of_focused)257 rv = widget.focus(default=default)258 finally:259 renpy.display.screen.pop_current_screen()260 return rv261def clear_focus():262 """263 Clears the focus when the window loses mouse focus.264 """265 change_focus(None)266# This handles mouse events, to see if they change the focus.267def mouse_handler(ev, x, y, default=False):268 """269 Handle mouse events, to see if they change the focus.270 `ev`271 If ev is not None, this function checks to see if it is a mouse event.272 """273 global pending_focus_type274 if ev is not None:275 if ev.type not in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN):276 return277 else:278 pending_focus_type = "mouse"279 new_focus = renpy.display.render.focus_at_point(x, y)280 if new_focus is None:281 new_focus = default_focus282 return change_focus(new_focus, default=default)283# This focuses an extreme widget, which is one of the widgets that's284# at an edge. To do this, we multiply the x, y, width, and height by285# the supplied multiplers, add them all up, and take the focus with286# the largest value.287def focus_extreme(xmul, ymul, wmul, hmul):288 max_focus = None289 max_score = -(65536**2)290 for f in focus_list:291 if f.x is None:292 continue293 score = (f.x * xmul +294 f.y * ymul +295 f.w * wmul +296 f.h * hmul)297 if score > max_score:298 max_score = score299 max_focus = f300 if max_focus:301 return change_focus(max_focus)302# This calculates the distance between two points, applying303# the given fudge factors. The distance is left squared.304def points_dist(x0, y0, x1, y1, xfudge, yfudge):305 return (( x0 - x1 ) * xfudge ) ** 2 + \306 (( y0 - y1 ) * yfudge ) ** 2307# This computes the distance between two horizontal lines. (So the308# distance is either vertical, or has a vertical component to it.)309#310# The distance is left squared.311def horiz_line_dist(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1):312 # The lines overlap in x.313 if bx0 <= ax0 <= ax1 <= bx1 or \314 ax0 <= bx0 <= bx1 <= ax1 or \315 ax0 <= bx0 <= ax1 <= bx1 or \316 bx0 <= ax0 <= bx1 <= ax1:317 return (ay0 - by0) ** 2318 # The right end of a is to the left of the left end of b.319 if ax0 <= ax1 <= bx0 <= bx1:320 return points_dist(ax1, ay1, bx0, by0, renpy.config.focus_crossrange_penalty, 1.0)321 else:322 return points_dist(ax0, ay0, bx1, by1, renpy.config.focus_crossrange_penalty, 1.0)323# This computes the distance between two vertical lines. (So the324# distance is either hortizontal, or has a horizontal component to it.)325#326# The distance is left squared.327def verti_line_dist(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1):328 # The lines overlap in x.329 if by0 <= ay0 <= ay1 <= by1 or \330 ay0 <= by0 <= by1 <= ay1 or \331 ay0 <= by0 <= ay1 <= by1 or \332 by0 <= ay0 <= by1 <= ay1:333 return (ax0 - bx0) ** 2334 # The right end of a is to the left of the left end of b.335 if ay0 <= ay1 <= by0 <= by1:336 return points_dist(ax1, ay1, bx0, by0, 1.0, renpy.config.focus_crossrange_penalty)337 else:338 return points_dist(ax0, ay0, bx1, by1, 1.0, renpy.config.focus_crossrange_penalty)339# This focuses the widget that is nearest to the current widget. To340# determine nearest, we compute points on the widgets using the341# {from,to}_{x,y}off values. We pick the nearest, applying a fudge342# multiplier to the distances in each direction, that satisfies343# the condition (which is given a Focus object to evaluate).344#345# If no focus can be found matching the above, we look for one346# with an x of None, and make that the focus. Otherwise, we do347# nothing.348#349# If no widget is focused, we pick one and focus it.350#351# If the current widget has an x of None, we pass things off to352# focus_extreme to deal with.353def focus_nearest(from_x0, from_y0, from_x1, from_y1,354 to_x0, to_y0, to_x1, to_y1,355 line_dist,356 condition,357 xmul, ymul, wmul, hmul):358 global pending_focus_type359 pending_focus_type = "keyboard"360 if not focus_list:361 return362 # No widget focused.363 current = get_focused()364 if not current:365 change_focus(focus_list[0])366 return367 # Find the current focus.368 for f in focus_list:369 if f.widget is current and f.arg == argument:370 from_focus = f371 break372 else:373 # If we can't pick something.374 change_focus(focus_list[0])375 return376 # If placeless, focus_extreme.377 if from_focus.x is None:378 focus_extreme(xmul, ymul, wmul, hmul)379 return380 fx0 = from_focus.x + from_focus.w * from_x0381 fy0 = from_focus.y + from_focus.h * from_y0382 fx1 = from_focus.x + from_focus.w * from_x1383 fy1 = from_focus.y + from_focus.h * from_y1384 placeless = None385 new_focus = None386 # a really big number.387 new_focus_dist = (65536.0 * renpy.config.focus_crossrange_penalty) ** 2388 for f in focus_list:389 if f is from_focus:390 continue391 if not f.widget.style.keyboard_focus:392 continue393 if f.x is None:394 placeless = f395 continue396 if not condition(from_focus, f):397 continue398 tx0 = f.x + f.w * to_x0399 ty0 = f.y + f.h * to_y0400 tx1 = f.x + f.w * to_x1401 ty1 = f.y + f.h * to_y1402 dist = line_dist(fx0, fy0, fx1, fy1,403 tx0, ty0, tx1, ty1)404 if dist < new_focus_dist:405 new_focus = f406 new_focus_dist = dist407 # If we couldn't find anything, try the placeless focus.408 new_focus = new_focus or placeless409 # If we have something, switch to it.410 if new_focus:411 return change_focus(new_focus)412 # And, we're done.413def focus_ordered(delta):414 global pending_focus_type415 pending_focus_type = "keyboard"416 placeless = None417 candidates = [ ]418 index = 0419 current = get_focused()420 current_index = None421 for f in focus_list:422 if f.x is None:423 placeless = f424 continue425 if f.arg is not None:426 continue427 if not f.widget.style.keyboard_focus:428 continue429 if f.widget is current:430 current_index = index431 candidates.append(f)432 index += 1433 new_focus = None434 if current_index is None:435 if candidates:436 if delta > 0:437 new_focus = candidates[delta - 1]438 else:439 new_focus = candidates[delta]440 else:441 new_index = current_index + delta442 if 0 <= new_index < len(candidates):443 new_focus = candidates[new_index]444 new_focus = new_focus or placeless445 return change_focus(new_focus)446def key_handler(ev):447 map_event = renpy.display.behavior.map_event448 if renpy.game.preferences.self_voicing:449 if map_event(ev, 'focus_right') or map_event(ev, 'focus_down'):450 return focus_ordered(1)451 if map_event(ev, 'focus_left') or map_event(ev, 'focus_up'):452 return focus_ordered(-1)453 else:454 if map_event(ev, 'focus_right'):455 return focus_nearest(0.9, 0.1, 0.9, 0.9,456 0.1, 0.1, 0.1, 0.9,457 verti_line_dist,458 lambda old, new : old.x + old.w <= new.x,459 -1, 0, 0, 0)...

Full Screen

Full Screen

ibus-el-agent

Source:ibus-el-agent Github

copy

Full Screen

...93 self.top = 094 self.focus = None95 self.focus_cb_id = None96 def __update_focus_cb(self, form):97 focus = self.display.get_input_focus().focus98 if focus != self.focus:99 try:100 tree = focus.query_tree()101 parent = tree.parent102 if tree.root in (focus, parent):103 print form % focus.id104 else:105 print form % parent.id106 self.focus = focus107 except:108 pass # This probably makes aborting ibus-mode.109 return True110 def stop_focus_observation(self):111 self.focus = None...

Full Screen

Full Screen

monitored_list.py

Source:monitored_list.py Github

copy

Full Screen

...102 if 'focus' in argd:103 focus = argd['focus']104 del argd['focus']105 super(MonitoredFocusList, self).__init__(*argl, **argd)106 self.set_focus(focus)107 self._focus_modified = lambda ml, indices, new_items: None108 def __repr__(self):109 return "%s(%r, focus=%r)" % (110 self.__class__.__name__, list(self), self.get_focus())111 def get_focus(self):112 """113 Return the index of the item "in focus" or None if114 the list is empty. May also be accessed as .focus115 >>> MonitoredFocusList([1,2,3], focus=2).get_focus()116 2117 >>> MonitoredFocusList().get_focus()118 >>> MonitoredFocusList([1,2,3], focus=1).focus119 1120 """121 if not self:122 return None123 if self._focus >= len(self):124 # should't happen.. but just in case125 return len(self)-1126 return self._focus127 def set_focus(self, index):128 """129 index -- index into self.widget_list, negative indexes count from130 the end, any index out of range will raise an IndexError131 132 Negative indexes work the same way they do in slicing.133 May also be set using .focus134 135 >>> ml = MonitoredFocusList([9, 10, 11])136 >>> ml.set_focus(2); ml.get_focus()137 2138 >>> ml.set_focus(-2); ml.get_focus()139 1140 >>> ml.focus = 0; ml.get_focus()141 0142 """143 if not self:144 self._focus = 0145 return146 if index < 0:147 index += len(self)148 if index < 0 or index >= len(self):149 raise IndexError('list index out of range')150 self._focus = int(index)151 focus = property(get_focus, set_focus)152 def set_focus_modified_callback(self, callback):153 """154 Assign a function to handle updating the focus when the item155 in focus is about to be changed. The callback is in the form:156 callback(monitored_list, slc, new_items)157 indices -- a (start, stop, step) tuple whose range covers the 158 items being modified159 new_items -- a list of items replacing those at range(*indices)160 161 The only valid action for the callback is to call set_focus().162 Modifying the list in the callback has undefined behaviour.163 """164 self._focus_modified = callback165 def _handle_possible_focus_modified(self, slc, new_items=[]):166 """167 Default behaviour is to move the focus to the item following168 any removed items, or the last item in the list if that doesn't169 exist.170 """171 num_new_items = len(new_items)172 start, stop, step = indices = slc.indices(len(self))173 if step == 1:174 if start <= self._focus < stop:175 # call user handler, which might modify focus176 self._focus_modified(self, indices, new_items)177 if start + num_new_items <= self._focus < stop:178 self._focus = stop179 # adjust for added/removed items180 if stop <= self._focus:181 self._focus += num_new_items - (stop - start)182 else:183 removed = range(start, stop, step)184 if self._focus in removed:185 # call user handler, which might modify focus186 self._focus_modified(self, indices, new_items)187 if not num_new_items:188 # extended slice being removed189 if self._focus in removed:190 self._focus += 1191 # adjust for removed items192 self._focus -= len(range(start, self._focus, step))193 def _clamp_focus(self):194 """195 adjust the focus if it is out of range196 """197 if self._focus >= len(self):198 self._focus = len(self)-1199 if self._focus < 0:200 self._focus = 0201 # override all the list methods that might affect our focus202 203 def __delitem__(self, y):204 """205 >>> ml = MonitoredFocusList([0,1,2,3], focus=2)206 >>> del ml[3]; ml207 MonitoredFocusList([0, 1, 2], focus=2)208 >>> del ml[0]; ml209 MonitoredFocusList([1, 2], focus=1)210 >>> del ml[1]; ml211 MonitoredFocusList([1], focus=0)212 >>> del ml[0]; ml213 MonitoredFocusList([], focus=None)214 >>> ml = MonitoredFocusList([5,4,6,4,5,4,6,4,5], focus=4)215 >>> del ml[1::2]; ml216 MonitoredFocusList([5, 6, 5, 6, 5], focus=2)217 >>> del ml[::2]; ml218 MonitoredFocusList([6, 6], focus=1)219 """220 if isinstance(y, slice):221 self._handle_possible_focus_modified(y)222 else:223 self._handle_possible_focus_modified(slice(y, y+1))224 rval = super(MonitoredFocusList, self).__delitem__(y)225 self._clamp_focus()226 return rval227 def __setitem__(self, i, y):228 """229 >>> def modified(monitored_list, indices, new_items):230 ... print "range%r <- %r" % (indices, new_items)231 >>> ml = MonitoredFocusList([0,1,2,3], focus=2)232 >>> ml.set_focus_modified_callback(modified)233 >>> ml[0] = 9234 >>> ml[2] = 6235 range(2, 3, 1) <- [6]236 >>> ml[-1] = 8; ml237 MonitoredFocusList([9, 1, 6, 8], focus=2)238 >>> ml[1::2] = [12, 13]239 >>> ml[::2] = [10, 11]240 range(0, 4, 2) <- [10, 11]241 """242 if isinstance(i, slice):243 self._handle_possible_focus_modified(i, y)244 else:245 self._handle_possible_focus_modified(slice(i, i+1 or None), [y])246 return super(MonitoredFocusList, self).__setitem__(i, y)247 def __delslice__(self, i, j):248 """249 >>> def modified(monitored_list, indices, new_items):250 ... print "range%r <- %r" % (indices, new_items)251 >>> ml = MonitoredFocusList([0,1,2,3,4], focus=2)252 >>> ml.set_focus_modified_callback(modified)253 >>> del ml[3:5]; ml254 MonitoredFocusList([0, 1, 2], focus=2)255 >>> del ml[:1]; ml256 MonitoredFocusList([1, 2], focus=1)257 >>> del ml[1:]; ml258 range(1, 2, 1) <- []259 MonitoredFocusList([1], focus=0)260 >>> del ml[:]; ml261 range(0, 1, 1) <- []262 MonitoredFocusList([], focus=None)263 """264 self._handle_possible_focus_modified(slice(i, j))265 rval = super(MonitoredFocusList, self).__delslice__(i, j)266 self._clamp_focus()267 return rval268 def __setslice__(self, i, j, y):269 """270 >>> ml = MonitoredFocusList([0,1,2,3,4], focus=2)271 >>> ml[3:5] = [-1]; ml272 MonitoredFocusList([0, 1, 2, -1], focus=2)273 >>> ml[0:1] = []; ml274 MonitoredFocusList([1, 2, -1], focus=1)275 >>> ml[1:] = [3, 4]; ml276 MonitoredFocusList([1, 3, 4], focus=1)277 >>> ml[1:] = [2]; ml278 MonitoredFocusList([1, 2], focus=1)279 >>> ml[0:1] = [9,9,9]; ml280 MonitoredFocusList([9, 9, 9, 2], focus=3)281 >>> ml[:] = []; ml282 MonitoredFocusList([], focus=None)283 """284 self._handle_possible_focus_modified(slice(i, j), y)285 rval = super(MonitoredFocusList, self).__setslice__(i, j, y)286 self._clamp_focus()287 return rval288 289 def insert(self, index, object):290 """291 >>> ml = MonitoredFocusList([0,1,2,3], focus=2)292 >>> ml.insert(-1, -1); ml293 MonitoredFocusList([0, 1, 2, -1, 3], focus=2)294 >>> ml.insert(0, -2); ml295 MonitoredFocusList([-2, 0, 1, 2, -1, 3], focus=3)296 >>> ml.insert(3, -3); ml297 MonitoredFocusList([-2, 0, 1, -3, 2, -1, 3], focus=4)298 """299 self._handle_possible_focus_modified(slice(index, index), [object])300 return super(MonitoredFocusList, self).insert(index, object)...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful