Skip to content

Instantly share code, notes, and snippets.

@gwwfps
Created June 4, 2010 22:39
Show Gist options
  • Save gwwfps/426037 to your computer and use it in GitHub Desktop.
Save gwwfps/426037 to your computer and use it in GitHub Desktop.
Shares clipboard with LAN.
#!/usr/bin/env python
import socket
import logging
import zlib
from threading import Thread
from PyQt4.QtGui import QApplication
from PyQt4.QtNetwork import QUdpSocket, QHostAddress
# Config
SHARE_PORT = 31256
BROADCAST_ADDR = '192.168.1.255'
MAX_TEXT_SIZE = 1024
class ClipShare(object):
def __init__(self):
# Setup logger
self.logger = logging.getLogger("clipshare")
self.logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("[%(asctime)s][%(levelname)s]: %(message)s")
ch.setFormatter(formatter)
self.logger.addHandler(ch)
self.cliptext = ''
self.recvtext = ''
# Setup Qt application
self.app = QApplication([])
self.clip = self.app.clipboard()
self.clip.dataChanged.connect(self.cb_change)
# Setup UDP socket
self.sock = QUdpSocket()
self.sock.bind(SHARE_PORT, QUdpSocket.ShareAddress)
self.sock.readyRead.connect(self.receive)
# Incoming datagram handler
def receive(self):
while self.sock.hasPendingDatagrams():
data, host, port = self.sock.readDatagram(self.sock.pendingDatagramSize())
data = zlib.decompress(data).decode('utf-8')
if data == self.cliptext:
self.logger.debug('Caught own broadcast, ignoring.')
return
self.logger.debug('Listener received data from %s: %s' %
(host.toString(), data))
self.recvtext = data
self.clip.setText(data)
# Clipboard change handler
def cb_change(self):
text = self.clip.text()
if text == self.recvtext:
self.logger.debug('Caught clipshare clipboard update, ignoring.')
return
text = unicode(text).encode('utf-8')
self.logger.debug('Clipboard updated, content length is %d.' % len(text))
if len(text) > MAX_TEXT_SIZE:
self.logger.debug('New board content over size limit, ignoring.')
elif text == self.cliptext:
self.logger.debug('Updated content identical, ignoring.')
else:
self.cliptext = text
self.logger.info('Sending clipboard content.')
self.sock.writeDatagram(zlib.compress(text), QHostAddress(BROADCAST_ADDR),
SHARE_PORT)
if __name__ == '__main__':
cs = ClipShare()
cs.app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment