Beispiel #1
0
	def onTables(self, evt):
		keycode = evt.GetKeyCode()
		if keycode in [ord(','), ord(';')]:
			idx, tbl = self.getCurrentSelection()
			if keycode == ord(','):
				queueHandler.queueFunction(queueHandler.eventQueue, ui.message, "%s" % tbl)
			else:
				ui.browseableMessage('\n'.join([
					_("Table name: %s") % addoncfg.tablesTR[idx],
					_("File name: %s") % tbl,
					_("In switches: %s") % self.getInSwitchesText(tbl)
					]), _("About this table"), False)
		if keycode == wx.WXK_F1:
			ui.browseableMessage(
				_("""Braille tables usable from NVDA are listed. Press space, left arrow, or right arrow keys to include (or exclude) the selected table in switches.\n
			You can also press 'comma' key to get the file name of the selected table, and 'semicolon' key to view miscellaneous information on the selected table."""),
			_("Contextual help"), False)
		if keycode in [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_SPACE]:
			idx, tbl = self.getCurrentSelection()
			if keycode == wx.WXK_LEFT: self.changeSwitch(tbl, 0, False)
			elif keycode == wx.WXK_RIGHT: self.changeSwitch(tbl, 1, False)
			elif keycode == wx.WXK_SPACE: self.changeSwitch(tbl, 1, True)
			newSwitch = self.getInSwitchesText(tbl)
			self.tables.SetString(self.tables.GetSelection(), "%s%s: %s" % (addoncfg.tablesTR[idx], punctuationSeparator, newSwitch))
			queueHandler.queueFunction(queueHandler.eventQueue, ui.message, "%s" % newSwitch)
			utils.refreshBD()
		else: evt.Skip()
    def onOk(self, evt):
        global memo
        tx = self.searchWordEdit.GetValue()
        kwrd = tx.lower().strip('\'\"-,.:;!? ')

        lemmas = loadVocabulary()
        if kwrd in lemmas.keys():
            memo = (_('Found "{thisword}":\n %s').format(thisword=kwrd) %
                    lemmas.get(kwrd))
            # Translators: title of browseable message box.
            ui.browseableMessage(
                ".\n".join(memo.split(". ")),
                _("From {vocs}").format(vocs=getVocsName()[
                    config.conf["vocabulary"]["myvocabulary"]]))
            self.Destroy()
        else:
            # Translator: message when the searched word is not present in the vocabulary.
            gui.messageBox(
                _("Sorry, no match found for {thisword}. Selected vocabulary: {vocs}."
                  ).format(thisword=kwrd,
                           vocs=getVocsName()[config.conf["vocabulary"]
                                              ["myvocabulary"]]),
                # Translators: Title of warning dialog.
                _("NotFound!"),
                wx.OK)
Beispiel #3
0
 def script_showClipboardRawText(self, gesture):
     try:
         text = api.getClipData()
     except Exception:
         text = None
     if not text:
         if self.clipboardHasContent():
             # Translators: presented when clipboard is not empty, but there is no text to show in browse mode.
             ui.message(
                 _("Clipboard is not empty, but there is no text to show"))
         else:
             # Translators: presented when clipboard is empty.
             ui.message(_("Clipboard is empty"))
     else:
         if (config.conf["clipContentsDesigner"]
             ["maxLengthForBrowseableText"] <= len(text)):
             maxLength = config.conf["clipContentsDesigner"][
                 "maxLengthForBrowseableText"]
         else:
             maxLength = len(text)
         browseableText = text.strip()[:maxLength]
         ui.browseableMessage(
             browseableText,
             # Translators: title of a browseable message.
             _("Clipboard text ({max}/{current} - {formatForTitle})".format(
                 max=maxLength, current=len(text),
                 formatForTitle=RAW_TEXT)),
             False)
Beispiel #4
0
	def displayCurrentCharInfoMessage(self):
		### Code inspired from NVDA script_review_currentCharacter in file globalCommands.py
		info=api.getReviewPosition().copy()
		info.expand(textInfos.UNIT_CHARACTER)
		if info.text == '':
			speech.speakTextInfo(info,unit=textInfos.UNIT_CHARACTER,reason=controlTypes.REASON_CARET)
			return
		font = self.getCurrCharFontName(info)
		try:
			c = ord(info.text)
		except TypeError:
			# This might be a character taking multiple code points.
			# If it is a 32 bit character, encode it to UTF-32 and calculate the ord manually.
			# In Python 3, this is no longer necessary.
			try:
				encoded = info.text.encode("utf_32_le")
			except UnicodeEncodeError:
				c = None
			else:
				if len(encoded)==4:
					c = sum(ord(cp)<<i*8 for i, cp in enumerate(encoded))
				else:
					c = None
		### End code copy
		
		if c is not None:
			char = Character(c, info.text, font)
			computedInfoList = [(t, getattr(char, f)()) for t,f in requiredInfoList]
			if char.isMsFont():
				computedInfoList.extend([(t, getattr(char, f)()) for t,f in msCharInfoList])
		else:
			computedInfoList = [(t,'N/A') for t,f in requiredInfoList]
		infoTable = createHtmlInfoTable(computedInfoList )
		htmlMessage = gHtmlMessage.format(infoTable=infoTable)
		ui.browseableMessage(htmlMessage, title=pageTitle, isHtml= True)
