Best JavaScript code snippet using chromeless
Focus.js
Source:Focus.js  
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);...focus.py
Source:focus.py  
...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)...ibus-el-agent
Source:ibus-el-agent  
...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...monitored_list.py
Source:monitored_list.py  
...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)...GuiScreen.py
Source:GuiScreen.py  
1from pandac.PandaModules import *2from otp.otpbase import OTPGlobals3from direct.gui.DirectGui import *4from otp.otpgui import OTPDialog5from direct.directnotify import DirectNotifyGlobal6from otp.otpbase import OTPLocalizer7from direct.task.Task import Task8class GuiScreen:9    notify = DirectNotifyGlobal.directNotify.newCategory('GuiScreen')10    DGG.ENTERPRESS_ADVANCE = 011    DGG.ENTERPRESS_ADVANCE_IFNOTEMPTY = 112    DGG.ENTERPRESS_DONT_ADVANCE = 213    DGG.ENTERPRESS_REMOVE_FOCUS = 314    ENTRY_WIDTH = 2015    def __init__(self):16        self.waitingForDatabase = None17        self.focusIndex = None18        self.suppressClickSound = 019        return20    def startFocusMgmt(self, startFocus = 0, enterPressBehavior = DGG.ENTERPRESS_ADVANCE_IFNOTEMPTY, overrides = {}, globalFocusHandler = None):21        GuiScreen.notify.debug('startFocusMgmt:\nstartFocus=%s,\nenterPressBehavior=%s\noverrides=%s' % (startFocus, enterPressBehavior, overrides))22        self.accept('tab', self.__handleTab)23        self.accept('shift-tab', self.__handleShiftTab)24        self.accept('enter', self.__handleEnter)25        self.__startFrameStartTask()26        self.userGlobalFocusHandler = globalFocusHandler27        self.focusHandlerAbsorbCounts = {}28        for i in xrange(len(self.focusList)):29            item = self.focusList[i]30            if isinstance(item, DirectEntry):31                self.focusHandlerAbsorbCounts[item] = 032        self.userFocusHandlers = {}33        self.userCommandHandlers = {}34        for i in xrange(len(self.focusList)):35            item = self.focusList[i]36            if isinstance(item, DirectEntry):37                self.userFocusHandlers[item] = (item['focusInCommand'], item['focusInExtraArgs'])38                item['focusInCommand'] = self.__handleFocusChangeAbsorb39                item['focusInExtraArgs'] = [i]40                self.userCommandHandlers[item] = (item['command'], item['extraArgs'])41                item['command'] = None42                item['extraArgs'] = []43            elif isinstance(item, DirectScrolledList):44                self.userCommandHandlers[item] = (item['command'], item['extraArgs'])45                item['command'] = self.__handleDirectScrolledListCommand46                item['extraArgs'] = [i]47        self.enterPressHandlers = {}48        for i in xrange(len(self.focusList)):49            item = self.focusList[i]50            behavior = enterPressBehavior51            if item in overrides:52                behavior = overrides[item]53            if callable(behavior):54                self.enterPressHandlers[item] = behavior55            else:56                if not isinstance(item, DirectEntry) and behavior == GuiScreen_ENTERPRESS_ADVANCE_IFNOTEMPTY:57                    behavior = GuiScreen_ENTERPRESS_ADVANCE58                commandHandlers = (self.__alwaysAdvanceFocus,59                 self.__advanceFocusIfNotEmpty,60                 self.__neverAdvanceFocus,61                 self.__ignoreEnterPress)62                self.enterPressHandlers[item] = commandHandlers[behavior]63        self.setFocus(startFocus)64        return65    def focusMgmtActive(self):66        return self.focusIndex != None67    def stopFocusMgmt(self):68        GuiScreen.notify.debug('stopFocusMgmt')69        if not self.focusMgmtActive():70            return71        self.ignore('tab')72        self.ignore('shift-tab')73        self.ignore('enter')74        self.__stopFrameStartTask()75        self.userGlobalFocusHandler = None76        self.focusIndex = None77        self.focusHandlerAbsorbCounts = {}78        for item in self.focusList:79            if isinstance(item, DirectEntry):80                userHandler, userHandlerArgs = self.userFocusHandlers[item]81                item['focusInCommand'] = userHandler82                item['focusInExtraArgs'] = userHandlerArgs83                userHandler, userHandlerArgs = self.userCommandHandlers[item]84                item['command'] = userHandler85                item['extraArgs'] = userHandlerArgs86            elif isinstance(item, DirectScrolledList):87                userHandler, userHandlerArgs = self.userCommandHandlers[item]88                item['command'] = userHandler89                item['extraArgs'] = userHandlerArgs90        self.userFocusHandlers = {}91        self.userCommandHandlers = {}92        self.enterPressHandlers = {}93        return94    def setFocus(self, arg, suppressSound = 1):95        if type(arg) == type(0):96            index = arg97        else:98            index = self.focusList.index(arg)99        if suppressSound:100            self.suppressClickSound += 1101        self.__setFocusIndex(index)102    def advanceFocus(self, condition = 1):103        index = self.getFocusIndex()104        if condition:105            index += 1106        self.setFocus(index, suppressSound=0)107    def getFocusIndex(self):108        if not self.focusMgmtActive():109            return None110        return self.focusIndex111    def getFocusItem(self):112        if not self.focusMgmtActive():113            return None114        return self.focusList[self.focusIndex]115    def removeFocus(self):116        focusItem = self.getFocusItem()117        if isinstance(focusItem, DirectEntry):118            focusItem['focus'] = 0119        if self.userGlobalFocusHandler:120            self.userGlobalFocusHandler(None)121        return122    def restoreFocus(self):123        self.setFocus(self.getFocusItem())124    def __setFocusIndex(self, index):125        focusIndex = index % len(self.focusList)126        focusItem = self.focusList[focusIndex]127        if isinstance(focusItem, DirectEntry):128            focusItem['focus'] = 1129            self.focusHandlerAbsorbCounts[focusItem] += 1130        self.__handleFocusChange(focusIndex)131    def __chainToUserCommandHandler(self, item):132        userHandler, userHandlerArgs = self.userCommandHandlers[item]133        if userHandler:134            if isinstance(item, DirectEntry):135                enteredText = item.get()136                apply(userHandler, [enteredText] + userHandlerArgs)137            elif isinstance(item, DirectScrolledList):138                apply(userHandler, userHandlerArgs)139    def __chainToUserFocusHandler(self, item):140        if isinstance(item, DirectEntry):141            userHandler, userHandlerArgs = self.userFocusHandlers[item]142            if userHandler:143                apply(userHandler, userHandlerArgs)144    def __handleTab(self):145        self.tabPressed = 1146        self.focusDirection = 1147        self.__setFocusIndex(self.getFocusIndex() + self.focusDirection)148    def __handleShiftTab(self):149        self.tabPressed = 1150        self.focusDirection = -1151        self.__setFocusIndex(self.getFocusIndex() + self.focusDirection)152    def __handleFocusChangeAbsorb(self, index):153        item = self.focusList[index]154        if self.focusHandlerAbsorbCounts[item] > 0:155            self.focusHandlerAbsorbCounts[item] -= 1156        else:157            self.__handleFocusChange(index)158    def playFocusChangeSound(self):159        base.playSfx(DGG.getDefaultClickSound())160    def __handleFocusChange(self, index):161        if index != self.focusIndex:162            self.removeFocus()163        self.__focusChangedThisFrame = 1164        if hasattr(self, 'tabPressed'):165            del self.tabPressed166        else:167            self.focusDirection = 1168        self.focusIndex = index169        if self.suppressClickSound > 0:170            self.suppressClickSound -= 1171        else:172            self.playFocusChangeSound()173        focusItem = self.getFocusItem()174        if self.userGlobalFocusHandler:175            self.userGlobalFocusHandler(focusItem)176        if self.getFocusItem() != focusItem:177            GuiScreen.notify.debug('focus changed by global focus handler')178        if self.focusMgmtActive():179            self.__chainToUserFocusHandler(focusItem)180    def __startFrameStartTask(self):181        self.__focusChangedThisFrame = 0182        self.frameStartTaskName = 'GuiScreenFrameStart'183        taskMgr.add(self.__handleFrameStart, self.frameStartTaskName, -100)184    def __stopFrameStartTask(self):185        taskMgr.remove(self.frameStartTaskName)186        del self.frameStartTaskName187        del self.__focusChangedThisFrame188    def __handleFrameStart(self, task):189        self.__focusChangedThisFrame = 0190        return Task.cont191    def __handleDirectScrolledListCommand(self, index):192        self.__chainToUserCommandHandler(self.focusList[index])193        self.setFocus(index, suppressSound=self.getFocusIndex() == index)194    def __handleEnter(self):195        if self.__focusChangedThisFrame:196            return197        focusItem = self.getFocusItem()198        if isinstance(focusItem, DirectEntry):199            self.__chainToUserCommandHandler(focusItem)200        if self.focusMgmtActive() and focusItem == self.getFocusItem():201            self.enterPressHandlers[focusItem]()202    def __alwaysAdvanceFocus(self):203        self.advanceFocus()204    def __advanceFocusIfNotEmpty(self):205        focusItem = self.getFocusItem()206        enteredText = focusItem.get()207        if enteredText != '':208            self.advanceFocus()209        else:210            self.setFocus(self.getFocusIndex())211    def __neverAdvanceFocus(self):212        self.setFocus(self.getFocusIndex())213    def __ignoreEnterPress(self):214        pass215    def waitForDatabaseTimeout(self, requestName = 'unknown'):216        GuiScreen.notify.debug('waiting for database timeout %s at %s' % (requestName, globalClock.getFrameTime()))217        globalClock.tick()218        taskMgr.doMethodLater(OTPGlobals.DatabaseDialogTimeout, self.__showWaitingForDatabase, 'waitingForDatabase', extraArgs=[requestName])219    def __showWaitingForDatabase(self, requestName):220        GuiScreen.notify.info('timed out waiting for %s at %s' % (requestName, globalClock.getFrameTime()))221        dialogClass = OTPGlobals.getDialogClass()222        self.waitingForDatabase = dialogClass(text=OTPLocalizer.GuiScreenToontownUnavailable, dialogName='WaitingForDatabase', buttonTextList=[OTPLocalizer.GuiScreenCancel], style=OTPDialog.Acknowledge, command=self.__handleCancelWaiting)223        self.waitingForDatabase.show()224        taskMgr.doMethodLater(OTPGlobals.DatabaseGiveupTimeout, self.__giveUpWaitingForDatabase, 'waitingForDatabase', extraArgs=[requestName])225        return Task.done226    def __giveUpWaitingForDatabase(self, requestName):227        GuiScreen.notify.info('giving up waiting for %s at %s' % (requestName, globalClock.getFrameTime()))228        self.cleanupWaitingForDatabase()229        messenger.send(self.doneEvent, [{'mode': 'failure'}])230        return Task.done231    def cleanupWaitingForDatabase(self):232        if self.waitingForDatabase != None:233            self.waitingForDatabase.cleanup()234            self.waitingForDatabase = None235        taskMgr.remove('waitingForDatabase')236        return237    def __handleCancelWaiting(self, value):238        self.cleanupWaitingForDatabase()...uMenu.py
Source:uMenu.py  
1from Joystick import Joystick2class MenuElement():3    def __init__(self, txt):4        self.text = MenuElement.align_center(txt)5    6    @staticmethod7    def align_center(txt):8        l = len(txt)9        if l%2 == 0:10            return int((16 - l)/2)*" "+txt+int((16 - l)/2)*" "11        else:12            return (int((16 - l+1)/2))*" "+txt+(int((16 - l-1)/2))*" "13        14    def _action(self):15        pass16    def set_action(self, func):17        self._action = func18            19        20class State():21    js = None22    23    _focus_line = 024    _focus_dir = 0 # l-r: 0, u:1, d:2, comeback from action: -125    def __init__(self, menu: MenuElement, left = None, right = None, down = None, up = None, push = None):26        self.left = left27        self.right = right28        self.down = down29        self.up = up30        self.push = push31        self.menu = menu32        self.last_childstate = None33        self._set_transition()34        35    def _set_transition(self):36        if self.left is not None:37            self.left.right = self38        if self.right is not None:39            self.right.left = self40        if self.down is not None:41            self.down.up = self42        if self.up is not None:43            self.up.down = self44            self.up.last_childstate = self45            46    def _printer(self):47        print(self.menu.text)48        txt = self.menu.text49        if (State._focus_line == 0 and State._focus_dir == 0) or (State._focus_line == 1 and State._focus_dir == 2): # at 0, l-r OR at 1, d50            if self.left is not None:51                txt = "<" + txt[1:]52            if self.right is not None:53                txt = txt[:-1] + ">"54            uMenu.writer(0, 0, txt)55            if(self.down is not None):56                uMenu.writer(0, 1, self.down.menu.text)57            else:58                uMenu.writer(0, 1, " "*16)59            State._focus_line = 060        elif State._focus_line == 1 and State._focus_dir == 0: # at 1, l-r61            if self.left is not None:62                txt = "<" + txt[1:]63            if self.right is not None:64                txt = txt[:-1] + ">"65            uMenu.writer(0, 1, txt)66            State._focus_line = 167        elif State._focus_line == 0 and State._focus_dir == 2: # at 0, d68            uMenu.writer(0, 0, " ")69            uMenu.writer(15, 0, " ")70            if self.right is not None:71                uMenu.writer(15, 1, ">")72            State._focus_line = 173        elif State._focus_line == 1 and State._focus_dir == 1: # at 1, u74            uMenu.writer(0, 1, " ")75            uMenu.writer(15, 1, " ")76            if self.right is not None:77                uMenu.writer(15, 0, ">")78            if self.left is not None:79                uMenu.writer(0, 0, "<")80            State._focus_line = 081        elif State._focus_line == 0 and State._focus_dir == 1: # at 0, u82            if self.left is not None:83                txt = "<" + txt[1:]84            if self.right is not None:85                txt = txt[:-1] + ">"86            uMenu.writer(0, 1, txt)87            if(self.up is not None):88                uMenu.writer(0, 0, self.up.menu.text)89            else:90                uMenu.writer(0, 0, " "*16)91            State._focus_line = 192        elif State._focus_dir == -1: #cb from action93            uMenu.writer(0, State._focus_line, self.menu.text)94            if (State._focus_line == 0):95                if self.down is not None:96                    uMenu.writer(0, 1, self.down.menu.text)97            elif(State._focus_line == 1):98                uMenu.writer(0, 0, self.up.menu.text)99            100            101    def _state_transition(self):102        self._printer()103        next_state = self._check_input()104        next_state._state_transition()105    def _action(self):106        self.menu._action()107        self._state_transition() 108    def _check_input(self):109        while True:110            if State.js.moved_left() and self.left is not None:111                if State.js.check_r() == 1:112                    State._focus_dir = 0113                    return self.left114            if State.js.moved_right() and self.right is not None:115                if State.js.check_f() == 1:116                    State._focus_dir = 0117                    return self.right118            elif State.js.moved_up() and self.up is not None:119                if State.js.check_r() == 1:120                    State._focus_dir = 1121                    return self.up122            elif State.js.moved_down() and self.down is not None:123                if State.js.check_f() == 1:124                    State._focus_dir = 2125                    return self.down126            elif State.js.pressed():127                if State.js.check_sw_r() == 1:128                    State._focus_dir = -1129                    self._action()130                131class ChildState(State):132    def __init__(self, menu: MenuElement, left=None, right=None, down=None, up=None, push=None):133        super().__init__(menu, left=left, right=right, down=down, up=up, push=push)134    def _set_transition(self):135        if self.left is not None:136            self.left.right = self137        if self.right is not None:138            self.right.left = self139        if self.down is not None:140            self.down.up = self141        if self.up is not None and self.up.last_childstate is None:142            self.up.down = self143            self.up.last_childstate = self144        elif self.up is not None and self.up.last_childstate is not None:145            self.up.last_childstate.right = self146            self.left = self.up.last_childstate147            self.up.last_childstate = self148class uMenu():149    states = []150    last_state = None151    152    def _init__ (self):153        pass154    155    def writer(cls):156        print('use "set_text_writer" method')157    158    def set_text_writer(cls, func_move, func_write):159        def text_writer(x, y, text):160            func_move(x, y)161            func_write(text)162        uMenu.writer = text_writer163        164    def set_controls(cls, r_key = None, r_val = None, l_key = None, l_val = None,165                     u_key = None, u_val = None, d_key = None, d_val = None,166                     s_key = None, s_val = None):167        State.js = Joystick(r_key, r_val, l_key, l_val, u_key, u_val, d_key, d_val, s_key, s_val)168        169    @staticmethod170    def add_menu(menu: MenuElement):171        if uMenu.last_state is not None:172            x = State(menu, left = uMenu.last_state)173            uMenu.states.append(x)174            uMenu.last_state = x175            return x176        else:177            x = State(menu)178            uMenu.states.append(x)179            uMenu.last_state = x180            return x181    @staticmethod        182    def add_childmenu(menu: MenuElement, parent: State):183        x = ChildState(menu, up=parent)184        uMenu.states.append(x)185        return x186    def run_uMenu(self):...rasterfcfinder.py
Source:rasterfcfinder.py  
1#!/usr/bin/env python2# WVN 10/5/11 - rasterfcfinder.py based on rasterfinder.py3#  The paper describing the use of this Leginon node is:4#  W.V. Nicholson, H. White and J. Trinick (2010) JSB 172, 395-399.5#  "An approach to automated acquisition of cryoEM images from lacey6#  carbon grids."7import data8import targetfinder9# WVN 19/1/08 - changes borrowed from v.1.4.1 rasterfinder.py10# Apart from below changes in imports, other changes were in11# readImage (removed from rasterfinder), transpose_points(removed),12# createRaster (changes in code), get_box_stats (changes),13# findTargets (changes in code)14#  which are inherited from the new15# rasterfinder.py anyway.16# rewrites were required in overridden ice method.17#18# import Mrc19import threading20import ice21#import numarray22#import imagefun23import numpy24from pyami import arraystats25import gui.wx.RasterFCFinder26import polygon27import math28# WVN 12/8/0729import rasterfinder30# WVN 1/4/07 RasterFCFinder - based on RasterFinder31class RasterFCFinder(rasterfinder.RasterFinder):32	panelclass = gui.wx.RasterFCFinder.Panel33	settingsclass = data.RasterFCFinderSettingsData34	defaultsettings = dict(rasterfinder.RasterFinder.defaultsettings)35	defaultsettings.update({36               'focus center x': 0,37               'focus center y': 0,38               'focus radius': 45.0,39               'focus box size': 15.0,40               'focus min mean': 0.05,41               'focus max mean': 0.2,42               'focus min std': 0.0,43               'focus max std': 0.2,44	})45	def __init__(self, id, session, managerlocation, **kwargs):46		targetfinder.TargetFinder.__init__(self, id, session, managerlocation, **kwargs)47		self.icecalc = ice.IceCalculator()48		self.rasterpoints = None49		self.polygonrasterpoints = None50		self.userpause = threading.Event()51		self.images = {52			'Original': None,53		}54		self.imagetargets = {55			'Original': {},56			'Polygon': {},57			'Raster': {},58			'Final': {},59		}60		self.start()61	def ice(self):62		focusCenterX = self.settings['focus center x']63		focusCenterY = self.settings['focus center y']64		focusRadius = self.settings['focus radius']65		focusBoxSize = self.settings['focus box size']66		focusMinMean = self.settings['focus min mean']67		focusMaxMean = self.settings['focus max mean']68		focusMinSD = self.settings['focus min std']69		focusMaxSD = self.settings['focus max std']70		i0 = self.settings['ice thickness']71		tmin = self.settings['ice min mean']72		tmax = self.settings['ice max mean']73		tstd = self.settings['ice max std']74		boxsize = self.settings['ice box size']75		self.icecalc.set_i0(i0)76		# calculate stats around each raster point77		goodpoints = []78		mylist = []79		for rasterpoint in self.polygonrasterpoints:80			# WVN 19/1/08 - change borrowed from v.1.4.1 rasterfinder.py81			# box_stats = self.get_box_stats(self.original, rasterpoint, boxsize)82			box_stats = self.get_box_stats(self.currentimagedata['image'], rasterpoint, boxsize)83			t = self.icecalc.get_thickness(box_stats['mean'])84			ts = self.icecalc.get_stdev_thickness(box_stats['std'], box_stats['mean'])85			if (tmin <= t <= tmax) and (ts < tstd):86				goodpoints.append(rasterpoint)87				mylist.append( (rasterpoint, t, ts))88		goodpoints = self.transpose_points(goodpoints)89		self.logger.info('%s points with good ice' % (len(goodpoints),))90		### run template convolution91		# takes x,y instead of row,col92		# WVN - focus convolve not used in rasterfcfinder93		# if self.settings['focus convolve']:94	#		focus_points = self.applyTargetTemplate(goodpoints, 'focus')95		# else:96	#		focus_points = []97		focus_points = []98		if self.settings['acquisition convolve']:99			acq_points = self.applyTargetTemplate(goodpoints, 'acquisition')100		else:101			acq_points = goodpoints102		## add constant targets103		# WVN - focus constant template not used in rasterfcfinder104		# const_foc = self.settings['focus constant template']105		# focus_points.extend(const_foc)106		const_acq = self.settings['acquisition constant template']107		acq_points.extend(const_acq)108		# WVN - Find a suitable focus target on the chosen109		# focus "circle"110		circFocusPoints = []111		# WVN - changed to getting max. mean - to target carbon areas112		# rather than "feature-ful" areas113		#circFocusPointsSD = []114		circFocusPointsMean = []115		circPix = 2.0 * math.pi * focusRadius116		angRadStep = 1.0/focusRadius117		# radian step for 1 pixel118		for i in range(int(circPix)):119			omega = angRadStep * i120			# print "angle: ", (omega*180.0/math.pi)121			xPoint = int(focusCenterX + focusRadius*math.cos(omega))122			yPoint = int(focusCenterY + focusRadius*math.sin(omega))123			# coords have to be "transposed" for get_box_stats()124			# box_stats = self.get_box_stats(self.original, (yPoint, xPoint), focusBoxSize)125			# WVN 19/1/08 - change borrowed from v.1.4.1 rasterfinder.py126			box_stats = self.get_box_stats(self.currentimagedata['image'], (yPoint, xPoint), focusBoxSize)127			t = self.icecalc.get_thickness(box_stats['mean'])128			ts = self.icecalc.get_stdev_thickness(box_stats['std'], box_stats['mean'])129			if (focusMinMean <= t <= focusMaxMean) and \130		           (focusMinSD <= ts <= focusMaxSD) :131				circFocusPoints.append((xPoint, yPoint))132				# circFocusPointsSD.append(ts)133				circFocusPointsMean.append(t)134		if len(circFocusPoints) > 0:135			#bestFocusSD = max(circFocusPointsSD)136			bestFocusMean = max(circFocusPointsMean)137			bestFocusIndex = circFocusPointsMean.index(bestFocusMean)138			bestFocusPoint = circFocusPoints[bestFocusIndex]139			focus_points.append(bestFocusPoint)140			print "Best focus point on circle: ", bestFocusPoint141		# WVN - end of my code142		self.setTargets(acq_points, 'acquisition', block=True)...focusmanager.js
Source:focusmanager.js  
...15 * to set the focus state of the editor.16 * @param {CKEDITOR.editor} editor The editor instance.17 * @example18 * var focusManager = <b>new CKEDITOR.focusManager( editor )</b>;19 * focusManager.focus();20 */21CKEDITOR.focusManager = function( editor )22{23	if ( editor.focusManager )24		return editor.focusManager;2526	/**27	 * Indicates that the editor instance has focus.28	 * @type Boolean29	 * @example30	 * alert( CKEDITOR.instances.editor1.focusManager.hasFocus );  // e.g "true"31	 */32	this.hasFocus = false;3334	/**35	 * Object used to hold private stuff.36	 * @private37	 */38	this._ =39	{40		editor : editor41	};4243	return this;44};4546CKEDITOR.focusManager.prototype =47{48	/**49	 * Used to indicate that the editor instance has the focus.<br />50	 * <br />51	 * Note that this function will not explicitelly set the focus in the52	 * editor (for example, making the caret blinking on it). Use53	 * {@link CKEDITOR.editor#focus} for it instead.54	 * @example55	 * var editor = CKEDITOR.instances.editor1;56	 * <b>editor.focusManager.focus()</b>;57	 */58	focus : function()59	{60		if ( this._.timer )61			clearTimeout( this._.timer );6263		if ( !this.hasFocus )64		{65			// If another editor has the current focus, we first "blur" it. In66			// this way the events happen in a more logical sequence, like:67			//		"focus 1" > "blur 1" > "focus 2"68			// ... instead of:69			//		"focus 1" > "focus 2" > "blur 1"70			if ( CKEDITOR.currentInstance )
...Using AI Code Generation
1const Chromeless = require('chromeless').Chromeless2async function run() {3  const chromeless = new Chromeless()4    .type('chromeless', 'input[name="q"]')5    .press(13)6    .wait('#resultStats')7    .focus('input[name="q"]')8    .screenshot()9  await chromeless.end()10}11run().catch(console.error.bind(console))Using AI Code Generation
1const Chromeless = require('chromeless').Chromeless2async function run() {3  const chromeless = new Chromeless()4    .type('chromeless', 'input[name="q"]')5    .press(13)6    .wait('#resultStats')7    .focus('#lst-ib')8    .screenshot()9  await chromeless.end()10}11run().catch(console.error.bind(console))12{13  "scripts": {14  },15  "dependencies": {16  }17}18    at ExecutionContext._evaluateInternal (/Users/username/Desktop/chromeless-focus/node_modules/puppeteer/lib/ExecutionContext.js:97:13)19    at process._tickCallback (internal/process/next_tick.js:68:7)20const Chromeless = require('chromeless').Chromeless21async function run() {22  const chromeless = new Chromeless()23    .type('chromeless', 'input[name="q"]')24    .press(13)25    .wait('#resultStats')26    .focus('#lst-ib')27    .screenshot()28  await chromeless.end()29}30run().catch(console.error.bind(console))Using AI Code Generation
1const chromeless = new Chromeless()2async function run() {3    .type('chromeless', 'input[name="q"]')4    .press(13)5    .wait('#resultStats')6    .focus('#lst-ib')7    .type('chromeless')8    .screenshot()9  await chromeless.end()10}11run().catch(console.error.bind(console))Using AI Code Generation
1const Chromeless = require('chromeless').Chromeless;2const chromeless = new Chromeless();3async function run() {4    .type('chromeless', 'input[name="q"]')5    .click('input[type="submit"]')6    .wait('#resultStats')7    .screenshot();8  await chromeless.end();9}10run().catch(console.error.bind(console));11const Chromeless = require('chromeless').Chromeless;12const chromeless = new Chromeless();13async function run() {14    .focus('input[name="q"]')15    .type('chromeless')16    .click('input[type="submit"]')17    .wait('#resultStats')18    .screenshot();19  await chromeless.end();20}21run().catch(console.error.bind(console));22const Chromeless = require('chromeless').Chromeless;23const chromeless = new Chromeless();24async function run() {25    .focus('input[name="q"]')26    .type('chromeless')27    .delay(5000)28    .click('input[type="submit"]')29    .wait('#resultStats')30    .screenshot();31  await chromeless.end();32}33run().catch(console.error.bindUsing AI Code Generation
1const chromeless = require('chromeless')()2async function run() {3    .click('input[type="text"]')4    .type('chromeless')5    .press(13)6    .wait('#resultStats')7    .screenshot()8  await chromeless.end()9}10run().catch(console.error.bind(console))11const puppeteer = require('puppeteer');12(async () => {13  const browser = await puppeteer.launch();14  const page = await browser.newPage();15  await page.focus('input[type="text"]');16  await page.keyboard.type('chromeless');17  await page.keyboard.press('Enter');18  await page.waitFor('#resultStats');19  await page.screenshot({path: 'google.png'});20  await browser.close();21})();22const Nightmare = require('nightmare');23const nightmare = Nightmare({ show: true });24  .type('input[type="text"]', 'nightmare')25  .click('input[type="submit"]')26  .wait('#resultStats')27  .evaluate(() => document.querySelector('#resultStats').innerHTML)28  .end()29  .then(console.log)30  .catch(error => {31    console.error('Search failed:', error);32  });33var casper = require('casper').create();34  this.fill('form[action="/search"]', { q: 'casperjs' }, true);35});36casper.then(function() {37  this.echo(this.getTitle());38});39casper.run();40from selenium import webdriver41from selenium.webdriver.common.keys import Keys42driver = webdriver.Firefox()43elem = driver.find_element_by_name("q")44elem.send_keys("selenium")45elem.send_keys(Keys.RETURN)46driver.close()47const webdriverio = require('webdriverio');48const options = { desiredCapabilities: { browserName: 'chrome'Using AI Code Generation
1const chromeless = new Chromeless()2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .focus('input[name="q"]')6  .type('chromeless')7  .screenshot()8console.log(screenshot)9await chromeless.end()10{11  "scripts": {12  },13  "dependencies": {14  }15}Using AI Code Generation
1const Chromeless = require('chromeless').Chromeless;2const chromeless = new Chromeless();3const fs = require('fs');4(async () => {5        .wait('#lst-ib')6        .focus('#lst-ib')7        .type('chromeless')8        .press(13)9        .wait('#resultStats')10        .screenshot();11    await chromeless.end();12})();13const Chromeless = require('chromeless').Chromeless;14const chromeless = new Chromeless();15const fs = require('fs');16(async () => {17        .wait('#lst-ib')18        .click('#lst-ib')19        .type('chromeless')20        .press(13)21        .wait('#resultStats')22        .screenshot();23    await chromeless.end();24})();25const Chromeless = require('chromeless').Chromeless;26const chromeless = new Chromeless();27const fs = require('fs');28(async () => {29        .wait('#lst-ib')30        .type('chromeless')31        .press(13)32        .wait('#resultStats')33        .screenshot();34    await chromeless.end();35})();36const Chromeless = require('chromeless').Chromeless;37const chromeless = new Chromeless();38const fs = require('fs');39(async () => {40        .wait('#lst-ib')41        .type('chromeless')42        .press(13)43        .wait('#resultStats')44        .screenshot();45    await chromeless.end();46})();47const Chromeless = require('chromeless').Chromeless;48const chromeless = new Chromeless();Using AI Code Generation
1test('should focus on input', async t => {2        .typeText('#input', 'Hello')3        .expect(Selector('#input').value).eql('Hello')4        .click('#button')5        .expect(Selector('#input').focused).ok()6})7test('should focus on input', async t => {8        .typeText('#input', 'Hello')9        .expect(Selector('#input').value).eql('Hello')10        .click('#button')11        .expect(Selector('#input').focused).ok()12        .pressKey('tab')13        .expect(Selector('#button').focused).ok()14})15test('should focus on input', async t => {16        .typeText('#input', 'Hello')17        .expect(Selector('#input').value).eql('Hello')18        .click('#button')19        .expect(Selector('#input').focused).ok()20        .pressKey('tab')21        .expect(Selector('#button').focused).ok()22        .pressKey('tab')23        .expect(Selector('#input').focused).ok()24})25  1 | import { Selector } from 'testcafe';26  6 | test('should focus on input', async t =>Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
