Пример #1
0
	def script_reportTimeAndDate(self, gesture):
		if scriptHandler.getLastScriptRepeatCount() == 0:
			ui.message(datetime.now().strftime(config.conf["clockAndCalendar"]["timeDisplayFormat"]))
		elif scriptHandler.getLastScriptRepeatCount() == 1:
			ui.message(datetime.now().strftime(config.conf["clockAndCalendar"]["dateDisplayFormat"]))
		else:
			ui.message(datetime.now().strftime("Day %j, week %W of %Y."))
Пример #2
0
	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)
Пример #3
0
	def script_reportStatusLine(self, gesture):
		#it seems that the status bar is the last child of the forground object
		#so, get it from there
		obj = api.getForegroundObject().lastChild
		found=False
		if obj and obj.role == controlTypes.ROLE_STATUSBAR:
			text = api.getStatusBarText(obj)
			api.setNavigatorObject(obj)
			found=True
		else:
			info=api.getForegroundObject().flatReviewPosition
			if info:
				info.expand(textInfos.UNIT_STORY)
				info.collapse(True)
				info.expand(textInfos.UNIT_LINE)
				text=info.text
				info.collapse()
				api.setReviewPosition(info)
				found=True
		if not found:
			# Translators: Reported when there is no status line for the current program or window.
			ui.message(_("No status line found"))
			return
		if scriptHandler.getLastScriptRepeatCount()==0:
			ui.message(text)
		else:
			speech.speakSpelling(text)
Пример #4
0
	def script_encoderDateTime(self, gesture):
		import winKernel
		if scriptHandler.getLastScriptRepeatCount()==0:
			text=winKernel.GetTimeFormat(winKernel.LOCALE_USER_DEFAULT, 0, None, None)
		else:
			text=winKernel.GetDateFormat(winKernel.LOCALE_USER_DEFAULT, winKernel.DATE_LONGDATE, None, None)
		ui.message(text)
Пример #5
0
	def script_review_currentWord(self,gesture):
		info=api.getReviewPosition().copy()
		info.expand(textInfos.UNIT_WORD)
		scriptCount=scriptHandler.getLastScriptRepeatCount()
		if scriptCount==0:
			speech.speakTextInfo(info,reason=speech.REASON_CARET,unit=textInfos.UNIT_WORD)
		else:
			speech.speakSpelling(info.text,useCharacterDescriptions=bool(scriptCount>1))
Пример #6
0
	def script_reportCurrentFocus(self,gesture):
		focusObject=api.getFocusObject()
		if isinstance(focusObject,NVDAObject):
			if scriptHandler.getLastScriptRepeatCount()==0:
				speech.speakObject(focusObject, reason=speech.REASON_QUERY)
			else:
				speech.speakSpelling(focusObject.name)
		else:
			speech.speakMessage(_("no focus"))
Пример #7
0
	def script_reportStatusLine(self,gesture):
		obj = api.getStatusBar()
		if not obj:
			ui.message(_("no status bar found"))
			return
		text = api.getStatusBarText(obj)

		if scriptHandler.getLastScriptRepeatCount()==0:
			ui.message(text)
		else:
			speech.speakSpelling(text)
		api.setNavigatorObject(obj)
Пример #8
0
	def script_reportCurrentLine(self,gesture):
		obj=api.getFocusObject()
		treeInterceptor=obj.treeInterceptor
		if hasattr(treeInterceptor,'TextInfo') and not treeInterceptor.passThrough:
			obj=treeInterceptor
		try:
			info=obj.makeTextInfo(textInfos.POSITION_CARET)
		except (NotImplementedError, RuntimeError):
			info=obj.makeTextInfo(textInfos.POSITION_FIRST)
		info.expand(textInfos.UNIT_LINE)
		if scriptHandler.getLastScriptRepeatCount()==0:
			speech.speakTextInfo(info,unit=textInfos.UNIT_LINE,reason=speech.REASON_CARET)
		else:
			speech.speakSpelling(info.text)
Пример #9
0
	def script_review_currentCharacter(self,gesture):
		info=api.getReviewPosition().copy()
		info.expand(textInfos.UNIT_CHARACTER)
		scriptCount=scriptHandler.getLastScriptRepeatCount()
		if scriptCount==0:
			speech.speakTextInfo(info,unit=textInfos.UNIT_CHARACTER,reason=speech.REASON_CARET)
		elif scriptCount==1:
			speech.speakSpelling(info.text,useCharacterDescriptions=True)
		else:
			try:
				c = ord(info.text)
				speech.speakMessage("%d," % c)
				speech.speakSpelling(hex(c))
			except:
				speech.speakTextInfo(info,unit=textInfos.UNIT_CHARACTER,reason=speech.REASON_CARET)