Beispiel #5
0
	def script_getTableOverview(self, gesture):
		inTable = brailleInput.handler.table.displayName
		ouTable = configBE.tablesTR[configBE.tablesFN.index(config.conf["braille"]["translationTable"])]
		grade = [_('uncontracted'), _('contracted')]
		t = (_(' Input table')+': %s\n'+_('Output table')+': %s\n\n') % (inTable+' (%s)' % (brailleInput.handler.table.fileName), ouTable+' (%s)' % (config.conf["braille"]["translationTable"]))
		t += utils.getTableOverview()
		ui.browseableMessage('<pre>%s</pre>' % t, _('Table overview (%s)' % brailleInput.handler.table.displayName), True)
Beispiel #6
0
def currentCharDesc(ch: str = '', display: bool = True) -> str:
    if not ch: ch = getCurrentChar()
    if not ch: return ui.message(_("Not a character"))
    c = ord(ch)
    if c:
        try:
            char_name = unicodedata.name(ch)
        except ValueError:
            char_name = _("unknown")
        char_category = unicodedata.category(ch)
        HUC_repr = "%s, %s" % (huc.translate(ch, False), huc.translate(
            ch, True))
        speech_output = getSpeechSymbols(ch)
        brl_repr = getTextInBraille(ch)
        brl_repr_desc = huc.unicodeBrailleToDescription(brl_repr)
        s = (f"{ch}: {hex(c)}, {c}, {oct(c)}, {bin(c)}\n"
             f"{speech_output} ({char_name} [{char_category}])\n"
             f"{brl_repr} ({brl_repr_desc})\n"
             f"{HUC_repr}")
        if not display: return s
        if scriptHandler.getLastScriptRepeatCount() == 0: ui.message(s)
        elif scriptHandler.getLastScriptRepeatCount() == 1:
            ui.browseableMessage(s, (r"U+%.4x (%s) - " % (c, ch)) +
                                 _("Char info"))
    else:
        ui.message(_("Not a character"))
Beispiel #7
0
 def onOpenDoc(self, evt):
     # This is the function that will handle the events of "add-ons commands"submenu.
     import ui
     addonDic = {}
     self.updateAddonDic(addonDic)
     #. Translators: Name of the list.
     message = u"<h1>{title}</h1><br>".format(
         title=_("List of commands for running add-ons"))
     for addon in sorted(addonDic, key=lambda item: item.lower()):
         message += u"<h2>{addonSum}</h2>\n<table>\n<tr><th>".format(
             addonSum=addon)
         #. Translators: The title of the column containing the documentation of each of the scripts.
         message += _("Documentation")
         message += "</th><th>"
         #. Translators: The title of the column containing the command of each of the scripts.
         message += _("Gesture")
         message += "</th></tr>\n"
         script = addonDic[addon]
         for gesture in sorted(script):
             message += u"<tr><td>{doc}</td><td>{gesture}</td></tr>\n".format(
                 doc=script[gesture], gesture=gesture)
         message += "</table>\n"
     ui.browseableMessage(
         message,
         #. Translators: Title of the HTML message.
         _("Add-ons documentation"),
         True)
    def script_showResponse(self, gesture: InputGesture) -> None:
        """Show deserialized remote server response in human readable format,
		report if dictionary queries have not yet been performed.
		@param gesture: gesture assigned to this method
		@type gesture: InputGesture
		"""
        if not self._lastTranslator:
            # Translators: Information about the online service
            ui.message(_("There is no dictionary queries"))
            return
        from json import dumps
        service = services[getattr(self._lastTranslator, 'id',
                                   config.conf[addonName]['active'])]
        ui.browseableMessage(
            message=dumps(self._lastTranslator.resp,
                          skipkeys=True,
                          ensure_ascii=False,
                          indent=4),
            # Translators: The title of the window that displays the desiralized response from the server
            title=_("Response from") +
            ' "{server}": {text:.15s} ({langFrom}-{langTo})'.format(
                server=service.summary,
                text=self._lastTranslator.text,
                langFrom=service.langs[self._lastTranslator.langFrom].name,
                langTo=service.langs[self._lastTranslator.langTo].name),
            isHtml=False)
