Exemple #1
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
Exemple #2
0
 def requiredFormatInClip(self):
     if config.conf["clipContentsDesigner"]["confirmationRequirement"] == 0:
         return True
     if config.conf["clipContentsDesigner"]["confirmationRequirement"] == 1:
         try:
             api.getClipData()
             return True
         except Exception:
             return False
     if self.clipboardHasContent():
         return True
     return False
Exemple #3
0
 def script_saveClip(self, gesture):
     tones.beep(440, 500)  # Beep a standard middle A for 1 second.
     try:
         text = api.getClipData()
     except TypeError:
         text = None
     if not text or not isinstance(text, basestring):
         ui.message("Clipboard has no text")
         return
     else:
         now = datetime.datetime.now()
         timestr = time.strftime("%H%M%S")
         filename = timestr + '.html'
         filepath = save_dir + months[now.month] + '_' + str(
             now.year) + '/' + str(now.day) + '/'
         if not os.path.exists(filepath):
             os.makedirs(filepath)
         with open(filepath + filename, "w") as text_file:
             text_file.write('<html>')
             text_file.write('<h1> Saved on: ' + months[now.month] + ' ' +
                             str(now.day) + ', ' + str(now.year) +
                             '</h1> <br/>')
             text_file.write('<h1> <FONT FACE="arial">')
             text_file.write(str(text))
             text_file.write('</FONT FACE></h1>')
             text_file.write('</html>')
         webbrowser.open('file://' + (filepath + filename))
Exemple #4
0
	def on_push_clipboard_item(self, evt):
		connector = self.control_connector or self.connector
		try:
			connector.send(type='set_clipboard_text', text=api.getClipData())
		except TypeError:
			# JL: It might be helpful to provide a log.debug output for this.
			pass
Exemple #5
0
 def on_push_clipboard_item(self, evt):
     connector = self.control_connector or self.connector
     try:
         connector.send(type='set_clipboard_text', text=api.getClipData())
     except TypeError:
         # JL: It might be helpful to provide a log.debug output for this.
         pass
 def getTextToAdd(self):
     newText = self.getSelectedText() or self.getMath()
     if not newText:
         if not self._copyStartMarker:
             # Translators: message presented when it's not possible to add text, since no text has been selected or marked.
             ui.message(_("No selection. No start marker set"))
             return
         pos = api.getReviewPosition().copy()
         if self._copyStartMarker.obj != pos.obj:
             # Translators: Message presented when a start marked has been placed, but not in the current object.
             ui.message(
                 _("The start marker must reside within the same object"))
             return
         pos.move(textInfos.UNIT_CHARACTER, 1, endPoint="end")
         pos.setEndPoint(self._copyStartMarker, "startToStart")
         if not pos.compareEndPoints(pos, "startToEnd") < 0:
             # Translators: message presented when review cursor has been used to add text and there is no text to add.
             ui.message(_("No text to add"))
             return
         newText = pos.clipboardText
         self._copyStartMarker = None
     try:
         clipData = api.getClipData()
         if config.conf["clipContentsDesigner"]["addTextBefore"]:
             text = newText + getBookmark() + clipData
         else:
             text = clipData + getBookmark() + newText
     except TypeError:
         text = newText
     return text
def getSelectedText() -> str:
    """Retrieve the selected text.
	If the selected text is missing - extract the text from the clipboard.
	If the clipboard is empty or contains no text data - announce a warning.
	@return: selected text, text from the clipboard, or an empty string
	@rtype: str
	"""
    obj = api.getFocusObject()
    treeInterceptor = obj.treeInterceptor
    if hasattr(treeInterceptor,
               'TextInfo') and not treeInterceptor.passThrough:
        obj = treeInterceptor
    try:
        info = obj.makeTextInfo(POSITION_SELECTION)
    except (RuntimeError, NotImplementedError):
        info = None
    if not info or info.isCollapsed or not clearText(info.text):
        try:
            text = api.getClipData()
        except Exception:
            text = ''
        if not text or not isinstance(text, str) or not clearText(text):
            # Translators: User has pressed the shortcut key for translating selected text,
            # but no text was actually selected and clipboard is clear
            ui.message(
                _("There is no selected text, the clipboard is also empty, or its content is not text!"
                  ))
            return ''
        return text
    return info.text
