Source

Kiva Editor's Assistant / clipboard.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Cross-platform clipboard support

import platform
import codecs

#
# Define clipboard access functions that operate on the current platform
#

if platform.system() == 'Darwin':
    import subprocess

    def get_clipboard_text():
        s = subprocess.Popen('pbpaste', stdout=subprocess.PIPE)
        return s.stdout.read()

    def set_clipboard_text(text):
        sub = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
        subprocess.Popen.communicate(sub, input=text)
elif platform.system() == 'Windows':
    import win32clipboard
    
    def get_clipboard_text():
        try:
            win32clipboard.OpenClipboard()
            src = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
        finally:
            win32clipboard.CloseClipboard()
        return src


    def set_clipboard_text(text):
        try:
            win32clipboard.OpenClipboard()
            win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
        except Exception as e:
            print 'Set clipboard failed'
            print e
        finally:
            win32clipboard.CloseClipboard()
            
        with codecs.open('kiva.txt', 'w', 'utf-8') as f:
            f.write(text)
elif platform.system() == 'Linux':
    from PyQt4.QtGui import *
    qt4_app = QApplication([])

    def get_clipboard_text():
        clip = qt4_app.clipboard()
        return unicode(clip.text())
    
    def set_clipboard_text(text):
        clip = qt4_app.clipboard()
        # TODO: this doesn't work with X11, more needs to be done to
        # get Qt to write to the X11 clipboard; see
        # http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qclipboard.html#details
        clip.setText(unicode(text))
else:
    def get_clipboard_text():
        raise NotImplementedError
    
    def set_clipboard_text(text):
        raise NotImplementedError