Beispiel #9
0
 def onTables(self, evt):
     keycode = evt.GetKeyCode()
     if keycode in [ord(','), ord(';')]:
         idx, tbl = self.getCurrentSelection()
         if keycode == ord(','):
             queueHandler.queueFunction(queueHandler.eventQueue, ui.message,
                                        "%s" % tbl)
         else:
             ui.browseableMessage(
                 '\n'.join([
                     _("Table name: %s") % configBE.tablesTR[idx],
                     _("File name: %s") % tbl,
                     _("In switches: %s") % self.getInSwitchesText(tbl)
                 ]), _("About this table"), False)
     if keycode == wx.WXK_F1:
         ui.browseableMessage(
             _("In this combo box, all tables are present. Press space bar, left or right arrow keys to include (or not) the selected table in switches"
               ) + ".\n" +
             _("You can also press 'comma' key to get the file name of the selected table and 'semicolon' key to view miscellaneous infos on the selected table"
               ) + ".", _("Contextual help"), False)
     if keycode in [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_SPACE]:
         idx, tbl = self.getCurrentSelection()
         if keycode == wx.WXK_LEFT: self.changeSwitch(tbl, 0, False)
         elif keycode == wx.WXK_RIGHT: self.changeSwitch(tbl, 1, False)
         elif keycode == wx.WXK_SPACE: self.changeSwitch(tbl, 1, True)
         newSwitch = self.getInSwitchesText(tbl)
         self.tables.SetString(
             self.tables.GetSelection(),
             "%s%s: %s" % (configBE.tablesTR[idx], configBE.sep, newSwitch))
         queueHandler.queueFunction(queueHandler.eventQueue, ui.message,
                                    "%s" % newSwitch)
         utils.refreshBD()
     else:
         evt.Skip()
Beispiel #10
0
 def script_showCaretSymbol(self, gesture):
     obj = api.getFocusObject()
     treeInterceptor = obj.treeInterceptor
     if isinstance(treeInterceptor,
                   treeInterceptorHandler.DocumentTreeInterceptor
                   ) and not treeInterceptor.passThrough:
         obj = treeInterceptor
     try:
         info = obj.makeTextInfo(textInfos.POSITION_CARET)
     except:
         info = obj.makeTextInfo(textInfos.POSITION_FIRST)
     info.expand(textInfos.UNIT_CHARACTER)
     curLanguage = self._getCurrentLanguageForTextInfo(info)
     text = info.text
     expandedSymbol = characterProcessing.processSpeechSymbol(
         curLanguage, text)
     if expandedSymbol == text:
         # Translators: Reported when there is no replacement for the symbol at the position of the caret.
         ui.message(_("No symbol replacement"))
         return
     # Translators: Character and its replacement used from the "Review current Symbol" command. Example: "Character: ? Replacement: question"
     message = _("Character: {}\nReplacement: {}").format(
         text, expandedSymbol)
     languageDescription = languageHandler.getLanguageDescription(
         curLanguage)
     # Translators: title for expanded symbol dialog. Example: "Expanded symbol (English)"
     title = _("Symbol at the caret position ({})").format(
         languageDescription)
     ui.browseableMessage(message, title)
Beispiel #11
0
 def script_showClipboardText(self, gesture):
     try:
         text = api.getClipData()
     except Exception:
         text = None
     if not text:
         if self.clipboardHasContent():
             # Translators: presented when clipboard is not empty, but there is no text to show in browse mode.
             ui.message(
                 _("Clipboard is not empty, but there is no text to show"))
         else:
             # Translators: presented when clipboard is empty.
             ui.message(_("Clipboard is empty"))
     else:
         if (config.conf["clipContentsDesigner"]
             ["maxLengthForBrowseableText"] <= len(text)):
             maxLength = config.conf["clipContentsDesigner"][
                 "maxLengthForBrowseableText"]
         else:
             maxLength = len(text)
         format = config.conf["clipContentsDesigner"][
             "browseableTextFormat"]
         html = True
         if format == 0:
             browseableText = "<pre>%s</pre>" % text.strip()[:maxLength]
         else:
             browseableText = text.strip()[:maxLength]
         ui.browseableMessage(
             browseableText,
             # Translators: title of a browseable message.
             _("Clipboard text ({max}/{current} - {formatForTitle})".format(
                 max=maxLength,
                 current=len(text),
                 formatForTitle=BROWSEABLETEXT_FORMATS[format])),
             html)