Exemple #8
0
 def onInputPaste(self, evt):
     cpText = api.getClipData()
     if not cpText.strip():
         evt.Skip()
         return
     cpLines = cpText.splitlines()
     inputLine = self.inputCtrl.GetValue()
     from_, to_ = self.inputCtrl.GetSelection()
     prefix = inputLine[:from_]
     suffix = inputLine[to_:]
     for index, line in enumerate(cpLines):
         if index == 0:
             # First pasted line: Prepend the input text before the cursor
             line = prefix + line
         if index == len(cpLines) - 1:
             # Last pasted line: Append the input text after the cursor
             self.inputCtrl.ChangeValue(line + suffix)
             self.inputCtrl.SetInsertionPoint(len(line))
             return
         self.inputCtrl.ChangeValue(line)
         self.execute()
         if self.console.compile.error:
             # A compilation error occurred: Unlike in the standard Python
             # Console, restore the original input text after the cursor and
             # stop here to avoid execution of the remaining lines and ease
             # reading of output errors.
             self.inputCtrl.ChangeValue(suffix)
             break
Exemple #9
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)
Exemple #10
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)
Exemple #11
0
	def _script_translate_clip(self, gesture):
		try:
			text = api.getClipData()
		except Exception:
			ui.message(_("No text to translate"))
			return

		YandexTranslate(self.translateHandler, text=text, lang=self.getLang())
Exemple #12
0
    def script_normalize_clip(self, gesture):
        try:
            text = api.getClipData()
        except Exception:
            ui.message(_("No text to normalize"))
            return

        TextNormalizerThr(self.normalizeHandler, text=text)
Exemple #13
0
	def requiredFormatInClip(self):
		if not config.conf["clipContentsDesigner"]["requireTextForConfirmation"]:
			return True
		try:
			text = api.getClipData()
			return True
		except:
			return False
Exemple #14
0
	def script_translateClipboardText(self, gesture):
		try:
			text = api.getClipData()
		except:
			text = None
		if not text or not isinstance(text,six.string_types) or text.isspace():
			# Translators: message presented when user presses the shortcut key for translating clipboard text but the clipboard is empty.
			ui.message(_("There is no text on the clipboard"))
		else:
			threading.Thread(target=self.translate, args=(text,)).start()
Exemple #15
0
 def script_push_clipboard(self, gesture):
     connector = self.slave_transport or self.master_transport
     if not getattr(connector, 'connected', False):
         ui.message(_("Not connected."))
         return
     try:
         connector.send(type='set_clipboard_text', text=api.getClipData())
         ui.message(_("Clipboard pushed"))
     except TypeError:
         ui.message(_("Unable to push clipboard"))
Exemple #16
0
	def script_push_clipboard(self, gesture):
		connector = self.slave_transport or self.master_transport
		if not getattr(connector,'connected',False):
			ui.message(_("Not connected."))
			return
		try:
			connector.send(type='set_clipboard_text', text=api.getClipData())
			ui.message(_("Clipboard pushed"))
		except TypeError:
			ui.message(_("Unable to push clipboard"))
 def innerFunc(*args, **kwargs):
     func(*args, **kwargs)
     try:
         clips = initClipSfile()
         clip = api.getClipData()
         log.info(clip)
         clips['recent'].insert(0, clip)
         writeClips(clips)
     except OSError:
         pass
	def script_speakResultForBuffer(self, gesture):
		conf = _config.load_config()
		try:
			text = api.getClipData()
		except:
			text = None
		if not text or not isinstance(text,basestring) or text.isspace():
			ui.message(_("Clipboard don't contains text"))
		else:
			t = threading.Thread(target=_dict.getResult, args=[text, conf[conf["selected_dict"]], self.message])
			t.start()
Exemple #19
0
 def script_getClipInfo(self, gesture):
     try:
         text = api.getClipData()
     except TypeError:
         text = None
     if not text or not isinstance(text, str):
         #translators: message spoken when the clipboard is empty
         ui.message(_("There is no text on the clipboard"))
         return
     else:
         self.get_info(text.strip())
	def script_openDictionaryForBuffer(self, gesture):
		try:
			text = api.getClipData()
		except:
			text = None
		if not text or not isinstance(text,basestring) or text.isspace():
			ui.message(_("Clipboard don't contains text"))
		else:
			ui.message(_('Looking for information'))
			t = threading.Thread(target=_dict.getResult, args=[text, _conf[_conf["selected_dict"]], ui.browseableMessage])
			t.start()
