def getClipboardData(format): # We only support unicode text for now if format != CF_UNICODETEXT: raise ValueError("Unsupported format") # Fetch the data from the clipboard as a global memory handle h = windll.user32.GetClipboardData(format) if not h: raise ctypes.WinError() # Lock the global memory while we fetch the unicode string # But make sure not to free the memory accidentally -- it is not ours h = winKernel.HGLOBAL(h, autoFree=False) with h.lock() as addr: # Read the string from the local memory address return wstring_at(addr)
def getImageFromClipboard(cls): CF_DIB = 8 CF_HDROP = 15 CF_UNICODETEXT = 13 clipboardImage = None formats = cls.enumerateClipboardFormat() if CF_DIB in formats: clipboardImage = ImageGrab.grabclipboard() elif CF_HDROP in formats: try: filePathList = [] with winUser.openClipboard(gui.mainFrame.Handle): rawData = windll.user32.GetClipboardData(CF_HDROP) if not rawData: ui.message(_("Error occurred while getting pasted file.")) rawData = winKernel.HGLOBAL(rawData, autoFree=False) with rawData.lock() as addr: fileCount = windll.shell32.DragQueryFileW( c_uint32(addr), c_uint32(0xFFFFFFFF), c_uint32(0), c_uint32(0) ) for c in range(fileCount): BUFFER_SIZE = 4096 filePath = create_unicode_buffer(BUFFER_SIZE) windll.shell32.DragQueryFileW( c_uint32(addr), c_uint32(c), c_uint32(filePath), c_uint32(BUFFER_SIZE) ) filePathList.append(wstring_at(filePath, size=BUFFER_SIZE).rstrip('\x00')) log.debug("filePathList\n{0}".format(filePathList)) for fileName in filePathList: # TODO Add a prompt for users to choose from import os if os.path.isfile(fileName): clipboardImage = Image.open(rawData[0]) clipboardImage = clipboardImage.convert("RGB") return clipboardImage except TypeError as e: log.io(e) elif CF_UNICODETEXT in formats: # TODO extract url or file path from text then grab an image from it. try: from api import getClipData import os text = getClipData() if os.path.exists(text): if os.path.isfile(text): clipboardImage = Image.open(text) else: # Translators: Reported when text in clipboard is not a valid path ui.message(_(u"Text in clipboard is the name of a directory.")) else: # Translators: Reported when text in clipboard is not a valid path ui.message(_(u"Text in clipboard is not a valid path.")) except IOError: # Translators: Reported when cannot get content of the path specified errMsg = _("The file specified in clipboard is not an image") ui.message(errMsg) return clipboardImage