Beispiel #12
0
 def script_readDoc(self, gesture):
     obj = self.getEditor()
     if not obj:
         return ui.message(_("Editor not found"))
     obj = obj.simpleNext
     if not obj:
         return ui.message(_("Nothing"))
     else:
         msgs = []
         while obj:
             if obj.role in [
                     controlTypes.ROLE_TOOLTIP, controlTypes.ROLE_STATICTEXT
             ]:
                 if obj.role == controlTypes.ROLE_TOOLTIP:
                     obj = obj.simpleFirstChild
                 if obj.name.strip() and obj.name != '':
                     if obj.description:
                         msgs.append(f"{obj.name} {obj.description}")
                     else:
                         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))
Beispiel #13
0
 def script_notifications(self, gesture):
     obj = self.getPropertyPage().simpleLastChild.simplePrevious
     if obj.role == controlTypes.ROLE_ALERT:
         if api.getFocusObject().parent == obj:  # Already focused
             ui.message(shared.getAlertText(obj))
             speech.speakObject(api.getFocusObject())
             return
         if shared.focusAlertPopup(obj):
             return
     if self.notificationHistory:
         if scriptHandler.getLastScriptRepeatCount() == 1:
             ui.browseableMessage(
                 "\n".join([
                     "%s: %s" % (shared.elapsedFromTimestamp(
                         notification[0]), notification[1])
                     for notification in self.notificationHistory
                 ]), "%s - Thunderbird" % _("Notification History"))
         else:
             #TRANSLATORS: read the last notification
             ui.message(
                 _("Last alert, %s: %s") %
                 (shared.elapsedFromTimestamp(
                     self.notificationHistory[-1][0]),
                  self.notificationHistory[-1][1]))
     else:
         #TRANSLATORS: there is no recent notification in Thunderbird
         ui.message(_("There is no notification"))
Beispiel #14
0
 def gen_passwd(self):
     length = None
     try:
         # translators: dialog display text for password generation.
         dlg = wx.TextEntryDialog(
             gui.mainFrame,
             _("Enter the length of the password you'd like to generate:"),
             _("Enter length"))
         self.inDialog = True
         dlg.ShowModal()
         dlg.SetFocus()
         length = int(dlg.GetValue())
         dlg.Destroy()
         del dlg
         self.inDialog = False
     except Exception as ex:
         logHandler.log.warning("{}; bailing out.".format(
             ex if ex is not None else "Unknown error"))
         # translators: message displayed to user when a non-integral number is found.
         gui.messageBox(_("Please enter an integer."), _("Error"))
     symbols = string.printable.strip()
     # translators: generated password. Do not translate.
     ui.browseableMessage(
         _(''.join([
             symbols[x * len(symbols) / 256]
             for x in struct.unpack('%dB' % (length, ), os.urandom(length))
         ])), _("Generated Password"), False)
     return
Beispiel #15
0
 def script_bookInfo(self, gesture):
     if api.getForegroundObject().role == controlTypes.ROLE_DIALOG:
         gesture.send()
         return
     title = self.getDataFromColumn(1)
     if title: ui.message(title)
     try:
         clipboard = api.getClipData()
     except TypeError:  # Specified clipboard format is not available
         clipboard = ""
     gesture.send()
     KeyboardInputGesture.fromName("tab").send()  # Skip to document
     KeyboardInputGesture.fromName(
         "applications").send()  # Open context menu
     KeyboardInputGesture.fromName("downArrow").send(
     )  # Down to first item in menu: Copy to clipboard
     KeyboardInputGesture.fromName("Enter").send()  # Activate menu item
     KeyboardInputGesture.fromName("escape").send()  # Close dialog
     if scriptHandler.getLastScriptRepeatCount() == 1:
         ui.browseableMessage(api.getClipData(),
                              title if title else _("Book info"))
     else:
         sleep(0.50)
         try:
             ui.message(api.getClipData())
         except PermissionError:
             pass
     try:
         sleep(0.2)
         if True or not api.copyToClip(clipboard):
             api.win32clipboard.OpenClipboard()
             api.win32clipboard.EmptyClipboard()
             api.win32clipboard.CloseClipboard()
     except (PermissionError, AttributeError):
         pass