Пример #10
0
	def script_setRowHeaderColumn(self,gesture):
		scriptCount=scriptHandler.getLastScriptRepeatCount()
		tableID=self.tableID
		if not config.conf['documentFormatting']['reportTableHeaders']:
			# Translators: a message reported in the SetRowHeaderColumn script for Excel.
			ui.message(_("Cannot set headers. Please enable reporting of table headers in Document Formatting Settings"))
			return
		if scriptCount==0:
			self.rowHeaderColumns[tableID]=self.columnNumber
			# Translators: a message reported in the SetRowHeaderColumn script for Excel.
			ui.message(_("Set row header column"))
		elif scriptCount==1 and tableID in self.rowHeaderColumns:
			del self.rowHeaderColumns[tableID]
			# Translators: a message reported in the SetRowHeaderColumn script for Excel.
			ui.message(_("Cleared row header column"))
Пример #11
0
	def script_title(self,gesture):
		obj=api.getForegroundObject()
		title=obj.name
		if not isinstance(title,basestring) or not title or title.isspace():
			title=obj.appModule.appName  if obj.appModule else None
			if not isinstance(title,basestring) or not title or title.isspace():
				title=_("no title")
		repeatCount=scriptHandler.getLastScriptRepeatCount()
		if repeatCount==0:
			ui.message(title)
		elif repeatCount==1:
			speech.speakSpelling(title)
		else:
			if api.copyToClip(title):
				ui.message(_("%s copied to clipboard")%title)
Пример #12
0
	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)
Пример #13
0
	def script_setRowHeader(self,gesture):
		scriptCount=scriptHandler.getLastScriptRepeatCount()
		if not config.conf['documentFormatting']['reportTableHeaders']:
			# Translators: a message reported in the SetRowHeader script for Excel.
			ui.message(_("Cannot set headers. Please enable reporting of table headers in Document Formatting Settings"))
			return
		if scriptCount==0:
			if self.parent.setAsHeaderCell(self,isColumnHeader=False,isRowHeader=True):
				# Translators: a message reported in the SetRowHeader script for Excel.
				ui.message(_("Set {address} as start of row headers").format(address=self.cellCoordsText))
			else:
				# Translators: a message reported in the SetRowHeader script for Excel.
				ui.message(_("Already set {address} as start of row headers").format(address=self.cellCoordsText))
		elif scriptCount==1:
			if self.parent.forgetHeaderCell(self,isColumnHeader=False,isRowHeader=True):
				# Translators: a message reported in the SetRowHeader script for Excel.
				ui.message(_("removed {address}    from row headers").format(address=self.cellCoordsText))
			else:
				# Translators: a message reported in the SetRowHeader script for Excel.
				ui.message(_("Cannot find {address}    in row headers").format(address=self.cellCoordsText))
Пример #14
0
 def script_announceInfo(self, gesture):
     obj = api.getForegroundObject()
     infos = {}
     try:
         # Translators: dict key spoken below
         infos[_("Executable name")] = obj.appModule.appName
         # Translators: dict key spoken below
         infos[_("Product name")] = obj.appModule.productName
         # Translators: dict key spoken below
         infos[_("Product version")] = obj.appModule.productVersion
     except:
         pass
     if getLastScriptRepeatCount() and infos:
         info = '; '.join(['%s: %s' % (k, v) for k, v in infos.items()])
         if api.copyToClip(info):
             # Translators: message announcing what was copied
             ui.message(_("Application info copied in clipboard"))
     elif infos:
         info = '; '.join(['%s: %s' % (k, v) for k, v in infos.items()])
         ui.message(info)
     else:
         ui.message(_("Application info not available"))
Пример #15
0
 def script_url(self, gesture):
     if not self.inMainWindow():
         #TRANSLATORS: message spoken by NVDA when the focus is not in the main Firefox window
         ui.message(_("Not available here"))
         return
     path = (("id", "nav-bar"), ("id", "urlbar"), (
         "id",
         "identity-box",
     ))
     secInfoButton = self.searchObject(path)
     if secInfoButton:
         securInfo = secInfoButton.description  # This has changed in FF 57. Keeping this line for compatibility with earlier versions.
         try:  # This one is for FF 57 and later.
             securInfo = secInfoButton.getChild(
                 1).name if secInfoButton.getChild(
                     1).IA2Attributes["id"] == "connection-icon" else ""
             if securInfo:
                 owner = " ".join([
                     o.name for o in filter(
                         lambda o: o.role == controlTypes.ROLE_STATICTEXT,
                         secInfoButton.recursiveDescendants)
                 ])
                 securInfo = "%s, %s" % (owner,
                                         securInfo) if owner else securInfo
         except:
             pass
         #TRANSLATORS: this connection is using http, not https
         securInfo = _(
             "Insecure connection") if not securInfo else securInfo
         url = secInfoButton.next.value
         #TRANSLATORS: message spoken when reading the Firefox address bar
         ui.message(_("Page address is: %s (%s)") % (url, securInfo))
         if scriptHandler.getLastScriptRepeatCount() == 1:
             if api.copyToClip(url):
                 #TRANSLATORS: message spoken when an item hast just been copied to the clipboard
                 ui.message(_("Copied to clipboard"))
         return
     #TRANSLATORS: message spoken when addres bar could not be found
     ui.message(_("Address not found"))
