def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError, "unrecognized file type" fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError, "unrecognized file type version" self.ships = [] while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, err: exception = err
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError, "unrecognized file type" fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError, "unrecognized file type version" self.ships = [] while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, e: exception = e
def changeResolution(self): fileName = QFileDialog.getOpenFileName( self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open', QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadWrite): QMessageBox.warning( self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) headerVersion = data.readInt32() xdpi = data.readInt32() ydpi = data.readInt32() dialog = ChangeResolutionDialog(xdpi, ydpi, self) if dialog.exec_(): file.seek(4) data.writeInt32(dialog.sbXdpi.value()) data.writeInt32(dialog.sbYdpi.value()) self.status.showMessage("Resolution changed successful", 7000) file.close()
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 read_project(settings, openFileName): """ Toplevel reader routine. """ status = None handle = None try: handle = QFile(openFileName) if not handle.open(QIODevice.ReadOnly): raise IOError(handle.errorString()) stream = QDataStream(handle) # check header magic = stream.readInt32() if magic != MAGIC_NUMBER: status = ("Unrecognized file type - \n{0}\nis not " "a sconcho spf file!").format(openFileName) raise IOError(status) version = stream.readInt32() stream.setVersion(QDataStream.Qt_4_5) # initialize API specific entries repeatLegends = {} rowRepeats = [] textItems = [] rowLabels = {} columnLabels = {} if version == 1: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats) = read_API_1_version(stream, settings) elif version == 2: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems) = \ read_API_2_version(stream, settings) elif version == 3: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels) = \ read_API_3_version(stream, settings) else: raise IOError("unsupported API version") except (IOError, OSError) as e: status = "Failed to open %s: %s " % (openFileName, e) finally: if handle is not None: handle.close() if status is not None: return (False, status, None, None, None, None, None, None, None, None) return (True, None, patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels)
def open(self): self.offerSave() path = (QFileInfo(self.filename).path() if not self.filename.isEmpty() else ".") fname = QFileDialog.getOpenFileName(self, "Page Designer - Open", path, "Page Designer Files (*.pgd)") if fname.isEmpty(): return self.filename = fname fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) items = self.scene.items() while items: item = items.pop() self.scene.removeItem(item) del item self.addBorders() stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) magic = stream.readInt32() if magic != MagicNumber: raise IOError, "not a valid .pgd file" fileVersion = stream.readInt16() if fileVersion != FileVersion: raise IOError, "unrecognised .pgd file version" while not fh.atEnd(): self.readItemFromStream(stream) except IOError, e: QMessageBox.warning(self, "Page Designer -- Open Error", "Failed to open {0}: {1}".format(self.filename, e))
def loadQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) magic = stream.readInt32() if magic != MovieContainer.MAGIC_NUMBER: raise IOError("unrecognized file type") version = stream.readInt32() if version < MovieContainer.OLD_FILE_VERSION: raise IOError("old and unreadable file format") elif version > MovieContainer.FILE_VERSION: raise IOError("new and unreadable file format") old = False if version == MovieContainer.OLD_FILE_VERSION: old = True stream.setVersion(QDataStream.Qt_4_2) self.clear(False) while not stream.atEnd(): title = QString() acquired = QDate() location = QString() notes = QString() stream >> title year = stream.readInt16() minutes = stream.readInt16() if old: stream >> acquired >> notes else: stream >> acquired >> location >> notes self.add(Movie(title, year, minutes, acquired, location, notes)) except EnvironmentError as e: error = "Failed to load: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {0} movie records from {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def changeResolution(self): fileName = QFileDialog.getOpenFileName(self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open',QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadWrite): QMessageBox.warning(self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) headerVersion = data.readInt32() xdpi = data.readInt32() ydpi = data.readInt32() dialog = ChangeResolutionDialog(xdpi, ydpi, self) if dialog.exec_(): file.seek(4) data.writeInt32(dialog.sbXdpi.value()) data.writeInt32(dialog.sbYdpi.value()) self.status.showMessage("Resolution changed successful", 7000) file.close()
def decode_data(self, bytearray): """Handle drag/drop data.""" data = [] item = {} ds = QDataStream(bytearray) while not ds.atEnd(): row = ds.readInt32() column = ds.readInt32() map_items = ds.readInt32() for i in range(map_items): key = ds.readInt32() value = QVariant() ds >> value item[Qt.ItemDataRole(key)] = value data.append(item) return data
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError("no filename specified for loading") fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError("unrecognized file type") fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError("unrecognized file type version") self.ships = {} while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() ship = Ship(name, owner, country, teu, description) self.ships[id(ship)] = ship self.owners.add(str(owner)) self.countries.add(str(country)) self.dirty = False except IOError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
def run(self): fh = QFile(self.filename) fhlen = self._file_len(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) self.data_block = {} stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) magic = stream.readInt32() if magic != gMAGICNUM: raise IOError, "not a valid .jd file" fileVersion = stream.readInt16() if fileVersion != gFILEVERSION: raise IOError, "unrecognised .jd file version" while not fh.atEnd(): self._ReadItemFromStream(stream) self.emit(SIGNAL("PROJECTLOADERDONE(PyQt_PyObject)"), self.data_block)
def unpackPrnFile(self): fileName = QFileDialog.getOpenFileName(self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open',QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadOnly): QMessageBox.warning(self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) file_name = QFileInfo(file).fileName() headerVersion = int.from_bytes(data.readRawData(4), 'little', signed=False) self.status.showMessage("Header Type: {:#X}".format(headerVersion)) if headerVersion == self.NEW_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) name = b'\xff\xfe' + data.readRawData(512) name = name.decode('utf-16').replace(chr(0), '') zero = data.readInt32() elif headerVersion == self.STD_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() if not bitsperdrop: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) zero = data.readInt32() name = 'Not used in this format' elif headerVersion == self.CALDERA_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() if not bitsperdrop: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) zero = data.readInt32() name = 'Not used in this format' else: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colors = {} for color in colorList: colors[color] = {} for level in range(1, 2**bitsperdrop): colors[color][level] = QImage(imgw, imgh , QImage.Format_Mono) colors[color][level].setColor(0, qRgb(255, 255, 255)) colors[color][level].setColor(1, qRgb(0, 0, 0)) colors[color][level].fill(0) pd = QProgressDialog('Analyze file ...', 'Cancel', 0, imgh-1, self) pd.setWindowTitle('Analyze ...') pd.open() mask = 0xFF>>(8-bitsperdrop) # Получаем маску для текущего количества бит на каплю for row in range(imgh): for color in colorList: for bytenum in range(0, bpl, bitsperdrop): # Получаем номер байта, с которого будем читать byte = int.from_bytes(data.readRawData(bitsperdrop), 'big') for pix in range(8): shift = (7 - pix)*bitsperdrop pixel = (byte>>shift)&mask if pixel > 0: numofpix = 8*bytenum/bitsperdrop + pix if numofpix < imgw: colors[color][pixel].setPixel(numofpix, row, 1) pd.setValue(row) if pd.wasCanceled(): pd.close() file.close() return pd.close() file.close() catalog = QFileDialog.getExistingDirectory(self, directory=self.settings.value('unpacker/dir_save',QDir.currentPath())) if catalog is None: return self.settings.setValue('unpacker/dir_save', catalog) file = QFile("{}\{}_{}.txt".format(catalog, file_name, colorOrder)) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning(self, "Prn creator", "Unable create file {}:\n{}.".format(name, file.errorString())) return text = QTextStream(file) text << "Filename: {}\n".format(file_name) text << "Test Name: {}\n\n".format(name) text << "X Resolution: {} dpi\n".format(xdpi) text << "Y Resolution: {} dpi\n".format(ydpi) text << "Image Width: {} pix\n".format(imgw) text << "Image Height: {} pix\n\n".format(imgh) text << "Bits Per Drop: {}\n".format(bitsperdrop) text << "Bytes Per Line: {}\n\n".format(bpl) text << "Number Of Colors: {}\n".format(colnum) text << "Order Of Colors: {}\n\n".format(colorOrder) text << "Paper Width: {}\n".format(ppw) for color in colorList: for level in range(1, 2**bitsperdrop): colors[color][level].save("{}\{}.{}.gs{}.tif".format(catalog, file_name, "{}".format(color) if color.isupper() else "_{}".format(color), level)) self.status.showMessage("Unpacking finished", 7000)
def unpackPrnFile(self): fileName = QFileDialog.getOpenFileName( self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open', QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadOnly): QMessageBox.warning( self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) file_name = QFileInfo(file).fileName() headerVersion = int.from_bytes(data.readRawData(4), 'little', signed=False) self.status.showMessage("Header Type: {:#X}".format(headerVersion)) if headerVersion == self.NEW_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) name = b'\xff\xfe' + data.readRawData(512) name = name.decode('utf-16').replace(chr(0), '') zero = data.readInt32() elif headerVersion == self.STD_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() if not bitsperdrop: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) zero = data.readInt32() name = 'Not used in this format' elif headerVersion == self.CALDERA_RIP_FILE: xdpi = data.readInt32() ydpi = data.readInt32() bpl = data.readInt32() imgh = data.readInt32() imgw = data.readInt32() ppw = data.readInt32() colnum = data.readInt32() bitsperdrop = data.readInt32() if not bitsperdrop: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colorOrder = data.readRawData(16).decode().replace(chr(0), '') colorList = list(colorOrder) zero = data.readInt32() name = 'Not used in this format' else: QMessageBox.warning(self, "Unpacker .prn", "File format not supported") return colors = {} for color in colorList: colors[color] = {} for level in range(1, 2**bitsperdrop): colors[color][level] = QImage(imgw, imgh, QImage.Format_Mono) colors[color][level].setColor(0, qRgb(255, 255, 255)) colors[color][level].setColor(1, qRgb(0, 0, 0)) colors[color][level].fill(0) pd = QProgressDialog('Analyze file ...', 'Cancel', 0, imgh - 1, self) pd.setWindowTitle('Analyze ...') pd.open() mask = 0xFF >> ( 8 - bitsperdrop ) # Получаем маску для текущего количества бит на каплю for row in range(imgh): for color in colorList: for bytenum in range( 0, bpl, bitsperdrop ): # Получаем номер байта, с которого будем читать byte = int.from_bytes(data.readRawData(bitsperdrop), 'big') for pix in range(8): shift = (7 - pix) * bitsperdrop pixel = (byte >> shift) & mask if pixel > 0: numofpix = 8 * bytenum / bitsperdrop + pix if numofpix < imgw: colors[color][pixel].setPixel(numofpix, row, 1) pd.setValue(row) if pd.wasCanceled(): pd.close() file.close() return pd.close() file.close() catalog = QFileDialog.getExistingDirectory( self, directory=self.settings.value('unpacker/dir_save', QDir.currentPath())) if catalog is None: return self.settings.setValue('unpacker/dir_save', catalog) file = QFile("{}\{}_{}.txt".format(catalog, file_name, colorOrder)) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning( self, "Prn creator", "Unable create file {}:\n{}.".format(name, file.errorString())) return text = QTextStream(file) text << "Filename: {}\n".format(file_name) text << "Test Name: {}\n\n".format(name) text << "X Resolution: {} dpi\n".format(xdpi) text << "Y Resolution: {} dpi\n".format(ydpi) text << "Image Width: {} pix\n".format(imgw) text << "Image Height: {} pix\n\n".format(imgh) text << "Bits Per Drop: {}\n".format(bitsperdrop) text << "Bytes Per Line: {}\n\n".format(bpl) text << "Number Of Colors: {}\n".format(colnum) text << "Order Of Colors: {}\n\n".format(colorOrder) text << "Paper Width: {}\n".format(ppw) for color in colorList: for level in range(1, 2**bitsperdrop): colors[color][level].save("{}\{}.{}.gs{}.tif".format( catalog, file_name, "{}".format(color) if color.isupper() else "_{}".format(color), level)) self.status.showMessage("Unpacking finished", 7000)