#Translate clipboard content on Windows unsing Google Translate # #!/bin/python # -*- coding: utf-8 -*- """Translate clipboard content on Windows unsing Google Translate""" # Author : Ginko # Date : 08/01/2015 # Version : 0.1.a # License : zlib/libpng # The zlib/libpng License # Copyright (c) 2015 Ginko Aloe - ginkobox.fr # This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. # Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: # 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. # goslate module from http://pythonhosted.org/goslate/ # Clip object inspired from https://stackoverflow.com/a/25678113 # Example usage (from cmd.exe): C:\pathTo\python.exe C:\path\to\translate.py en import ctypes, sys import goslate class Clip(object): def __init__(self): self.wcscpy = ctypes.cdll.msvcrt.wcscpy self.OpenClipboard = ctypes.windll.user32.OpenClipboard self.EmptyClipboard = ctypes.windll.user32.EmptyClipboard self.GetClipboardData = ctypes.windll.user32.GetClipboardData self.SetClipboardData = ctypes.windll.user32.SetClipboardData self.CloseClipboard = ctypes.windll.user32.CloseClipboard self.CF_UNICODETEXT = 13 self.GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc self.GlobalLock = ctypes.windll.kernel32.GlobalLock self.GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock self.GMEM_DDESHARE = 0x2000 def get(self): self.OpenClipboard(None) handle = self.GetClipboardData(self.CF_UNICODETEXT) data = ctypes.c_wchar_p(handle).value pcontents = self.GlobalLock(handle) data = ctypes.c_wchar_p(pcontents).value if pcontents else u'' self.GlobalUnlock(handle) self.CloseClipboard() return data def put(self, data): # if not isinstance(data, unicode): # data = data.decode('mbcs') self.OpenClipboard(None) self.EmptyClipboard() hCd = self.GlobalAlloc(self.GMEM_DDESHARE, 2 * (len(data) + 1)) pchData = self.GlobalLock(hCd) self.wcscpy(ctypes.c_wchar_p(pchData), data) self.GlobalUnlock(hCd) self.SetClipboardData(self.CF_UNICODETEXT, hCd) self.CloseClipboard() def main(): clip = Clip() gs = goslate.Goslate() lang = sys.argv[1] if len(sys.argv) > 1 else 'fr' c = gs.translate(clip.get(), lang) clip.put(c) if __name__ == "__main__": main()