Пример #16
0
 def script_announceDriveInfo(self, gesture):
     #goes through all registered drives and gives info on each one
     info = []
     for drive in psutil.disk_partitions():
         #get info on each one
         # If and only if the Windows says disk is ready in order to avoid a core stack freeze when no disk is inserted into a slot.
         # This can be checked by looking for a file system.
         if drive.fstype:
             driveInfo = psutil.disk_usage(drive[0])
             # Translators: Shows drive letter, type of drive (fixed or removable), used capacity and total capacity of a drive (example: C drive, ntfs; 40 GB of 100 GB used (40%).
             info.append(
                 _("{driveName} ({driveType} drive): {usedSpace} of {totalSpace} used {percent}%."
                   ).format(
                       driveName=drive[0],
                       driveType=drive[2],
                       usedSpace=toBiggestBytes(tryTrunk(driveInfo[1])),
                       totalSpace=toBiggestBytes(tryTrunk(driveInfo[0])),
                       percent=tryTrunk(driveInfo[3])))
     if scriptHandler.getLastScriptRepeatCount() == 0:
         ui.message(" ".join(info))
     else:
         if api.copyToClip(" ".join(info)): ui.message(self.RMCopyMessage)
Пример #17
0
 def startRecognition(self, current_source, current_engine_type):
     try:
         engine = self.getCurrentEngine(current_engine_type)
         repeatCount = scriptHandler.getLastScriptRepeatCount()
         textResultWhenRepeatGesture = not config.conf["onlineOCRGeneral"][
             "swapRepeatedCountEffect"]
         if not current_source == "clipboardImage" and self.isScreenCurtainRunning(
         ):
             ui.message(
                 _("Please disable screen curtain before recognition."))
             return
         if repeatCount == 0:
             if not engine:
                 ui.message(_("Cannot get recognition engine"))
                 return
             engine.text_result = textResultWhenRepeatGesture
             if current_source == "navigatorObject":
                 recogUi.recognizeNavigatorObject(engine)
                 return
             else:
                 imageInfo, recognizeImage = self.getImageFromSource(
                     current_source)
                 if not recognizeImage:
                     ui.message(
                         _("Clipboard URL source is not implemented."))
                     return
                 pixels = recognizeImage.tobytes("raw", "BGRX")
                 # Translators: Reported when content recognition begins.
                 ui.message(_("Recognizing"))
                 engine.recognize(pixels, imageInfo, recogUi._recogOnResult)
         elif repeatCount == 1:
             engine.text_result = not textResultWhenRepeatGesture
     except Exception as e:
         from logHandler import log
         log.error(getattr(e, 'message', repr(e)))
         ui.message(
             _("Error occurred, when trying to start recognition, Please change source or engine and try again."
               ))
Пример #18
0
	def script_toggleBackgroundEncoderMonitor(self, gesture):
		if scriptHandler.getLastScriptRepeatCount()==0:
			if not self.backgroundMonitor:
				encoderMonCount[self.encoderType] += 1 # Multiple encoders.
				# Translators: Presented when toggling the setting to monitor the selected encoder.
				ui.message(_("Monitoring encoder {encoderNumber}").format(encoderNumber = self.IAccessibleChildID))
			else:
				encoderMonCount[self.encoderType] -= 1
				# Translators: Presented when toggling the setting to monitor the selected encoder.
				ui.message(_("Encoder {encoderNumber} will not be monitored").format(encoderNumber = self.IAccessibleChildID))
			self._setFlags(self.encoderId, not self.backgroundMonitor, SPLBackgroundMonitor, "BackgroundMonitor")
			if self.backgroundMonitor:
				try:
					monitoring = self.threadPool[self.IAccessibleChildID].is_alive()
				except KeyError:
					monitoring = False
				if not monitoring: self.connectStart()
		else:
			for encoderType in encoderMonCount:
				encoderMonCount[encoderType] = 0
			SPLBackgroundMonitor.clear()
			# Translators: Announced when background encoder monitoring is canceled.
			ui.message(_("Encoder monitoring canceled"))