Beispiel #16
0
 def script_speakInfo(self, gesture):
     try:
         fg = api.getForegroundObject()
         s2 = fg.firstChild.next.next.next.next.next.firstChild.next.name
         s3 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.name
         s4 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.next.name
         s7 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.next.next.next.next.name
         s8 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.next.next.next.next.next.name
         if not s8: s7 = ""
         s5 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.next.next.next.next.next.next.next.next.name
         s6 = fg.firstChild.next.next.next.next.next.firstChild.next.next.next.next.next.next.next.next.next.next.next.next.next.next.name
         infoString = (" %s %s %s %s %s %s %s" %
                       (s2, s3, s4, s7, s8, s5, s6))
         infoString2 = (" %s %s %s %s %s %s %s" %
                        (s2, s3, s4, s7, s8, s5, s6))
         #infoString2 = s2+" - "+s4+" - "+s6
         infoString3 = ("%s %s %s %s %s %s" % (s3, s4, s7, s8, s5, s6))
         #infoString3 = s4+" - "+s6
         if scriptHandler.getLastScriptRepeatCount() == 1:
             #double press
             api.copyToClip(infoString3)
             tones.beep(1500, 120)
         else:
             num = int(gesture.mainKeyName[-1])
             if num == 2:
                 if not s6: s6 = "no song information found!"
                 if not s4: s4 = "no station information found!"
                 ui.browseableMessage(infoString2,
                                      title="Now playing on " + s4,
                                      isHtml=False)
             else:
                 ui.message(infoString)
     except AttributeError:
         pass
Beispiel #17
0
 def script_displayHelp(self, gesture):
     # Translators: Title of the layered command help window.
     title = _("Windows Magnifier layered commands")
     cmdList = '\r'.join(s[0] + ': ' + s[2]
                         for s in self.__magLayerScriptList)
     # Translators: Part of the help message displayed for the layered command help.
     msg = _("Magnifier layer commands:\n{cmdList}").format(cmdList=cmdList)
     ui.browseableMessage(msg, title)
Beispiel #18
0
 def script_lastControl(self, gesture):
     if memo:
         # Translators: title of browseable message box.
         ui.browseableMessage(".\n".join(memo.split(". ")),
                              _("Moon Position"))
     else:
         #translators: message when  there are no recent info about the moon.
         ui.message(_("There is no recent info for moon position."))
Beispiel #19
0
 def script_help(self, gesture):
     with open(self.helpPath, 'r') as helpFile:
         help_html = helpFile.read()
         speech.cancelSpeech
         help_html = ''.join(
             re.match('(.*<body>)(.*<hr />)(.*)',
                      help_html,
                      flags=re.DOTALL).groups()[::2])
         ui.browseableMessage(help_html, 'Help', True)
Beispiel #20
0
	def addonHelpPage(self) -> None:
		"""Display the add-on help page.
		Call using keyboard commands or menu items.
		"""
		lines = [
			"<h1>%s</h1>" % addonSummary,
			# Translators: Message in the add-on short help
			"<p>NVDA+Y - %s,</p>" % _("switch to add-on control mode"),
			# Translators: Message in the add-on short help
			"<p>%s.</p>" % _("to get a quick translation of a word or phrase - press %s twice") % "NVDA+Y",
			"<br>",
			# Translators: Message in the add-on short help
			"<h2>%s</h2>" % _("In add-on gestures layer mode:"),
			'<ul type="disc">']
		for method in [
			self.script_dictionaryAnnounce.__doc__,
			self.script_dictionaryBox.__doc__,
			self.script_swapLanguages.__doc__,
			self.script_announceLanguages.__doc__,
			self.script_copyLastResult.__doc__,
			self.script_editText.__doc__,
			self.script_updateLanguages.__doc__,
			self.script_selectService.__doc__,
			self.script_dictionaryStatistics.__doc__,
			self.script_showResponse.__doc__]:
			lines.append("<li>%s</li>" % method)
		lines += [
			"</ul>", "<br>",  # noqa ET113
			# Translators: Message in the add-on short help  # noqa ET128
			"<h2>%s</h2>" % _("Voice synthesizers profiles management:"),
			'<ul type="disc">']
		for method in [
			self.script_selectSynthProfile.__doc__,
			self.script_announceSelectedSynthProfile.__doc__,
			self.script_restorePreviousSynth.__doc__,
			self.script_restoreDefaultSynth.__doc__,
			self.script_removeSynthProfile.__doc__,
			self.script_saveSynthProfile.__doc__,
			self.script_displayAllSynthProfiles.__doc__]:
			lines.append("<li>%s</li>" % method)
		lines += ["</ul>", "<br>"]
		for line in [
			self.script_servicesDialog.__doc__,
			self.script_showSettings.__doc__,
			self.script_help.__doc__,
			# Translators: Message in the add-on short help
			_("for any of the listed features you can customize the keyboard shortcut in NVDA input gestures dialog")]:
			lines.append("<p>%s.</p>" % line.capitalize())
		ui.browseableMessage(
			message=htmlTemplate.format(body=''.join(lines)),
			# Translators: The title of the window with help information about the add-on commands
			title=_("help on add-on commands").capitalize(),
			isHtml=True
		)
