def exportThumbnail(self, report_path, thumbpath, name, node, size=None): self.thumbnailer = Thumbnailer() if self.thumbnailer.isThumbnailable(node): pixmap = self.thumbnailer.generate(node, iconSize=256, frames=10, blocking=True) self.thumbnailer.unregister() if pixmap: try: exportPath = os.path.join(report_path, os.path.join(thumbpath, name)) array = QByteArray() qfile = QBuffer(array) qfile.open(QIODevice.ReadWrite) pixmap.save(qfile, 'JPG') qfile.seek(0) with open(exportPath, 'wb') as f: f.write(qfile.read(qfile.size())) qfile.close() return True except Exception as e: qfile.close() return False else: return False
def render_to_file(self, url, file_object): """Renders the image into a File resource. Returns the size of the data that has been written. """ format = self.format # this may not be constant due to processEvents() image = self.render(url) qBuffer = QBuffer() image.save(qBuffer, format, quality=self.quality) file_object.write(qBuffer.buffer().data()) return qBuffer.size()
class ReportJSRenderReply(QNetworkReply): def __init__(self, parent, request): QNetworkReply.__init__(self, parent) self.__parent = parent self.qbuffer = None self.connect(self, SIGNAL('abouteToClose()'), self.__close) self.byteArray = QByteArray() self.qbuffer = QBuffer(self.byteArray) self.setRequest(request) self.setOperation(QNetworkAccessManager.GetOperation) self.setHeader( QNetworkRequest.ContentTypeHeader, QVariant( '"text/javascript" charset="utf-8" language="javascript"')) self.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QVariant(QNetworkRequest.AlwaysNetwork)) self.open() self.setUrl(request.url()) self.writeJS() QTimer.singleShot(0, self, SIGNAL("readyRead()")) QTimer.singleShot(0, self, SIGNAL("finished()")) def writeJS(self): pageName = self.url().path() pageName = unicode(pageName).encode('UTF-8', 'replace') buff = "" try: buff = self.__parent.pages[pageName] except KeyError: print "can't get page " + pageName self.qbuffer.write(buff) self.qbuffer.seek(0) def abort(self): self.close() def __del__(self): pass def open(self, mode=None): try: self.qbuffer.open(QIODevice.ReadWrite | QIODevice.Unbuffered) self.setOpenMode(QIODevice.ReadWrite | QIODevice.Unbuffered) return True except (AttributeError, IOError): return False def seek(self, pos): if self.qbuffer: return self.qbuffer.seek(pos) return False def __close(self): if self.qbuffer: self.qbuffer.close() self.qbuffer = None return True def readData(self, size): if self.qbuffer: return self.qbuffer.read(size) return "" def pos(self): if self.qbuffer: return self.qbuffer.pos() return 0 def isSequential(self): if self.qbuffer: return self.qbuffer.isSequential() return False def size(self): return self.qbuffer.size() def reset(self): if self.qbuffer: self.qbuffer.seek(0) return True return False def atEnd(self): if self.qbuffer: return self.qbuffer.atEnd() return False
class NodeThumbnailRenderReply(QNetworkReply): def __init__(self, parent, request): QNetworkReply.__init__(self, parent) self.qbuffer = None self.connect(self, SIGNAL('abouteToClose()'), self.__close) self.byteArray = QByteArray() self.qbuffer = QBuffer(self.byteArray) self.node = vfs().getnode(str(request.url().path().toUtf8())) self.thumbnailer = Thumbnailer() self.connect(self.thumbnailer, SIGNAL("ThumbnailUpdate"), self.updateThumbnail) self.setRequest(request) self.setOperation(QNetworkAccessManager.GetOperation) mime = "image/jpg" self.setHeader(QNetworkRequest.ContentTypeHeader, QVariant(mime)) self.open() self.setUrl(request.url()) self.connect(parent, SIGNAL("ready"), self.ready) self.ready() def ready(self): if self.node.dataType().find('video') != -1: pixmap = self.thumbnailer.generate(self.node, iconSize=128, frames=10) else: pixmap = self.thumbnailer.generate(self.node, iconSize=256, frames=10) if pixmap: self.updateThumbnail(self.node, pixmap) def updateThumbnail(self, node, pixmap): if pixmap == None: pixmap = QPixmap(":file_broken.png") pixmap.save(self.qbuffer, 'JPG') self.qbuffer.seek(0) QTimer.singleShot(0, self, SIGNAL("readyRead()")) QTimer.singleShot(0, self, SIGNAL("finished()")) def abort(self): self.close() def __del__(self): self.thumbnailer.unregister() def open(self, mode=None): try: self.qbuffer.open(QIODevice.ReadWrite | QIODevice.Unbuffered) self.setOpenMode(QIODevice.ReadWrite | QIODevice.Unbuffered) return True except (AttributeError, IOError): return False def seek(self, pos): if self.qbuffer: return self.qbuffer.seek(pos) return False def __close(self): if self.qbuffer: self.qbuffer.close() self.qbuffer = None return True def readData(self, size): if self.qbuffer: return self.qbuffer.read(size) return "" def pos(self): if self.qbuffer: return self.qbuffer.pos() return 0 def isSequential(self): if self.qbuffer: return self.qbuffer.isSequential() return False def size(self): return self.qbuffer.size() def reset(self): if self.qbuffer: self.qbuffer.seek(0) return True return False def atEnd(self): if self.qbuffer: return self.qbuffer.atEnd() return False
class Connection(QTcpSocket): """Abstracts server-client connections. Whenever data is received, a Connection attempts to parse a Message and arguments from the data, and emits messageReceived for each parsed message. See QTcpSocket documentation for other members.""" messageSent = pyqtSignal(int, list) """Emitted whenever a message is sent. Arguments: the message type, list of arguments.""" messageReceived = pyqtSignal(int, list) """Emitted whenever a message is recieved. Arguments: the message type, list of arguments.""" messageReceived2 = pyqtSignal() def __init__(self, id = None, client = False, parent = None): """Creates a connection. id -- Optional socket descriptor. client -- Whether this connection is opened from the client side or server side. parent -- Parent object.""" QTcpSocket.__init__(self, parent) if id: if not self.setSocketDescriptor(id): self.done() return self.id = id self.player = None self.client = client self.buffer = QBuffer() self.buffer.open(QBuffer.ReadWrite) self.readyRead.connect(self._readIncomingData) def abort(self): """Aborts the connection.""" super(Connection, self).abort() def _readIncomingData(self): bytesWritten = self.buffer.write(self.readAll()) self.buffer.seek(0) result = self._parse() bytesRead = 0 while result: bytesRead += result[2] msg, args = result[:2] if self.client: log.debug("Received %s %s", msg, args) elif self.player and self.player.name: log.debug("Received %s %s from %s", msg, args, self.player) else: log.debug("Received %s %s from %s", msg, args, self.peerAddress().toString()) self.messageReceived.emit(msg, args) self.messageReceived2.emit() result = self._parse() #remove the successfully parsed data size = self.buffer.size() self.buffer.close() data = self.buffer.data() self.buffer.setData(data.right(size - bytesRead)) self.buffer.open(QBuffer.ReadWrite) self.buffer.seek(self.buffer.size()) def _parse(self): if self.buffer.bytesAvailable() >= 4: stream = QDataStream(self.buffer) msg = Message.fromInt(stream.readInt32()) if msg == None: return args = [] bytesRead = 4 for aType in msg.argTypes: if aType == str: if self.buffer.bytesAvailable() < 4: return length = stream.readInt32() if self.buffer.bytesAvailable() < length: return args.append(stream.readRawData(length)) bytesRead += 4 + length elif aType == int: if self.buffer.bytesAvailable() < 4: return args.append(stream.readInt32()) bytesRead += 4 elif aType == long: if self.buffer.bytesAvailable() < 8: return args.append(stream.readInt64()) bytesRead += 8 return (msg, args, bytesRead) def sendMessage(self, msg, args, id = None): """Sends a message. msg -- The message type. args -- List of message arguments. id -- An optional socket descriptor. If specified, then the message will only be sent if this connection's socket descriptor matches id.""" if id: if self.socketDescriptor() != id: return msg = Message.fromInt(msg) if not msg.validateArgs(args): log.warning("Message %d and args %s have invalid types. Message not sent.", msg, args) return if self.client: log.debug("Sending %s %s", msg, args) elif self.player and self.player.name: log.debug("Sending %s %s to %s", msg, args, self.player) else: log.debug("Sending %s %s to %s", msg, args, self.peerAddress().toString()) data = QByteArray() stream = QDataStream(data, self.WriteOnly) stream.writeInt32(int(msg)) for arg in args: if type(arg) == str: stream.writeInt32(len(arg)) stream.writeRawData(arg) elif type(arg) == int: stream.writeInt32(arg) elif type(arg) == long: stream.writeInt64(arg) self.write(data) self.messageSent.emit(msg, args)