Пример #19
0
 def script_announceBatteryInfo(self, gesture):
     battery.getInfo()
     if battery.noBattery:
         # Translators: Message reported when there is no battery on the system, mostly laptops with battery pack removed and running on AC power.
         info = _("This computer does not have a battery connected.")
     elif not battery.onBattery:
         # Translators: message presented when AC is connected and battery is charging, also show current battery percentage.
         info = _("{percent}%, battery charging.").format(
             percent=tryTrunk(battery.percentage))
     elif battery.onBattery:
         # Translators: message presented when computer is running on battery power, showing percentage remaining and estimated remaining time.
         info = _("{percent}% battery remaining, about {time}.").format(
             percent=tryTrunk(battery.percentage), time=battery.timeLeft)
         if battery.low:
             # Translators: Message reported when battery level is low.
             info += _(" Warning: low battery.")
         elif battery.critical:
             # Translators: Message reported when battery level is critical.
             info += _(" Warning: battery is critically low.")
     if scriptHandler.getLastScriptRepeatCount() == 0:
         ui.message(info)
     else:
         if api.copyToClip(info): ui.message(self.RMCopyMessage)
Пример #20
0
def script_braille_routeTo(self, gesture):
    obj = obj = api.getNavigatorObject()
    if (config.conf["brailleExtender"]['routingReviewModeWithCursorKeys']
            and obj.hasFocus and braille.handler._cursorPos and
        (obj.role == controlTypes.ROLE_TERMINAL or
         (obj.role == controlTypes.ROLE_EDITABLETEXT
          and braille.handler.tether == braille.handler.TETHER_REVIEW))):
        speechMode = speech.speechMode
        speech.speechMode = 0
        nb = braille.handler._cursorPos - gesture.routingIndex
        i = 0
        key = "leftarrow" if nb > 0 else "rightarrow"
        while i < abs(nb):
            keyboardHandler.KeyboardInputGesture.fromName(key).send()
            i += 1
        speech.speechMode = speechMode
        speech.speakSpelling(getCurrentChar())
        return
    braille.handler.routeTo(gesture.routingIndex)
    if scriptHandler.getLastScriptRepeatCount(
    ) == 0 and config.conf["brailleExtender"]['speakRoutingTo']:
        ch = getCurrentChar()
        if ch != "": speech.speakSpelling(ch)
Пример #21
0
 def script_readColumn(self, gesture):
     # ask for index
     num = self.getIndex(gesture.mainKeyName.rsplit('+', 1)[-1])
     if num > self.childCount:
         # Translators: message when digit pressed exceed the columns number
         ui.message(_("No more columns available"))
         return
     # for invisible column case
     num = self.getFixedNum(num)
     # getChild is zero-based
     obj = self.getChild(num - 1)
     # None obj should be generated
     # only in invisible column case
     if not obj:
         # Translators: message when digit pressed not match a visible column
         ui.message(_("No more visible columns available"))
         return
     # generally, an empty name is a None object,
     # in Mozilla, instead, it's a unicode object with length 0
     if obj.name and len(obj.name):
         # obj.name is the column content
         content = ''.join([obj.name, ";"])
     else:
         # Translators: message when cell in specified column is empty
         content = _("Not available;")
     global readHeader, copyHeader
     if getLastScriptRepeatCount() and self.lastColumn == num:
         header = ''.join([obj.columnHeaderText, ": "
                           ]) if copyHeader else ""
         if api.copyToClip(header + content):
             # Translators: message announcing what was copied
             ui.message(_("Copied in clipboard: %s") % (header + content))
     else:
         header = ''.join([obj.columnHeaderText, ": "
                           ]) if readHeader else ""
         self.lastColumn = num
         ui.message(header + content)
Пример #22
0
def script_braille_routeTo(self, gesture):
    obj = obj = api.getNavigatorObject()
    if (config.conf["brailleExtender"]['routingReviewModeWithCursorKeys']
            and obj.hasFocus and braille.handler._cursorPos
            and (obj.role == controlTypes.ROLE_TERMINAL or
                 (obj.role == controlTypes.ROLE_EDITABLETEXT
                  and getTether() == braille.handler.TETHER_REVIEW))):
        speechMode = speech.speechMode
        speech.speechMode = 0
        nb = braille.handler._cursorPos - gesture.routingIndex
        i = 0
        key = "leftarrow" if nb > 0 else "rightarrow"
        while i < abs(nb):
            keyboardHandler.KeyboardInputGesture.fromName(key).send()
            i += 1
        speech.speechMode = speechMode
        speech.speakSpelling(getCurrentChar())
        return
    try:
        braille.handler.routeTo(gesture.routingIndex)
    except LookupError:
        pass
    if scriptHandler.getLastScriptRepeatCount(
    ) == 0 and config.conf["brailleExtender"]["speakRoutingTo"]:
        region = braille.handler.buffer
        if region.cursorPos is None: return
        try:
            start = region.brailleToRawPos[
                braille.handler.buffer.windowStartPos + gesture.routingIndex]
            _, endBraillePos = brailleRegionHelper.getBraillePosFromRawPos(
                region, start)
            end = region.brailleToRawPos[endBraillePos + 1]
            ch = region.rawText[start:end]
            if ch:
                speech.speakMessage(getSpeechSymbols(ch))
        except IndexError:
            pass