Beispiel #21
0
 def script_info(self, gesture):
     #ui.message(str(getPipeFile()['Channels']))
     out = ''
     for x in menuFull:
         if x.role == 11 and not controlTypes.STATE_HASPOPUP in x.states:
             out += repr(x.name.partition('\x09')[0]) + ',\n'
     # ui.browseableMessage(out)
     ui.browseableMessage('\n'.join(
         (api.getCaretObject().name, api.getFocusObject().name,
          str(api.getForegroundObject().windowHandle),
          str(api.winUser.getForegroundWindow()))))
Beispiel #22
0
def dbHelp():
    sys.path.append(addonRootDir)
    #Import this late, as we only need this here and it's a large autobuilt blob.
    from NVDA_helpCommands import commands
    sys.path.remove(sys.path[-1])
    html = "<p>"
    #Translators: Description of how to Move to the next topic in the in-built help.
    html += escape(
        _('To use this help documentation, you can navigate to the next category with h, or by saying "next heading".'
          ))
    #Translators: Description of how to Move  through help tables in the in-built help.
    html += escape(
        _('To move by column or row, use table navigation, (You can say "Previous row/column", "prev row", "prev column", "next row", "next column" to navigate with speech).'
          ))
    #Translators: Description of how to  find a command  in the in-built help.
    html += escape(
        _('to find specific text, say "find text", wait for the find dialog to appear, then dictate your text, then say "press enter" or "click ok".'
          ))
    html += "</p><h2>"
    #Translators: The Context sensitive help heading, telling the user what these commands are..
    html += escape(_("Currently available commands."))
    html += "</h2>"
    categories = {}
    #Translators: The name of a category in Dictationbridge for the commands help.
    miscName = _("Miscellaneous")
    categories[miscName] = HelpCategory(miscName)
    for command in commands:
        if command["identifier_for_NVDA"] in SPECIAL_COMMANDS:
            #All special commands get the miscelaneous category.
            categories[miscName].addRow(command["text"], command["helpText"])
            continue
        #Creating a gesture is not efficient, but helps eliminate code bloat.
        gesture = DictationGesture(command["identifier_for_NVDA"])
        scriptInfo = gesture.script_hacky
        if not scriptInfo:
            #This script is not active right now!
            continue
        doc = getattr(scriptInfo[0], "__doc__", "")
        category = ""
        try:
            category = scriptInfo[0].category
        except AttributeError:
            category = getattr(scriptInfo[1], "scriptCategory", miscName)
        if not categories.get(category):
            categories[cat] = HelpCategory(cat)
        categories[cat].addRow(command["text"], doc)
    for category in categories.values():
        html += category.html()
    ui.browseableMessage(
        html,
        #Translators: The title of the context sensitive help for Dictation Bridge NVDA Commands.
        _("Dictation Bridge NVDA Context Sensitive Help"),
        True)
Beispiel #23
0
 def script_virtualizeConversation(self, gesture):
     try:
         chatOutputList = NVDAObjects.IAccessible.getNVDAObjectFromEvent(self.getChatHistoryWindow(), winUser.OBJID_CLIENT, 0).lastChild
         messages = [msg.name for msg in chatOutputList.children]
         conversationName = chatOutputList.parent.parent.name
         # Translators: brief summary when virtualizing conversation which includes the number of  messages shown
         text = _("Displaying the {n} most recent messages chronologically:\n{messageText}").format(n=len(messages), messageText='\n'.join(messages))
         # Translators: title of the buffer when virtualizing messages, excluding conversation name
         ui.browseableMessage(text, title=_("Chat history for ") + conversationName, isHtml=False)
     except LookupError:
         log.debugWarning("Couldn't find chat history list")
         ui.message(MSG_NO_ACTIVE_CONVERSATION)
Beispiel #24
0
 def script_getLast(self, gesture):
     if last:
         #pressing once will speak info, twice will show a BrowseableDialog
         r = scriptHandler.getLastScriptRepeatCount()
         if r == 0:
             ui.message(last)
         elif r == 1:
             ui.browseableMessage("\n".join(last.split(". ")),
                                  "text information")
     else:
         #translators: message spoken when the user tries getting previous information but there is none
         ui.message(_("you haven't yet gotten info"))