Exemple #21
0
def getClipboardText():
    """Return text from the clipboard, if not then return False."""
    # The code for this function is partially taken from the NVDA source code licensed under the GNU GPL.
    # See script_reportClipboardText method in globalCommands.py file.
    try:
        text = api.getClipData()
    except:
        text = None
    if not text or not isinstance(text, str) or text.isspace():
        return False
    else:
        return text
	def script_reportClipboardText(self,gesture):
		try:
			text = api.getClipData()
		except:
			text = None
		if not text or not isinstance(text,basestring) or text.isspace():
			ui.message(_("There is no text on the clipboard"))
			return
		if len(text) < 1024: 
			ui.message(text)
		else:
			ui.message(_("The clipboard contains a large portion of text. It is %s characters long") % len(text))
Exemple #23
0
 def _paste_safe(self, text, obj=None, label=False):
     try:
         temp = api.getClipData()
     except:
         temp = ''
     api.copyToClip(text)
     if label == True:
         KIGesture.fromName('p').send()
         KIGesture.fromName('control+alt+v').send()
     else:
         KIGesture.fromName('control+v').send()
     api.processPendingEvents()
     if obj:
         obj.reportFocus()
     api.copyToClip(temp)
Exemple #24
0
 def requiredFormatInClip(self):
     if config.conf["clipContentsDesigner"]["confirmationRequirement"] == 0:
         return True
     if config.conf["clipContentsDesigner"]["confirmationRequirement"] == 1:
         try:
             clipData = api.getClipData()
             return True
         except TypeError:
             return False
     win32clipboard.OpenClipboard()
     clipFormat = win32clipboard.EnumClipboardFormats()
     win32clipboard.CloseClipboard()
     if clipFormat:
         return True
     return False
Exemple #25
0
def markLaTeX():
    try:
        temp = api.getClipData()
    except:
        temp = ''
    api.copyToClip(r'\(\)')

    KeyboardInputGesture.fromName("control+v").send()

    leftArrow = KeyboardInputGesture.fromName("leftArrow")
    leftArrow.send()
    leftArrow.send()
    if temp != '':
        wx.CallLater(100, api.copyToClip, temp)
    else:
        wx.CallLater(100, clearClipboard)
Exemple #26
0
    def script_pastePP(self, gesture):
        if self.itemIndexzn < 0:
            varGlobal.mensaje(
                _("Use flechas derecha e izquierda para moverse por las categorías, flechas arriba y abajo para seleccionar item, F1 para escuchar el contenido de la nota, F2 para copiar al portapapeles, F3 para pegar en el foco o escape para salir"
                  ))
            return

        if len(self.temporal) == 0:
            varGlobal.mensaje(_("Esta categoría no tiene notas"))
            return
        else:
            valor = self.itemIndexzn
            if self.temporal[valor][0] == "txt":
                self.script_exit(None)
                self.finish()
                paste = self.temporal[valor][2]
                # Source code taken from: frequentText add-on for NVDA. Written by Rui Fontes and Ângelo Abrantes
                try:
                    clipboardBackup = api.getClipData()
                except:
                    pass

                api.copyToClip(paste)
                time.sleep(0.1)
                api.processPendingEvents(False)
                focus = api.getFocusObject()
                if focus.windowClassName == "ConsoleWindowClass":
                    # Windows console window - Control+V doesn't work here, so using an alternative method here
                    WM_COMMAND = 0x0111
                    watchdog.cancellableSendMessage(focus.windowHandle,
                                                    WM_COMMAND, 0xfff1, 0)
                else:
                    time.sleep(0.1)
                    try:
                        KeyboardInputGesture.fromName("Control+v").send()
                    except:
                        # Solución para teclados con caracteres cirilicos.
                        KeyboardInputGesture.fromName("shift+insert").send()

                varGlobal.mensaje(_("Nota pegada en el foco"))
                try:
                    core.callLater(300,
                                   lambda: api.copyToClip(clipboardBackup))
                except:
                    pass
 def script_fromClip(self, gesture):
     try:
         text = api.getClipData()
     except:
         text = None
     if not text or not isinstance(text, str):
         #translators: message spoken when the clipboard is empty
         ui.message(_("There is no text on the clipboard"))
     else:
         s = text
         w = s.split()
         ws = len(w)
         if ws > 1:
             tones.beep(330, 120, 30, 30)
             # Translators: message when there is more than one word on clipboard.
             ui.message(_("Too much text on clipboard. Invalid keyword."))
         else:
             kwrd = s.lower().strip('\'\"-,.:;!? ')
             threading.Thread(target=self.findMeaning,
                              args=(kwrd, )).start()