Пример #23
0
	def script_announceDropbox(self, gesture):
		# We get the systray
		l=("shell_TrayWnd","TrayNotifyWnd","SysPager","ToolbarWindow32")
		h,FindWindowExA =0,winUser.user32.FindWindowExA
		for element in l:
			h=FindWindowExA(h,0,element,0)

		o=NVDAObjects.IAccessible.getNVDAObjectFromEvent(h,-4,1)
		name=o.name
		while not name.lower().startswith("dropbox"):
			o=o.next
			if not o :
				ui.message(_("drop box not found"))
				return
			else:
				name=o.name


		name =name.split ()
		# We get the number of call of this script
		repeatCount =scriptHandler.getLastScriptRepeatCount()
		if repeatCount ==0 :
			del (name[1])
			name=" ".join (name)
		elif repeatCount ==1:
			name = " ".join(name[0:2])
		else:
			# If we are already inside of the context menu, stop the script
			objFocused = api.getFocusObject()
			currentProcess = objFocused.appModule.appName.lower()
			if (currentProcess.lower() == u'dropbox' and objFocused.windowClassName.lower() == u'#32768') and (objFocused.role == controlTypes.ROLE_POPUPMENU or objFocused.role == controlTypes.ROLE_MENUITEM):
				return
			else:
				rightMouseButton (o)
			return
		ui.message (name)
Пример #24
0
    def script_attachments(self, gesture):
        obj = api.getFocusObject()
        appVersionMaj = int(obj.appModule.productVersion.split('.')[0])

        try:
            if appVersionMaj >= 16:  #Outlook 2016+
                attachmentsList, handle, namesGen, windowName = self.getAttachmentInfos2016(
                )
            else:
                attachmentsList, handle, namesGen, windowName = self.getAttachmentInfos2013(
                )
        except LookupError:
            self.errorBeep()
            return
        self.nAttachments = len(attachmentsList)
        if getLastScriptRepeatCount() == 1 and self.nAttachments > 0:
            # double press, set focus in field
            self.focusInfo['firstObj'].setFocus()
            winUser.setForegroundWindow(self.focusInfo['handle'])
        else:
            # single press
            self.focusInfo = {'handle': handle}
            try:
                self.focusInfo['firstObj'] = attachmentsList[0]
            except IndexError:
                self.focusInfo['firstObj'] = None
            #Launch the attachments announcement code in a different thread since it can take time in the case of numerous attachments (above 17 on my machine).
            #In this case, getLastScriptRepeatCount() after double press will return 0 instead of 1.
            def announceAttachments():
                msg = (
                    windowName + ": " + str(self.nAttachments) +
                    '. ' +  #Attachments number
                    ', '.join(namesGen))
                core.callLater(0, ui.message, msg)

            threading.Thread(target=announceAttachments).start()
Пример #25
0
    def script_readStatusBar(self, gesture):
        obj = api.getFocusObject()
        while obj and obj.role != controlTypes.ROLE_STATUSBAR and obj.simpleParent and obj.simpleParent.role != controlTypes.ROLE_APPLICATION:
            obj = obj.simpleParent

        while obj:
            if obj.role is controlTypes.ROLE_STATUSBAR:
                msgs = []
                obj = obj.simpleFirstChild
                api.setNavigatorObject(obj)
                while obj:
                    msgs.append(obj.name)
                    obj = obj.simpleNext
                scriptCount = getLastScriptRepeatCount()
                if scriptCount == 0:
                    braille.handler.message("  ".join(msgs))
                    for e in msgs:
                        speech.speakMessage(
                            e, speech.priorities.SpeechPriority.NEXT)
                else:
                    ui.browseableMessage('\n'.join(msgs))
                return
            obj = obj.simpleNext
        ui.message(_("Unable to find status bar"))