Beispiel #25
0
    def script_ocrNavigatorObject(self, gesture):
        nav = api.getNavigatorObject()
        left, top, width, height = nav.location
        bmp = wx.EmptyBitmap(width, height)
        # Tesseract copes better if we convert to black and white...
        ## img = img.convert(mode='L')
        # and increase the size.
        ## img = img.resize((width * IMAGE_RESIZE_FACTOR, height * IMAGE_RESIZE_FACTOR), Image.BICUBIC)
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, width, height, wx.ScreenDC(), left, top)

        baseFile = os.path.join(tempfile.gettempdir(), "nvda_ocr")
        try:
            imgFile = baseFile + ".png"
            txtFile = baseFile + ".txt"
            bmp.SaveFile(imgFile, wx.BITMAP_TYPE_PNG)

            ui.message(_("Running OCR"))
            lang = getConfig()['language']
            lang2 = getConfig()['language2']
            if not lang == lang2:
                mlangs = lang + "+" + lang2
            else:
                mlangs = lang
            # Hide the Tesseract window.
            si = subprocess.STARTUPINFO()
            si.dwFlags = subprocess.STARTF_USESHOWWINDOW
            si.wShowWindow = subprocess.SW_HIDE
            subprocess.check_call(
                (TESSERACT_EXE, imgFile, baseFile, "-l", mlangs),
                startupinfo=si)
        finally:
            try:
                os.remove(imgFile)
            except OSError:
                pass
        # Let the user review the OCR output.
        result = ""
        try:
            with open(txtFile, encoding="UTF-8") as f:
                result = f.read().strip()
        except:
            pass
        os.remove(txtFile)
        if result != "":
            ui.message(_("Done"))
            try:
                ui.browseableMessage(result, _("OCR Result"))
            except:
                ui.message(result)
        else:
            ui.message(_("Error"))
Beispiel #26
0
def currentCharDesc():
	ch = getCurrentChar()
	c = ord(ch)
	if c != '':
		s = '%c: %s; %s; %s; %s'% (ch, hex(c), c, oct(c), bin(c))
		if scriptHandler.getLastScriptRepeatCount() == 0: ui.message(s)
		elif (scriptHandler.getLastScriptRepeatCount() == 1):
			brch = getTextInBraille(ch)
			ui.browseableMessage('%s\n%s (%s)' % (s, brch, unicodeBrailleToDescription(brch)), r'\x%d - Char info' % c)
		else:
			api.copyToClip(s)
			ui.message('"{0}" copied to clipboard.'.format(s))
	else: ui.message(_('Not a character.'))
 def script_lastResult(self, gesture):
     if memo:
         if scriptHandler.getLastScriptRepeatCount() == 0:
             ui.message(memo)
         elif scriptHandler.getLastScriptRepeatCount() == 1:
             # Translators: title of browseable message box.
             ui.browseableMessage(
                 ".\n".join(memo.split(". ")),
                 _("From {vocs}").format(vocs=getVocsName()[
                     config.conf["vocabulary"]["myvocabulary"]]))
     else:
         #translators: message when  there are no recent searches in the vocabulary
         ui.message(_("There is no recent research in the vocabulary."))
    def translate(self, text: str, isHtml: bool = False) -> None:
        """Retrieve the dictionary entry for the given word or phrase and display/announce the result.
		This method must always be called in a separate thread so as not to block NVDA.
		@param text: a word or phrase to look up in a dictionary
		@type text: str
		@param isHtml: a sign of whether it is necessary to display the result of work in the form of HTML page
		@type isHtml: bool
		"""
        active = config.conf[addonName]['active']
        langs = services[active].langs
        pairs = [(self.source, self.target)]
        if self.isAutoSwap:
            if langs.isAvailable(self.target, self.source):
                pairs.append((self.target, self.source))
        for lFrom, lInto in pairs:
            translator = translateWithCaching(lFrom, lInto, text,
                                              hashForCache(active))
            if translator.error:
                translateWithCaching.cache_clear(
                )  # reset cache when HTTP errors occur
            self._cacheInfo = str(translateWithCaching.cache_info(
            ))  # - to check the current status of queries cache
            if translator.plaintext:
                break
        else:
            if not translator.plaintext:
                # Translators: Notification of missing dictionary entry for current request
                ui.message(_("No results"))
                self._messages.clear()
                return
        self._lastTranslator = translator
        setattr(self._lastTranslator, 'id', active)
        if isHtml:
            ui.browseableMessage(message=translator.html,
                                 title='%s-%s' %
                                 (langs[translator.langFrom].name,
                                  langs[translator.langTo].name),
                                 isHtml=isHtml)
        else:
            self._messages.append('%s - %s' % (langs[translator.langFrom].name,
                                               langs[translator.langTo].name))
            self._messages.append(translator.plaintext)
            message = '...'.join(self._messages)
            self._messages.clear()
            queueFunction(eventQueue, messageWithLangDetection, {
                'text': message,
                'lang': translator.langTo
            })
        if self.isCopyToClipboard:
            api.copyToClip(translator.plaintext, notify=True)