Exemple #28
0
 def script_showClipboardText(self, gesture):
     try:
         text = api.getClipData()
     except:
         text = None
     if not text or not isinstance(text, basestring) or text.isspace():
         win32clipboard.OpenClipboard()
         clipFormat = win32clipboard.EnumClipboardFormats()
         win32clipboard.CloseClipboard()
         if clipFormat:
             # 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:
         maxLength = config.conf["clipContentsDesigner"][
             "maxLengthForBrowseableText"] if config.conf[
                 "clipContentsDesigner"][
                     "maxLengthForBrowseableText"] <= len(text) else len(
                         text)
         format = config.conf["clipContentsDesigner"][
             "browseableTextFormat"]
         html = True
         if format == 0:
             browseableText = "<pre>%s</pre>" % text.strip()[:maxLength]
         elif format == 1:
             browseableText = text.strip()[:maxLength]
         else:
             browseableText = text[:maxLength]
             html = False
         # Translators: title of a browseable message.
         ui.browseableMessage(
             browseableText,
             _("Clipboard text ({max}/{current} - {formatForTitle})".format(
                 max=maxLength,
                 current=len(text),
                 formatForTitle=BROWSEABLETEXT_FORMATS[format])), html)
Exemple #29
0
    def script_indentPaste(self, gesture):
        clipboardBackup = api.getClipData()
        try:
            focus = api.getFocusObject()
            selection = focus.makeTextInfo(textInfos.POSITION_SELECTION)
            if len(selection.text) != 0:
                ui.message(_("Some text selected! Cannot indent-paste."))
                return
            line = focus.makeTextInfo(textInfos.POSITION_CARET)
            line.collapse()
            line.expand(textInfos.UNIT_LINE)
            # Make sure line doesn't include newline characters
            while len(line.text) > 0 and line.text[-1] in "\r\n":
                line.move(textInfos.UNIT_CHARACTER, -1, "end")
            lineLevel = self.getIndentLevel(line.text + "a")
            #ui.message(f"Level {level}")
            text = clipboardBackup
            textLevel = min([
                self.getIndentLevel(s) for s in text.splitlines()
                if not speech.isBlank(s)
            ])
            useTabs = '\t' in text or '\t' in line.text
            delta = lineLevel - textLevel
            text = text.replace("\t", " " * 4)
            if delta > 0:
                text = "\n".join([" " * delta + s for s in text.splitlines()])
            elif delta < 0:
                text = "\n".join(
                    [s[min(-delta, len(s)):] for s in text.splitlines()])
            if useTabs:
                text = text.replace(" " * 4, "\t")

            api.copyToClip(text)
            line.updateSelection()
            time.sleep(0.1)
            keyboardHandler.KeyboardInputGesture.fromName("Control+v").send()
        finally:
            core.callLater(100, api.copyToClip, clipboardBackup)
            core.callLater(100, ui.message, _("Pasted"))
Exemple #30
0
def command(text, offset):
    try:
        temp = api.getClipData()
    except:
        temp = ''
    api.copyToClip(text)

    KeyboardInputGesture.fromName("control+v").send()

    leftArrow = KeyboardInputGesture.fromName("leftArrow")
    rightArrow = KeyboardInputGesture.fromName("rightArrow")
    if offset > 0:
        for i in range(abs(offset)):
            rightArrow.send()
    else:
        for i in range(abs(offset)):
            leftArrow.send()

    if temp != '':
        wx.CallLater(100, api.copyToClip, temp)
    else:
        wx.CallLater(100, clearClipboard)