Пример #26
0
 def script_elapsedTime(self, gesture):
     if isStarting():
         sayMessage(announce[3])
         return
     if isRecording():
         message(announce[4])
         return
     if checkSelection() or checkPart():
         if not actualDuration():
             text = announce[1]
         elif actualDuration() == totalTime():
             text = u'{0} {1} {2} {3}'.format(_('Elapsed time: '),
                                              actualDuration(), announce[2],
                                              actualDurationPercentage())
         else:
             # Translators: Message to indicate the elapsed time.
             text = u'{0} {1} {2}'.format(_('Elapsed time: '),
                                          actualDuration(),
                                          actualDurationPercentage())
         repeat = getLastScriptRepeatCount()
         if repeat == 0:
             message(text)
         elif repeat == 1:
             message(u'{0} {1}'.format(announce[8], totalTime()))
Пример #27
0
	def script_sayCurKeyboardLanguage (self, gesture):
		import winUser
		import scriptHandler
		import ctypes
		import languageHandler
		# Getting the handle of the foreground window.
		curWindow = winUser.getForegroundWindow()
		# Getting the threadID.
		threadID = winUser.getWindowThreadProcessID(curWindow)[1]
		# Getting the keyboard layout iD.
		klID = winUser.getKeyboardLayout(threadID)
		# Extract language ID from klID.
		lID = klID & (2**16 - 1)
		# Getting the current keyboard language description from ctypes.windll.kernel32.GetLocaleInfoW.
		# Some language IDs are not available in the local.windows_locale dictionary, it is best to search their description directly in Windows itself
		buf = ctypes.create_unicode_buffer (1024)
		ctypes.windll.kernel32.GetLocaleInfoW (lID, languageHandler.LOCALE_SLANGUAGE, buf, 1024)
		desc = buf.value
		defaultOsl = locale.getdefaultlocale()[0]
		repeatCount = scriptHandler.getLastScriptRepeatCount()
		if repeatCount == 0:
			ui.message (desc)
		else:
			ui.message (languageHandler.getLanguageDescription (defaultOsl))
Пример #28
0
    def script_startRecognition(self, gesture):
        obj = api.getNavigatorObject()
        if controlTypes.STATE_OFFSCREEN in obj.states:
            errorHandler('OFF_SCREEN')
            return

        try:
            x, y, width, height = obj.location
        except:
            errorHandler('CAPTCHA_HAS_NO_LOCATION')
            return

        if _config.conf[
                'sizeReport'] and scriptHandler.getLastScriptRepeatCount(
                ) != 1:
            ui.message(_('Size: {0} X {1} pixels').format(width, height))
            return

        bmp = wx.EmptyBitmap(width, height)
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, width, height, wx.ScreenDC(), x, y)
        wx.CallAfter(interface.getInstruction,
                     self.sendCaptcha,
                     image=bmp.ConvertToImage())
Пример #29
0
 def script_speakParent(self, gesture):
     count=scriptHandler.getLastScriptRepeatCount()
     # Translators: error message if parent couldn't be found)
     errorMsg = _("No parent item in this tree view")
     self.moveInTree(-1, errorMsg, unbounded=True, op=operator.lt, speakOnly=True, moveCount=count+1)
Пример #30
0
	def script_analyzeObject(self, gesture):
		if not self.isVirtual: self.isVirtual = scriptHandler.getLastScriptRepeatCount()>0
		if self.isVirtual: return True
		if self.tmr: self.tmr.cancel()
		speech.cancelSpeech()
		p = self.getFilePath()
		if p == True:
			ui.message(_("Analyzing selected file"))
		else:
			ui.message(_("Analyzing navigator object"))
		try: nav = api.getNavigatorObject()
		except: return False

		try:
			screenCurtainId = ScreenCurtainProvider.getSettings().getId()
			screenCurtainProviderInfo = vision.handler.getProviderInfo(screenCurtainId)
			isScreenCurtainRunning = bool(vision.handler.getProviderInstance(screenCurtainProviderInfo))
			if isScreenCurtainRunning:
				# Translators: Reported when screen curtain is enabled.
				ui.message(_("Please disable screen curtain before using CloudVision add-on."))
				return
		except:
			pass

		if self.isWorking: return False
		self.isWorking = True

		if not nav.location and p == False:
			speech.cancelSpeech()
			ui.message(_("This navigator object is not analyzable"))
			return
		if p == False:
			left, top, width, height = nav.location

		if (p == False) and (width < 1 or height < 1):
			return False
		if p == False:
			bmp = wx.Bitmap(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())
		if p == True:
			with open(filePath, "rb") as f:
				body = f.read()
			img_str = base64.b64encode(body)

		sound = getConfig()['sound']
		s=0
		if sound: s=1
		textonly = getConfig()['textonly']
		imageonly = getConfig()['imageonly']
		target = "all"
		if textonly and not imageonly: target = "text"
		if not textonly and imageonly: target = "image"
		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, img_str, lang, s, target, t, q])
		self.tmr.start()