Beispiel #29
0
 def script_showCurrentBookmarksFile(self, gesture):
     obj = api.getFocusObject()
     if not controlTypes.STATE_MULTILINE in obj.states:
         treeInterceptor = obj.treeInterceptor
         if not (isinstance(treeInterceptor,
                            BrowseModeDocumentTreeInterceptor)
                 and not treeInterceptor.passThrough):
             gesture.send()
             return
     fileName = getFile("bookmarks")
     ui.browseableMessage(
         # Translators: Title for the message presented when the file name for place markers is shown in browse mode.
         fileName,
         _("%s file" % ADDON_SUMMARY))
def convertToMD(text, metadata, display=True):
    title = metadata["title"]
    dmp = getMetadataBlock(metadata) if metadata["genMetadata"] else ""
    if metadata["detectExtratags"]: text = backTranslateExtraTags(text)
    if config.conf["markdownForever"]["markdownEngine"] == "html2markdown":
        convert = html2markdown.convert
    else:
        convert = html2text.html2text
    res = ("%s\n%s" % (dmp, convert(text))).strip()
    if display:
        pre = (title + " - ") if title else title
        ui.browseableMessage(res, pre + _("HTML to Markdown conversion"),
                             False)
    else:
        return res
def dbHelp():
	sys.path.append(addonRootDir)
	#Import this late, as we only need this here and it's a large autobuilt blob.
	from NVDA_helpCommands import commands
	sys.path.remove(sys.path[-1])
	html = "<p>"
	#Translators: Description of how to Move to the next topic in the in-built help.
	html += escape(_('To use this help documentation, you can navigate to the next category with h, or by saying "next heading".'))
	#Translators: Description of how to Move  through help tables in the in-built help.
	html += escape(_('To move by column or row, use table navigation, (You can say "Previous row/column", "prev row", "prev column", "next row", "next column" to navigate with speech).'))
	#Translators: Description of how to  find a command  in the in-built help.
	html += escape(_('to find specific text, say "find text", wait for the find dialog to appear, then dictate your text, then say "press enter" or "click ok".'))
	html += "</p><h2>"
	#Translators: The Context sensitive help heading, telling the user what these commands are..
	html +=escape(_("Currently available commands."))
	html += "</h2>"
	categories = {}
	#Translators: The name of a category in Dictationbridge for the commands help.
	miscName = _("Miscellaneous")
	categories[miscName] = HelpCategory(miscName)
	for command in commands:
		if command["identifier_for_NVDA"] in SPECIAL_COMMANDS:
			#All special commands get the miscelaneous category.
			categories[miscName].addRow(command["text"], command["helpText"])
			continue
		#Creating a gesture is not efficient, but helps eliminate code bloat.
		gesture = DictationGesture(command["identifier_for_NVDA"])
		scriptInfo = gesture.script_hacky
		if not scriptInfo:
			#This script is not active right now!
			continue
		doc = getattr(scriptInfo[0], "__doc__", "")
		category = ""
		try:
			category = scriptInfo[0].category
		except AttributeError:
			category = getattr(scriptInfo[1], "scriptCategory", miscName)
		if not categories.get(category):
			categories[cat] = HelpCategory(cat)
		categories[cat].addRow(command["text"], doc)
	for category in categories.values():
		html+=category.html()
	ui.browseableMessage(html,
		#Translators: The title of the context sensitive help for Dictation Bridge NVDA Commands.
		_("Dictation Bridge NVDA Context Sensitive Help"),
		True)
Beispiel #32
0
def displayPlaylistTranscripts(transcript, HTMLDecoration=False):
	ui.browseableMessage("\n".join(transcript),title=_("Playlist Transcripts"), isHtml=HTMLDecoration)
	def script_htmlPreview(self, gesture):
		html = self.prepareHtml()
		#Translators: The title of the browseable message
		title=_("Preview of MarkDown or HTML")
		ui.browseableMessage(html, title, True)