Exemple #31
0
def getTextToAdd():
    newText = getSelectedText() or getMath()
    if not newText:
        if not getattr(
                api.getReviewPosition().obj, "_selectThenCopyRange",
                None) or not api.getReviewPosition().obj._selectThenCopyRange:
            # Translators: message presented when it's not possible to add text, since no text has been selected.
            ui.message(_("No text to add"))
            return
        newText = api.getReviewPosition(
        ).obj._selectThenCopyRange.clipboardText
    try:
        clipData = api.getClipData()
    except Exception:
        clipData = None
    if clipData:
        if _NVDAConfigManager.toggleAddTextBeforeOption(False):
            text = newText + getBookmark() + clipData
        else:
            text = clipData + getBookmark() + newText
    else:
        text = newText
    return text
Exemple #32
0
 def getTextToAdd(self):
     newText = self.getSelectedText() or self.getMath()
     if not newText:
         if not getattr(api.getReviewPosition().obj, "_selectThenCopyRange",
                        None) or not api.getReviewPosition(
                        ).obj._selectThenCopyRange:
             # Translators: message presented when it's not possible to add text, since no text has been selected.
             ui.message(_("No text to add"))
             return
         newText = api.getReviewPosition(
         ).obj._selectThenCopyRange.clipboardText
     try:
         clipData = api.getClipData()
     except Exception:
         clipData = None
     if clipData:
         if config.conf["clipContentsDesigner"]["addTextBefore"]:
             text = newText + getBookmark() + clipData
         else:
             text = clipData + getBookmark() + newText
     else:
         text = newText
     return text
Exemple #33
0
	def onPaste (self, evt):
		# Simulates typing the block of text in the edit area.
		self.Hide()
		evt.Skip()
		config = ConfigObj(_ffIniFile, list_values = True, encoding = "utf-8")
		blocks = config[Catg]
		index=self.listBox.GetFocusedItem()
		name = self.listBox.GetItemText(index)
		paste = blocks[name]
		pasteStr = "\r\n".join(paste)
		if len(paste) >= 2:
			pasteStr += "\r\n"
		try:
			clipboardBackup = api.getClipData()
		except OSError:
			api.copyToClip(pasteStr)
			time.sleep(0.1)
			api.processPendingEvents(False)
			focus = api.getFocusObject()
			if focus.windowClassName == "ConsoleWindowClass":
				# Windows console window - Control+V doesn't work here, so using an alternative method here
				WM_COMMAND = 0x0111
				watchdog.cancellableSendMessage(focus.windowHandle, WM_COMMAND, 0xfff1, 0)
			else:
				KeyboardInputGesture.fromName("Control+v").send()
		else:
			api.copyToClip(pasteStr)
			time.sleep(0.1)
			api.processPendingEvents(False)
			focus = api.getFocusObject()
			if focus.windowClassName == "ConsoleWindowClass":
				# Windows console window - Control+V doesn't work here, so using an alternative method here
				WM_COMMAND = 0x0111
				watchdog.cancellableSendMessage(focus.windowHandle, WM_COMMAND, 0xfff1, 0)
			else:
				KeyboardInputGesture.fromName("Control+v").send()
			core.callLater(300, lambda: api.copyToClip(clipboardBackup))
Exemple #34
0
 def on_push_clipboard_item(self, evt):
     connector = self.slave_transport or self.master_transport
     try:
         connector.send(type='set_clipboard_text', text=api.getClipData())
     except TypeError:
         log.exception("Unable to push clipboard")
Exemple #35
0
	def on_push_clipboard_item(self, evt):
		connector = self.control_connector or self.connector
		try:
			connector.send(type='set_clipboard_text', text=api.getClipData())
		except TypeError as e:
			log.debug("Error while pushing clipboard: %s" %(e))
Exemple #36
0
	def on_push_clipboard_item(self, evt):
		connector = self.control_connector or self.connector
		try:
			connector.send(type='set_clipboard_text', text=api.getClipData())
		except TypeError:
			pass
Exemple #37
0
	def on_push_clipboard_item(self, evt):
		connector = self.slave_transport or self.master_transport
		try:
			connector.send(type='set_clipboard_text', text=api.getClipData())
		except TypeError:
			log.exception("Unable to push clipboard")