Пример #31
0
	def script_createList(self, gesture):
		if scriptHandler.getLastScriptRepeatCount() == 0:
			self._createSystrayList()
		else:
			self._createTaskList()
 def script_reportOrJumpTo_beep(self, gesture):
     if scriptHandler.getLastScriptRepeatCount() <= 1:
         self.reportOrJumpTo(showJumpToDialog=bool(
             scriptHandler.getLastScriptRepeatCount() == 1))
     return
Пример #33
0
 def script_GetFontInfo(self, gesture):
     focus = api.getFocusObject()
     formatting = []
     if shared.isWebElement(focus):
         info = focus.makeTextInfo(textInfos.POSITION_CARET)
         info.expand(textInfos.UNIT_CHARACTER)
         fields = info.getTextWithFields()
         for field in fields:
             if isinstance(field, textInfos.FieldCommand) and isinstance(
                     field.field, textInfos.FormatField):
                 for key in config.conf["developertoolkit"]["fontInfo"]:
                     try:
                         if shared.isDetailedMessages():
                             # Specialized color formatting rules.
                             if shared.isColor(field.field[key]):
                                 if shared.colorAsName():
                                     formatting.append(u"{}: {}".format(
                                         key, field.field[key].name))
                                 elif shared.colorAsHex():
                                     formatting.append(
                                         u"{}: #{:02x}{:02x}{:02x}".format(
                                             key, field.field[key].red,
                                             field.field[key].green,
                                             field.field[key].blue))
                                 elif shared.colorAsRGB():
                                     formatting.append(u"{}: {}".format(
                                         key, field.field[key]))
                             # There are no more specialized formatting rules to apply.
                             else:
                                 formatting.append(u"{}: {}".format(
                                     key, field.field[key]))
                         # Formatting rules to apply when detailed messages is disabled.
                         else:
                             # Specialized rules to apply when the formatting fields have True/False values such as bold, italic, underline.
                             if shared.isBool(field.field[key]):
                                 if field.field[key] == True:
                                     formatting.append(u"{}".format(key))
                                 else:
                                     pass
                             # The formatting rules for color values.
                             elif shared.isColor(field.field[key]):
                                 if shared.colorAsName():
                                     formatting.append(u"{}".format(
                                         field.field[key].name))
                                 elif shared.colorAsHex():
                                     formatting.append(
                                         u"#{:02x}{:02x}{:02x}".format(
                                             field.field[key].red,
                                             field.field[key].green,
                                             field.field[key].blue))
                                 elif shared.colorAsRGB():
                                     formatting.append(
                                         u"RGB({}, {}, {})".format(
                                             field.field[key].red,
                                             field.field[key].green,
                                             field.field[key].blue))
                             # There are no more formatting rules to follow.
                             else:
                                 formatting.append(u"{}".format(
                                     field.field[key]))
                     except KeyError:
                         pass
         message = u"\n".join(formatting)
         if getLastScriptRepeatCount() == 0:
             ui.message(message)
         elif getLastScriptRepeatCount() >= 1:
             shared.copyToClipboard(message)
     else:
         message = u"Only available in web content."
         ui.message(message)
 def script_report_location(self, gesture):
     stopScriptTimer()
     doc = self.WinwordDocumentObject
     (start, end) = (self.WinwordSelectionObject.Start,
                     self.WinwordSelectionObject.End)
     r = doc.range(start, start)
     left = self.getLocalizedMeasurementTextForPointSize(
         r.information(wdHorizontalPositionRelativeToPage))
     top = self.getLocalizedMeasurementTextForPointSize(
         r.information(wdVerticalPositionRelativeToPage))
     # Translators:  message in report location script.
     position = _(
         "at {0} from left edge and {1} from top edge of the page").format(
             left, top)
     if start == end:
         if self.inTable():
             cell = r.Cells[0]
             (row, col) = (cell.rowIndex, cell.columnIndex)
             # Translators: message in report location script.
             location = _(
                 "You are at the row {row}, column {column}  of table"
             ).format(row=row, column=col)
             text = "%s, %s." % (location, position)
         else:
             line = r.information(wdFirstCharacterLineNumber)
             column = r.information(wdFirstCharacterColumnNumber)
             page = r.Information(wdActiveEndPageNumber)
             location = _(
                 "you are at Line {line}, column {column} of page {page}"
             ).format(line=line, column=column, page=page)
             text = "%s, %s." % (location, position)
     else:
         line = r.information(wdFirstCharacterLineNumber)
         column = r.information(wdFirstCharacterColumnNumber)
         page = r.Information(wdActiveEndPageNumber)
         location = _(
             "Selection begins at line {line}, column {column} of page {page}"
         ).format(line=line, column=column, page=page)
         text = "%s, %s." % (location, position)
         r = doc.range(end - 1, end)
         line = r.information(wdFirstCharacterLineNumber)
         column = r.information(wdFirstCharacterColumnNumber)
         page = r.Information(wdActiveEndPageNumber)
         left = self.getLocalizedMeasurementTextForPointSize(
             r.information(wdHorizontalPositionRelativeToPage))
         top = self.getLocalizedMeasurementTextForPointSize(
             r.information(wdVerticalPositionRelativeToPage))
         position = _(
             "at {0} from left edge and {1} from top edge of the page."
         ).format(left, top)
         location = _(
             "It ends at line {line}, column {column} of page {page}"
         ).format(line=line, column=column, page=page)
         text = text + "\r\n" + "%s, %s" % (location, position)
     count = scriptHandler.getLastScriptRepeatCount()
     if count > 0:
         # Translators: this is the title of informationdialog box to show appModule informations.
         dialogTitle = _("Location information")
         InformationDialog.run(None, dialogTitle, "", text)
     else:
         ui.message(text)
