def script_dispatchEventPrevious(self, gesture): try: if not self.objNav(): gesture.send() else: if self.modo(): gesture.send() else: if (not self.navegar('previous', gesture)): fecha = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") shift = True obj = api.getNavigatorObject() navegado = api.getNavigatorObject() childrens = 0 if gesture.mainKeyName == 'l': while not obj.role == controlTypes.ROLE_LIST: obj = obj.parent childrens = obj.childCount xpath = str(obj.IA2Attributes["id"]) self.logger.newEvent("previous", gesture, 'foco', navegado, xpath, self.url, childrens) except: error = "error script_dispatchEventPrevious"
def script_navigatorObject_moveToFlatReviewAtObjectPosition(self,gesture): obj=api.getNavigatorObject() pos=obj.flatReviewPosition if pos: api.setReviewPosition(pos) pos=pos.copy() obj=api.getNavigatorObject() speech.speakObjectProperties(obj,name=True,role=True) pos.expand(textInfos.UNIT_LINE) speech.speakTextInfo(pos) else: speech.speakMessage(_("No flat review for this object"))
def script_startExploration(self, gesture): self.configVars() with measureTime("Toolbars found in"): self.findToolbars() self.initialFilterBars() if self.bars: self.populateBar(self.bars[self.barIndex]) if not self.bars: # Translators: message in applications without toolbars ui.message(_("No toolbar found")) return # a backup of various info, useful later self.startSnap["focus"] = api.getFocusObject() self.startSnap["nav"] = api.getNavigatorObject() self.startSnap["foreground"] = api.getForegroundObject() self.startSnap["pid"] = api.getFocusObject().processID self.startSnap["reviewMode"] = review.getCurrentMode() # declare exploration started self.exploring = True # set object navigation active review.setCurrentMode("object", updateReviewPosition=False) # see script_explore for gesture explanation for direction in ("up", "right", "down", "left"): self.bindGesture("kb:%sArrow" % direction, "explore") self.bindGesture("kb:escape", "finish") self.bindGesture("kb:enter", "objActivate") self.bindGesture("kb:space", "objLeftClick") self.bindGesture("kb:applications", "objRightClick") self.bindGesture("kb:shift+f10", "objRightClick") bar = self.bars[self.barIndex] api.setNavigatorObject(bar) speech.speakObject(bar, reason=REASON_FOCUS)
def _devInfoToLog(self): import api obj = api.getNavigatorObject() if hasattr(obj, "devInfo"): log.info("Developer info for navigator object:\n%s" % "\n".join(obj.devInfo)) else: log.info("No developer info for navigator object")
def handleCaretMove(pos): """ Instructs the review position to be updated due to caret movement. @param pos: Either a TextInfo instance at the caret position, or an NVDAObject or TeeInterceptor who's caret position should be retreaved. @type pos: L{textInfos.TextInfo} or L{NVDAObject} or L{TreeInterceptor} """ if not config.conf["reviewCursor"]["followCaret"]: return if isinstance(pos, textInfos.TextInfo): info = pos obj = pos.obj else: info = None obj = pos mode = getCurrentMode() if isinstance(obj, NVDAObject): if not mode == 'object' or obj != api.getNavigatorObject(): return elif isinstance(obj, DocumentTreeInterceptor): if mode not in ('object', 'document'): return if mode != 'document': if obj.passThrough: #if trying to set with a position in a treeInterceptor but passThrough is turned on, ignore it completely return setCurrentMode('document', updateReviewPosition=False) if not info: try: info = obj.makeTextInfo(textInfos.POSITION_CARET) except (NotImplementedError, RuntimeError): return api.setReviewPosition(info, isCaret=True)
def handleCaretMove(pos): """ Instructs the review position to be updated due to caret movement. @param pos: Either a TextInfo instance at the caret position, or an NVDAObject or TeeInterceptor who's caret position should be retreaved. @type pos: L{textInfos.TextInfo} or L{NVDAObject} or L{TreeInterceptor} """ if not config.conf["reviewCursor"]["followCaret"]: return if isinstance(pos,textInfos.TextInfo): info=pos obj=pos.obj else: info=None obj=pos mode=getCurrentMode() if isinstance(obj,NVDAObject): if not mode=='object' or obj!=api.getNavigatorObject(): return elif isinstance(obj,DocumentTreeInterceptor): if mode not in ('object','document'): return if mode!='document': if obj.passThrough: #if trying to set with a position in a treeInterceptor but passThrough is turned on, ignore it completely return setCurrentMode('document',updateReviewPosition=False) if not info: try: info=obj.makeTextInfo(textInfos.POSITION_CARET) except (NotImplementedError,RuntimeError): return api.setReviewPosition(info)
def _caretScriptPostMovedHelper(self, speakUnit, gesture, info = None): """ This method ensures that LaTeX translation occurs when the system caret moves, and also makes sure that normal behaviour occurs when l{processMaths} is off. """ if scriptHandler.isScriptWaiting (): return if not info: try: info = self.makeTextInfo (textInfos.POSITION_CARET) except: return if config.conf["reviewCursor"]["followCaret"] and api.getNavigatorObject() is self: api.setReviewPosition (info) if speakUnit == textInfos.UNIT_LINE and EditableLatex.processMaths: spokenLine = GetLine () #We don't need to get braille. It's handled by the region. if not spokenLine:# Is it a blank line? spokenLine = _("blank") else: self.speakMathLine(spokenLine) else: if speakUnit: info.expand(speakUnit) speech.speakTextInfo(info, unit=speakUnit, reason=controlTypes.REASON_CARET)
def setCurrentMode(mode, updateReviewPosition=True): """ Sets the current review mode to the given mode ID or index and updates the review position. @param mode: either a 0-based index into the modes list, or one of the mode IDs (first item of a tuple in the modes list). @type mode: int or string @return: a presentable label for the new current mode (suitable for speaking or brailleing) @rtype: string """ global _currentMode if isinstance(mode, int): ID, label, func = modes[mode] else: for index, (ID, label, func) in enumerate(modes): if mode == ID: mode = index break else: raise LookupError("mode %s not found" % mode) obj = api.getNavigatorObject() pos = func(obj) if pos: _currentMode = mode if updateReviewPosition: api.setReviewPosition(pos[0], clearNavigatorObject=False) return label
def getCurrentBrailleTables(input_=False, brf=False): if brf: tables = [ os.path.join(baseDir, "res", "brf.ctb").encode("UTF-8"), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] else: tables = [] app = appModuleHandler.getAppModuleForNVDAObject( api.getNavigatorObject()) if brailleInput.handler._table.fileName == config.conf["braille"][ "translationTable"] and app and app.appName != "nvda": tables += dictionaries.dictTables if input_: mainTable = os.path.join(brailleTables.TABLES_DIR, brailleInput.handler._table.fileName) else: mainTable = os.path.join( brailleTables.TABLES_DIR, config.conf["braille"]["translationTable"]) tables += [ mainTable, os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] return tables
def script_playNavigatorObject(self, gesture): if not self.imagePlayer: ui.message(_("AudioScreen disabled")) return obj = api.getNavigatorObject() x, y, w, h = obj.location self.playRect(x, y, w, h, detailed=True, forceRestart=True)
def updateNamespaceSnapshotVars(self): """Update the console namespace with a snapshot of NVDA's current state. This creates/updates variables for the current focus, navigator object, etc. Typically, used before the NVDA python console is opened, after which, calls to the 'api' module will refer to this new focus. """ try: caretPos = api.getCaretPosition() except RuntimeError: log.debug( "Unable to set caretPos snapshot variable for python console.") caretPos = None self._namespaceSnapshotVars = { "focus": api.getFocusObject(), # Copy the focus ancestor list, as it gets mutated once it is replaced in api.setFocusObject. "focusAnc": list(api.getFocusAncestors()), "fdl": api.getFocusDifferenceLevel(), "fg": api.getForegroundObject(), "nav": api.getNavigatorObject(), "caretObj": api.getCaretObject(), "caretPos": caretPos, "review": api.getReviewPosition(), "mouse": api.getMouseObject(), "brlRegions": braille.handler.buffer.regions, } self.namespace.update(self._namespaceSnapshotVars)
def script_dispatchEventNext(self, gesture): try: #ui.message("corriendo") if not self.objNav(): gesture.send() else: if self.modo(): gesture.send() else: if (not self.navegar('next', gesture)): fecha = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") shift = True obj = api.getNavigatorObject() childrens = 0 if gesture.mainKeyName == 'l': while not obj.role == controlTypes.ROLE_LIST: obj = obj.parent childrens = obj.childCount xpath = str(obj.IA2Attributes["id"]) self.logger.event(str(fecha), shift, gesture.mainKeyName, xpath, self.url, 'next', childrens) except: error = "Error script_dispatchEventNext"
def script_startRecognition(self, gesture): obj = api.getNavigatorObject() if obj.role != controlTypes.ROLE_GRAPHIC and conf["graphicOnly"]: ui.message(_("This object is not a graphical element")) return if controlTypes.STATE_OFFSCREEN in obj.states: ui.message(_("Captcha off screen")) return try: x, y, width, height = obj.location except Exception: ui.message(_("Captcha has no location")) return if conf["sizeReport"] and scriptHandler.getLastScriptRepeatCount( ) != 1: ui.message(_("Size: {0} X {1} pixels").format(width, height)) return bmp = wx.Bitmap(width, height) mem = wx.MemoryDC(bmp) mem.Blit(0, 0, width, height, wx.ScreenDC(), x, y) image = bmp.ConvertToImage() body = io.BytesIO() image.SaveFile(body, wx.BITMAP_TYPE_PNG) wx.CallAfter(self._creator, body=body.getvalue())
def script_analyzeObject(self, gesture): api_url = "https://us-central1-icon-classifier.cloudfunctions.net/function-2/interpret_image?locale=%s&b64=%s" ui.message(_("Analyzing navigator object")) nav = api.getNavigatorObject() if not nav.location: ui.message(_("This navigator object is not analyzable")) return left, top, width, height = nav.location img = ImageGrab.grab(bbox=(left, top, left + width, top + height)) maxArea = 35000 area = width * height if area > maxArea: scale = sqrt(float(maxArea) / float(area)) img = img.resize((int(width * scale), int(height * scale))) buffer = StringIO() img.save(buffer, format="JPEG") img_str = base64.b64encode(buffer.getvalue()) lang = getConfig()['language'] resp = urllib.urlopen(api_url % (lang, img_str)).read().decode('utf-8') ui.message(_('Analysis completed: ') + resp)
def __init__(self, name, listEvent, url): ''' Constructor ''' foco = api.getFocusObject() navegado = api.getNavigatorObject() super(NavigationByKeyL, self).__init__(name, foco, navegado, url)
def script_pressItem(self, gesture): nav = api.getNavigatorObject() api.moveMouseToNVDAObject(nav) winUser.mouse_event(winUser.MOUSEEVENTF_LEFTDOWN, 0, 0, None, None) winUser.mouse_event(winUser.MOUSEEVENTF_LEFTUP, 0, 0, None, None) winUser.mouse_event(winUser.MOUSEEVENTF_LEFTDOWN, 0, 0, None, None) winUser.mouse_event(winUser.MOUSEEVENTF_LEFTUP, 0, 0, None, None)
def recognizeNavigatorObject(recognizer): """User interface function to recognize content in the navigator object. This should be called from a script or in response to a GUI action. @param recognizer: The content recognizer to use. @type recognizer: L{contentRecog.ContentRecognizer} """ global _activeRecog if isinstance(api.getFocusObject(), RecogResultNVDAObject): # Translators: Reported when content recognition (e.g. OCR) is attempted, # but the user is already reading a content recognition result. ui.message(_("Already in a content recognition result")) return nav = api.getNavigatorObject() # Translators: Reported when content recognition (e.g. OCR) is attempted, # but the content is not visible. notVisibleMsg = _("Content is not visible") try: left, top, width, height = nav.location except TypeError: log.debugWarning("Object returned location %r" % nav.location) ui.message(notVisibleMsg) return try: imgInfo = RecogImageInfo.createFromRecognizer(left, top, width, height, recognizer) except ValueError: ui.message(notVisibleMsg) return if _activeRecog: _activeRecog.cancel() # Translators: Reporting when content recognition (e.g. OCR) begins. ui.message(_("Recognizing")) sb = screenBitmap.ScreenBitmap(imgInfo.recogWidth, imgInfo.recogHeight) pixels = sb.captureImage(left, top, width, height) _activeRecog = recognizer recognizer.recognize(pixels, imgInfo, _recogOnResult)
def getCurrentBrailleTables(input_=False): if input_: if instanceGP.BRFMode and not errorTable: tables = [ os.path.join(configBE.baseDir, "res", "brf.ctb").encode("UTF-8"), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] else: tables = dictionaries.dictTables+[ os.path.join(brailleTables.TABLES_DIR, brailleInput.handler._table.fileName), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] else: if errorTable: if instanceGP.BRFMode: instanceGP.BRFMode = False tables = [ os.path.join(brailleTables.TABLES_DIR, config.conf["braille"]["translationTable"]), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] elif instanceGP.BRFMode: tables = [ os.path.join(configBE.baseDir, "res", "brf.ctb").encode("UTF-8"), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] else: tables = [] app = appModuleHandler.getAppModuleForNVDAObject(api.getNavigatorObject()) if app and app.appName != "nvda": tables += dictionaries.dictTables tables += configBE.preTable + [ os.path.join(brailleTables.TABLES_DIR, config.conf["braille"]["translationTable"]), os.path.join(brailleTables.TABLES_DIR, "braille-patterns.cti") ] + configBE.postTable return tables
def script_playNavigatorObject(self,gesture): if not self.imagePlayer: ui.message(_("AudioScreen disabled")) return obj=api.getNavigatorObject() x,y,w,h=obj.location self.playRect(x,y,w,h,detailed=True,forceRestart=True)
def _moveToRow(self, row): if not row: return self._moveToColumn(None) nav = api.getNavigatorObject() if nav != self and nav.parent == self: self.__class__._savedColumnNumber = nav.columnNumber row.setFocus()
def script_navigatorObject_current(self,gesture): curObject=api.getNavigatorObject() if not isinstance(curObject,NVDAObject): speech.speakMessage(_("no navigator object")) return if scriptHandler.getLastScriptRepeatCount()>=1: if curObject.TextInfo!=NVDAObjectTextInfo: textList=[] if curObject.name and isinstance(curObject.name, basestring) and not curObject.name.isspace(): textList.append(curObject.name) try: info=curObject.makeTextInfo(textInfos.POSITION_SELECTION) if not info.isCollapsed: textList.append(info.text) else: info.expand(textInfos.UNIT_LINE) if not info.isCollapsed: textList.append(info.text) except (RuntimeError, NotImplementedError): # No caret or selection on this object. pass else: textList=[prop for prop in (curObject.name, curObject.value) if prop and isinstance(prop, basestring) and not prop.isspace()] text=" ".join(textList) if len(text)>0 and not text.isspace(): if scriptHandler.getLastScriptRepeatCount()==1: speech.speakSpelling(text) else: if api.copyToClip(text): speech.speakMessage(_("%s copied to clipboard")%text) else: speech.speakObject(curObject,reason=speech.REASON_QUERY)
def event_caret(self, obj, nextHandler): self.detectPossibleSelectionChange() braille.handler.handleCaretMove(self) caret = self.makeTextInfo(textInfos.POSITION_CARET) if config.conf["reviewCursor"][ "followCaret"] and api.getNavigatorObject( ) is self.rootNVDAObject: api.setReviewPosition(caret)
def event_caret(self): if self is api.getFocusObject() and not eventHandler.isPendingEvents("gainFocus"): braille.handler.handleCaretMove(self) if config.conf["reviewCursor"]["followCaret"] and api.getNavigatorObject() is self: try: api.setReviewPosition(self.makeTextInfo(textInfos.POSITION_CARET)) except (NotImplementedError, RuntimeError): pass
def script_prevSelectedElement(self, gesture): obj = api.getNavigatorObject().treeInterceptor if isinstance(obj, browseMode.BrowseModeTreeInterceptor): if self.webBrowseMode == 0: commands.script_navigatorObject_previousInFlow(gesture) else: self.browseModeCommands[self.webBrowseMode - 1][1](obj, gesture)
def script_moveToPreviousColumn(self, gesture): cur = api.getNavigatorObject() if cur == self: new = None elif cur.parent != self or cur.columnNumber == 1: new = self else: new = cur.previous self._moveToColumn(new)
def script_moveToNextColumn(self, gesture): cur = api.getNavigatorObject() if cur == self: new = self.firstChild elif cur.parent != self: new = self else: new = cur.next self._moveToColumn(new)
def script_previous(self, gesture): obj = api.getNavigatorObject() if obj.parent == self: obj = obj.previous if obj.previous else self.lastChild while obj.actionCount == 0 and obj.role != controlTypes.ROLE_BUTTON: obj = obj.previous if obj.previous else self.lastChild self._setFakeFocus(obj) else: self._setFakeFocus(self.simpleFirstChild)
def script_dropLeft(self, gesture): obj = api.getNavigatorObject() if obj.location == (0, 0, 0, 0) or controlTypes.STATE_INVISIBLE in obj.states or controlTypes.STATE_OFFSCREEN in obj.states \ or api.getDesktopObject().objectFromPoint(obj.location[0]+1, obj.location[1]+1) != obj: self.error(_("Can't drop here")) return x = obj.location[0] - 1 y = obj.location[1] + obj.location[3] / 2 self.dragAndDrop(x, y)
def script_moveToNextColumn(self, gesture): cur = api.getNavigatorObject() if cur == self: new = self.simpleFirstChild elif cur.parent != self: new = self else: new = cur.simpleNext self._moveToColumn(new)
def script_moveToPreviousColumn(self, gesture): cur = api.getNavigatorObject() if cur == self: new = None elif cur.parent != self or not cur.simplePrevious: new = self else: new = cur.simplePrevious self._moveToColumn(new)
def showBrailleObj(): s = [] obj = api.getNavigatorObject() s.append(controlTypes.roleLabels[obj.role]) if obj.name: s.append(obj.name) if obj.value: s.append(obj.value) if obj.roleText: s.append(obj.roleText) if obj.description: s.append(obj.description) if obj.keyboardShortcut: s.append('=> ' + api.getNavigatorObject().keyboardShortcut) if obj.location: s.append('[%s]' % (', '.join([str(k) for k in obj.location]))) if s != []: braille.handler.message(' '.join(s)) return
def script_analyzeObject(self, gesture): if not self.isVirtual: self.isVirtual = scriptHandler.getLastScriptRepeatCount() > 0 if self.isVirtual: return True if self.isWorking: return False self.isWorking = True api_url = "https://visionbot.ru/addon/index.php" if self.tmr: self.tmr.cancel() speech.cancelSpeech() ui.message(_("Analyzing navigator object")) try: nav = api.getNavigatorObject() except: return False if not nav.location: speech.cancelSpeech() ui.message(_("This navigator object is not analyzable")) return left, top, width, height = nav.location bmp = wx.EmptyBitmap(width, height) mem = wx.MemoryDC(bmp) mem.Blit(0, 0, width, height, wx.ScreenDC(), left, top) image = bmp.ConvertToImage() try: body = BytesIO() except TypeError: body = StringIO() if wx.__version__ == '3.0.2.0': # Maintain compatibility with old version of WXPython image.SaveStream(body, wx.BITMAP_TYPE_PNG) else: # Used in WXPython 4.0 image.SaveFile(body, wx.BITMAP_TYPE_PNG) img_str = base64.b64encode(body.getvalue()) sound = getConfig()['sound'] s = 0 if sound: s = 1 textonly = getConfig()['textonly'] imageonly = getConfig()['imageonly'] n = 0 if textonly and not imageonly: n = 1 if not textonly and imageonly: n = 2 trtext = getConfig()['trtext'] t = 0 if trtext: t = 1 qronly = getConfig()['qronly'] q = 0 if qronly: q = 1 lang = getConfig()['language'] self.tmr = Timer(0.1, self.thr_analyzeObject, [gesture, api_url, img_str, lang, s, n, t, q]) self.tmr.start()
def script_doAction(self, gesture): obj = api.getNavigatorObject() if obj.parent == self: if obj.actionCount > 0: scriptHandler.executeScript( globalCommands.commands.script_review_activate, KeyboardInputGesture) else: scriptHandler.executeScript(self.script_menu, None) else: beep(200, 80)
def event_caret(self): if self is api.getFocusObject() and not eventHandler.isPendingEvents( "gainFocus"): braille.handler.handleCaretMove(self) if config.conf["reviewCursor"][ "followCaret"] and api.getNavigatorObject() is self: try: api.setReviewPosition( self.makeTextInfo(textInfos.POSITION_CARET)) except (NotImplementedError, RuntimeError): pass
def script_next(self, gesture): obj = api.getNavigatorObject() if obj.parent == self: obj = obj.next if obj.next else self.firstChild while (obj.actionCount == 0 and obj.role != controlTypes.ROLE_BUTTON ) or obj.role == controlTypes.ROLE_GROUPING: obj = obj.next if obj.next else self.firstChild self._setFakeFocus(obj) else: self._setFakeFocus(self.simpleFirstChild)
def script_moveToPreviousColumn(self, gesture): cur = api.getNavigatorObject() if cur == self: new = None elif cur.parent != self or not cur.previous: new = self else: new = cur.previous while new and new.location and new.location.width == 0: new = new.previous self._moveToColumn(new)
def script_navigatorObject_firstChild(self,gesture): curObject=api.getNavigatorObject() if not isinstance(curObject,NVDAObject): speech.speakMessage(_("no navigator object")) return simpleReviewMode=config.conf["reviewCursor"]["simpleReviewMode"] curObject=curObject.simpleFirstChild if simpleReviewMode else curObject.firstChild if curObject is not None: api.setNavigatorObject(curObject) speech.speakObject(curObject,reason=speech.REASON_QUERY) else: speech.speakMessage(_("No children"))
def _caretScriptPostMovedHelper(self, speakUnit): if isScriptWaiting(): return try: info = self.makeTextInfo(textInfos.POSITION_CARET) except: return if config.conf["reviewCursor"]["followCaret"] and api.getNavigatorObject() is self: api.setReviewPosition(info.copy()) if speakUnit: info.expand(speakUnit) speech.speakTextInfo(info, unit=speakUnit, reason=speech.REASON_CARET)
def updateNavigatorLocation(): global navigatorRect nav = api.getNavigatorObject() if locationAvailable(nav): newRect = location2rect(nav.location) elif locationAvailable(api.getFocusObject()): newRect = location2rect(api.getFocusObject().location) else: return newRect = limitRectInDesktop(newRect) if not rectEquals(newRect, navigatorRect): navigatorRect = newRect setMarkPositions(navigatorMarkRectList, navigatorRect, NAVIGATOR_THICKNESS, NAVIGATOR_PADDING) for i in xrange(4): moveAndShowWindow(navigatorHwndList[i], navigatorMarkRectList[i])
def _set_passThrough(self, state): if self._passThrough == state: return self._passThrough = state if state: if config.conf['reviewCursor']['followFocus']: focusObj=api.getFocusObject() if self is focusObj.treeInterceptor: api.setNavigatorObject(focusObj) braille.handler.handleGainFocus(api.getFocusObject()) else: obj=api.getNavigatorObject() if config.conf['reviewCursor']['followCaret'] and self is obj.treeInterceptor: api.setNavigatorObject(self.rootNVDAObject) braille.handler.handleGainFocus(self)
def script_navigatorObject_doDefaultAction(self,gesture): curObject=api.getNavigatorObject() if not isinstance(curObject,NVDAObject): speech.speakMessage(_("no navigator object")) return try: action=curObject.getActionName() except NotImplementedError: ui.message(_("No default action")) return try: curObject.doAction() except NotImplementedError: ui.message(_("default action failed")) return ui.message("%s"%action)
def updateNamespaceSnapshotVars(self): """Update the console namespace with a snapshot of NVDA's current state. This creates/updates variables for the current focus, navigator object, etc. """ self._namespaceSnapshotVars = { "focus": api.getFocusObject(), # Copy the focus ancestor list, as it gets mutated once it is replaced in api.setFocusObject. "focusAnc": list(api.getFocusAncestors()), "fdl": api.getFocusDifferenceLevel(), "fg": api.getForegroundObject(), "nav": api.getNavigatorObject(), "review":api.getReviewPosition(), "mouse": api.getMouseObject(), "brlRegions": braille.handler.buffer.regions, } self.namespace.update(self._namespaceSnapshotVars)
def script_navigatorObject_moveFocus(self,gesture): obj=api.getNavigatorObject() if not isinstance(obj,NVDAObject): speech.speakMessage(_("no focus")) if scriptHandler.getLastScriptRepeatCount()==0: ui.message(_("move focus")) obj.setFocus() else: review=api.getReviewPosition() try: review.updateCaret() except NotImplementedError: ui.message(_("no caret")) return info=review.copy() info.expand(textInfos.UNIT_LINE) speech.speakTextInfo(info,reason=speech.REASON_CARET)
def script_navigatorObject_currentDimensions(self,gesture): obj=api.getNavigatorObject() if not obj: ui.message(_("no navigator object")) location=obj.location if not location: ui.message(_("No location information for navigator object")) (left,top,width,height)=location deskLocation=api.getDesktopObject().location if not deskLocation: ui.message(_("No location information for screen")) (deskLeft,deskTop,deskWidth,deskHeight)=deskLocation percentFromLeft=(float(left-deskLeft)/deskWidth)*100 percentFromTop=(float(top-deskTop)/deskHeight)*100 percentWidth=(float(width)/deskWidth)*100 percentHeight=(float(height)/deskHeight)*100 ui.message(_("Object edges positioned %.1f per cent from left edge of screen, %.1f per cent from top edge of screen, width is %.1f per cent of screen, height is %.1f per cent of screen")%(percentFromLeft,percentFromTop,percentWidth,percentHeight))
def updateNavigatorLocation(): global navigatorRect try: nav = api.getNavigatorObject() except: return if not isinstance(nav, NVDAObject): return if locationAvailable(nav): newRect = location2rect(nav.location) elif locationAvailable(api.getFocusObject()): newRect = location2rect(api.getFocusObject().location) else: return if not rectEquals(newRect, navigatorRect): navigatorRect = newRect moveAndShowWindow(navigatorHwnd, navigatorRect)
def script_moveMouseToNavigatorObject(self,gesture): obj=api.getNavigatorObject() try: p=api.getReviewPosition().pointAtStart except (NotImplementedError, LookupError): p=None if p: x=p.x y=p.y else: try: (left,top,width,height)=obj.location except: ui.message(_("object has no location")) return x=left+(width/2) y=top+(height/2) winUser.setCursorPos(x,y) mouseHandler.executeMouseMoveEvent(x,y)
def _set_passThrough(self, state): if self._passThrough == state: return self._passThrough = state if state: if config.conf['reviewCursor']['followFocus']: focusObj=api.getFocusObject() if self is focusObj.treeInterceptor: if review.getCurrentMode()=='document': # if focus is in this treeInterceptor and review mode is document, turning on passThrough should force object review review.setCurrentMode('object') api.setNavigatorObject(focusObj) braille.handler.handleGainFocus(api.getFocusObject()) else: obj=api.getNavigatorObject() if config.conf['reviewCursor']['followCaret'] and self is obj.treeInterceptor: if review.getCurrentMode()=='object': # if navigator object is in this treeInterceptor and the review mode is object, then turning off passThrough should force document review review.setCurrentMode('document',True) braille.handler.handleGainFocus(self)
def reloadAppModules(): """Reloads running appModules. especially, it clears the cache of running appModules and deletes them from sys.modules. Each appModule will then be reloaded immediately. """ global appModules state = [] for mod in runningTable.itervalues(): state.append({key: getattr(mod, key) for key in ("processID", # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. # Also, if there is an active context handle such as a loaded buffer, # nvdaHelperRemote can't reinit until that handle dies. "helperLocalBindingHandle", "_inprocRegistrationHandle", # #5380: We must save config profile triggers so they can be cleaned up correctly. # Otherwise, they'll remain active forever. "_configProfileTrigger", ) if hasattr(mod, key)}) # #2892: Don't disconnect from nvdaHelperRemote during termination. mod._helperPreventDisconnect = True terminate() del appModules mods=[k for k,v in sys.modules.iteritems() if k.startswith("appModules") and v is not None] for mod in mods: del sys.modules[mod] import appModules initialize() for entry in state: pid = entry.pop("processID") mod = getAppModuleFromProcessID(pid) mod.__dict__.update(entry) # The appModule property for existing NVDAObjects will now be None, since their AppModule died. # Force focus, navigator, etc. objects to re-fetch, # since NVDA depends on the appModule property for these. for obj in itertools.chain((api.getFocusObject(), api.getNavigatorObject()), api.getFocusAncestors()): try: del obj._appModuleRef except AttributeError: continue # Fetch and cache right away; the process could die any time. obj.appModule
def script_touch_rightClick(self, gesture): self.etsDebugOutput("etouch: attempting to perform right-click") obj=api.getNavigatorObject() try: p=api.getReviewPosition().pointAtStart except (NotImplementedError, LookupError): p=None if p: x=p.x y=p.y else: try: (left,top,width,height)=obj.location except: # Translators: Reported when the object has no location for the mouse to move to it. ui.message(_("object has no location")) return x=left+(width/2) y=top+(height/2) self.etsDebugOutput("etouch: mouse point found at %s, %s"%(x, y)) winUser.setCursorPos(x,y) winUser.mouse_event(winUser.MOUSEEVENTF_RIGHTDOWN,0,0,None,None) winUser.mouse_event(winUser.MOUSEEVENTF_RIGHTUP,0,0,None,None)
def setCurrentMode(mode,updateReviewPosition=True): """ Sets the current review mode to the given mode ID or index and updates the review position. @param mode: either a 0-based index into the modes list, or one of the mode IDs (first item of a tuple in the modes list). @type mode: int or string @return: a presentable label for the new current mode (suitable for speaking or brailleing) @rtype: string """ global _currentMode if isinstance(mode,int): ID,label,func=modes[mode] else: for index,(ID,label,func) in enumerate(modes): if mode==ID: mode=index break else: raise LookupError("mode %s not found"%mode) obj=api.getNavigatorObject() pos=func(obj) if pos: _currentMode=mode if updateReviewPosition: api.setReviewPosition(pos[0],clearNavigatorObject=False) return label
def script_test_navigatorDisplayModelText(self,gesture): obj=api.getNavigatorObject() text=obj.displayText speech.speakMessage(text) log.info(text)
def script_navigatorObject_devInfo(self,gesture): obj=api.getNavigatorObject() log.info("Developer info for navigator object:\n%s" % "\n".join(obj.devInfo), activateLogViewer=True)
def event_caret(self, obj, nextHandler): self.detectPossibleSelectionChange() braille.handler.handleCaretMove(self) caret = self.makeTextInfo(textInfos.POSITION_CARET) if config.conf["reviewCursor"]["followCaret"] and api.getNavigatorObject() is self.rootNVDAObject: api.setReviewPosition(caret)
def script_prevSelectedElement(self, gesture): obj = api.getNavigatorObject().treeInterceptor if isinstance(obj, browseMode.BrowseModeTreeInterceptor): if self.webBrowseMode == 0: commands.script_navigatorObject_previousInFlow(gesture) else: self.browseModeCommands[self.webBrowseMode-1][1](obj, gesture)