Пример #35
0
 def script_zLauncher(self, event):
     if getLastScriptRepeatCount() == 0:
         core.callLater(200, lambda: self.zlauncherClick(None))
     elif getLastScriptRepeatCount() == 1:
         self.doblePulsacion = True
         core.callLater(100, lambda: self.zlauncherDobleClick(None))
Пример #36
0
 def script_zNotes(self, event):
     if getLastScriptRepeatCount() == 0:
         core.callLater(200, lambda: self.znotaClick(None))
     elif getLastScriptRepeatCount() == 1:
         self.doblePulsacion = True
         core.callLater(100, lambda: self.znotaDobleClick(None))
Пример #37
0
	def script_dateTime(self,gesture):
		if scriptHandler.getLastScriptRepeatCount()==0:
			text=winKernel.GetTimeFormat(winKernel.LOCALE_USER_DEFAULT, winKernel.TIME_NOSECONDS, None, None)
		else:
			text=winKernel.GetDateFormat(winKernel.LOCALE_USER_DEFAULT, winKernel.DATE_LONGDATE, None, None)
		ui.message(text)
Пример #38
0
 def script_zNotesCopy(self, gesture):
     if getLastScriptRepeatCount() == 0:
         core.callLater(200, lambda: self.selectNewNote(None))
     elif getLastScriptRepeatCount() == 1:
         self.doblePulsacion = True
         core.callLater(100, lambda: self.newNote(None))
Пример #39
0
 def script_announceWinVer(self, gesture):
     info = self.getWinVer()
     if scriptHandler.getLastScriptRepeatCount() == 0:
         ui.message(info)
     else:
         if api.copyToClip(info): ui.message(self.RMCopyMessage)
Пример #40
0
 def script_viewAsciiMathAsSourceMathML(self, gesture):
     if isSecureMode(): return
     if scriptHandler.getLastScriptRepeatCount():
         tones.beep(440, 50)
     else:
         processText('AsciiMath', source=True)
Пример #41
0
 def script_announceRecordingPeak(self, gesture):
     repeatCount = scriptHandler.getLastScriptRepeatCount()
     #if repeatCount==0:
     rPeak = self.getToolBar('Recording Meter ').getChild(1).name.partition(
         'Peak')[2]
     ui.message(rPeak)
Пример #42
0
 def script_selectionCol(self, gesture):
     if scriptHandler.getLastScriptRepeatCount() == 0:
         self._tableau.selectionCol()
     else:
         self._tableau.resetSelectionCol()
Пример #43
0
 def script_speakObject(self, gesture):
     if scriptHandler.getLastScriptRepeatCount() == 0:
         self.playObject(NVDAObjects.api.getFocusObject())
     globalCommands.commands.script_reportCurrentFocus(gesture)
Пример #44
0
 def script_speakParent(self, gesture):
     focus = api.getFocusObject()
     count=scriptHandler.getLastScriptRepeatCount()
     # Translators: error message if parent couldn't be found (in editable control or in browser)
     msgEditable = _("No parent of indentation block")
     self.move(-1, [msgEditable], unbounded=True, op=operator.lt, speakOnly=True, moveCount=count+1)
Пример #45
0
 def script_viewLaTeXAsInteractiveMathML(self, gesture):
     if isSecureMode(): return
     if scriptHandler.getLastScriptRepeatCount():
         tones.beep(440, 50)
     else:
         processText('LaTeX')