def exportXml(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='{0}'?>\n" "<!DOCTYPE MOVIES>\n" "<MOVIES VERSION='1.0'>\n".format(CODEC)) for key, movie in self.__movies: stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' " "ACQUIRED='{2}'>\n".format(movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) \ << "<TITLE>" << Qt.escape(movie.title) \ << "</TITLE>\n<NOTES>" if not movie.notes.isEmpty(): stream << "\n" << Qt.escape( encodedNewlines(movie.notes)) stream << "\n</NOTES>\n</MOVIE>\n" stream << "</MOVIES>\n" except EnvironmentError as e: error = "Failed to export: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Exported {0} movie records to {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def updateHistory(self): lines = [] for line in self.lines: text = Qt.escape(line.text) target = Qt.escape(line.target) if line.type == Line.Chat or line.type == Line.Whisper: (r, g, b) = [int(c * 0.75) for c in line.playerColor] sender = Qt.escape(line.sender) dateTime = QDateTime.fromTime_t(int(line.timestamp)) time = dateTime.toString("hh:mm:ss AP") if line.type == Line.Whisper: lines.append("<p><strong style=\"color: rgb(%d, %d, %d)\">[%s] %s >> %s</strong>: %s</p>" % (r, g, b, time, sender, target, text)) else: lines.append("<p><strong style=\"color: rgb(%d, %d, %d)\">[%s] %s</strong>: %s</p>" % (r, g, b, time, sender, text)) else: if line.type == Line.Info: (r, g, b) = (0, 0, 170) text = line.text elif line.type == Line.PlayerJoined: (r, g, b) = (0, 170, 0) text = "%s has joined." % (target) elif line.type == Line.PlayerRejoined: (r, g, b) = (0, 170, 0) text = "%s has rejoined." % (target) elif line.type == Line.PlayerLeft: (r, g, b) = (170, 0, 0) text = "%s has left." % (target) lines.append("<p style=\"color: rgb(%d, %d, %d)\">** %s **</p>" % (r, g, b, text)) self.history.setHtml( "<html><body>%s</body></html>" % ("".join(lines)) ) self.history.verticalScrollBar().setValue(self.history.verticalScrollBar().maximum())
def exportXml(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='{0}'?>\n" "<!DOCTYPE MOVIES>\n" "<MOVIES VERSION='1.0'>\n".format(CODEC)) for key, movie in self.__movies: stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' " "ACQUIRED='{2}'>\n".format(movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) \ << "<TITLE>" << Qt.escape(movie.title) \ << "</TITLE>\n<NOTES>" if not movie.notes.isEmpty(): stream << "\n" << Qt.escape(encodedNewlines(movie.notes)) stream << "\n</NOTES>\n</MOVIE>\n" stream << "</MOVIES>\n" except EnvironmentError as e: error = "Failed to export: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Exported {0} movie records to {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def printDocument1(self): html = u"" date = QDate.currentDate().toString(self.DATE_FORMAT) address = Qt.escape("Bario francisco mesa").replace(",", "<br>") contact = Qt.escape("Luis Mejia") balance = 5000 html += ("<p align=right><img src=':/logo.png'></p>" "<p> align = right>Greasy hands ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>%s</p>" "<p>%s</p><p>Dear %s, </p>" "<p>The balance of your account is %s.") % ( date, address, contact, QString("$ %L1").arg( float(balance), 0, "f", 2)) if balance < 0: html += ( "<p><font color =red><b> Please remit the amount owing immediately.</b></font>" ) else: html += "We are delighted to have done business with you." html += ( "</p><p> </p><p>" "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>" ) transactions = [(QDate.currentDate(), 500), (QDate.currentDate(), 500), (QDate.currentDate(), -500), (QDate.currentDate(), 500)] for date, amount in transactions: color, status = "black", "Credit" if amount < 0: color, status = "red", "Debid" html += ( "<tr>" "<td align= right>%s</td>" "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % (date.toString(self.DATE_FORMAT), status, color, QString("$ %L1").arg(float(abs(amount)), 0, "f", 2))) html += ("</table></p><p style='page-break-after=always;'>" "We hope to continue doing business with you</p>") pdialog = QPrintDialog() if pdialog.exec_() == QDialog.Accepted: printer = pdialog.printer() document = QTextDocument() document.setHtml(html) document.print_(printer)
def printDocument1(self): html = u"" date = QDate.currentDate().toString(self.DATE_FORMAT) address = Qt.escape("Bario francisco mesa").replace(",","<br>") contact = Qt.escape("Luis Mejia") balance = 5000 html += ("<p align=right><img src=':/logo.png'></p>" "<p> align = right>Greasy hands ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>%s</p>" "<p>%s</p><p>Dear %s, </p>" "<p>The balance of your account is %s.")% ( date, address, contact, QString("$ %L1").arg(float(balance),0,"f",2)) if balance <0 : html += ("<p><font color =red><b> Please remit the amount owing immediately.</b></font>") else: html += "We are delighted to have done business with you." html += ("</p><p> </p><p>" "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>") transactions = [ (QDate.currentDate(),500), (QDate.currentDate(),500), (QDate.currentDate(),-500), (QDate.currentDate(),500) ] for date, amount in transactions: color, status = "black", "Credit" if amount <0: color, status = "red", "Debid" html += ("<tr>" "<td align= right>%s</td>" "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % ( date.toString(self.DATE_FORMAT), status,color, QString("$ %L1").arg(float(abs(amount)), 0, "f",2))) html += ("</table></p><p style='page-break-after=always;'>" "We hope to continue doing business with you</p>") pdialog = QPrintDialog() if pdialog.exec_() == QDialog.Accepted: printer = pdialog.printer() document = QTextDocument() document.setHtml(html) document.print_(printer)
def toMarkdown(self): references = '' i = 1 # doc = QString() # the full document doc = g.u('') block = self.document().begin( ) # block is like a para; text fragment is sequence of same char format while block.isValid(): #print "block=",block.text() if block.blockFormat().nonBreakableLines(): doc += ' ' + block.text() + '\n' #elif block.textList(): #textList = block.textList() #print block.textList().count() #print g.u(block.textList().itemText(block)) #print block.textList().itemNumber(block) #print block.textList().item(block.textList().itemNumber(block)).text() #doc += textList.itemText(block) + ' ' + textList.item(textList.itemNumber(block)).text() + '\n\n' else: if block.textList(): doc += ' ' + block.textList().itemText(block) + ' ' # para = QString() para = g.u('') iterator = block.begin() while iterator != block.end(): fragment = iterator.fragment() if fragment.isValid(): char_format = fragment.charFormat() text = g.u(Qt.escape(fragment.text()) ) # turns chars like < into entities < font_size = char_format.font().pointSize() # a fragment can only be an anchor, italics or bold if char_format.isAnchor(): ref = text if text.startswith( 'http://') else 'http://{0}'.format(text) # too lazy right now to check if URL has already been referenced but should references += " [{0}]: {1}\n".format(i, ref) text = "[{0}][{1}]".format(text, i) i += 1 elif font_size > 10: if font_size > 15: text = '#{0}'.format(text) elif font_size > 12: text = '##{0}'.format(text) else: text = '###{0}'.format(text) elif char_format.fontFixedPitch( ): #or format.fontFamily=='courier': text = QString("`%1`").arg(text) elif char_format.fontItalic(): text = QString("*%1*").arg(text) elif char_format.fontWeight( ) > QFont.Normal: #font-weight:600; same as for an H1; H1 font-size:xx-large; H1 20; H2 15 H3 12 text = QString("**%1**").arg(text) para += text iterator += 1 doc += para + '\n\n' block = block.next() return doc + references
def log(self, message, bold=False, pre=False): if bold: self.edit.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message))) elif pre: self.edit.appendHtml(u'<pre>{0}</pre>'.format(message)) else: self.edit.appendPlainText(message)
def cb_read(result): self.log_file.release() self.log_file = None self.label_download.setVisible(False) self.progress_download.setVisible(False) if result.error != None: self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True) return try: self.content = result.data.decode('utf-8') except UnicodeDecodeError: # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails self.log(u'Error: Log file is not UTF-8 encoded', bold=True) return self.button_save.setEnabled(True) if self.continuous: content = self.content.lstrip() else: content = self.content self.edit_content.setPlainText('') font = QFont('monospace') font.setStyleHint(QFont.TypeWriter) self.edit_content.setFont(font) self.edit_content.setPlainText(content)
def log(self, message, bold=False, pre=False): if bold: self.edit_content.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message))) elif pre: self.edit_content.appendHtml(u'<pre>{0}</pre>'.format(message)) else: self.edit_content.appendPlainText(message)
def cb_read(result): self.log_file.release() self.log_file = None self.label_download.setVisible(False) self.progress_download.setVisible(False) if result.error != None: self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True) return try: self.content = result.data.decode('utf-8') except UnicodeDecodeError: # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails self.log(u'Error: Log file is not UTF-8 encoded', bold=True) return self.button_save.setEnabled(True) if self.continuous: content = self.content.lstrip() else: content = self.content self.edit_content.setPlainText('') font = QFont('monospace') font.setStyleHint(QFont.TypeWriter) self.edit_content.setFont(font) self.edit_content.setPlainText(content)
def getTooltipValue( value ): """ Takes a potentially multilined string and converts it to the form suitable for tooltips """ value = str( value ) if Qt.mightBeRichText( value ): tooltipValue = str( Qt.escape( value ) ) else: tooltipValue = value lines = tooltipValue.splitlines() lineCount = len( lines ) if lineCount > 1: value = "" index = 0 for line in lines: if index >= 5: # First 5 lines only break if index > 0: value += "\n" if len( line ) > 128: value += line[ : 128 ] + "<...>" else: value += line index += 1 if lineCount > 5: value += "\n<...>" elif lineCount == 1: if len( lines[ 0 ] ) > 128: value = lines[ 0 ][ : 128 ] + "<...>" else: value = lines[ 0 ] return value
def toMarkdown(self): references = '' i = 1 # doc = QString() # the full document doc = g.u('') block = self.document().begin() # block is like a para; text fragment is sequence of same char format while block.isValid(): #print "block=",block.text() if block.blockFormat().nonBreakableLines(): doc += ' '+block.text()+'\n' #elif block.textList(): #textList = block.textList() #print block.textList().count() #print g.u(block.textList().itemText(block)) #print block.textList().itemNumber(block) #print block.textList().item(block.textList().itemNumber(block)).text() #doc += textList.itemText(block) + ' ' + textList.item(textList.itemNumber(block)).text() + '\n\n' else: if block.textList(): doc += ' '+block.textList().itemText(block) + ' ' # para = QString() para = g.u('') iterator = block.begin() while iterator != block.end(): fragment = iterator.fragment() if fragment.isValid(): char_format = fragment.charFormat() # pylint: disable=no-member # EKR: I'm not sure whether this warning is valid. # I'm going to kill it because this is an experimental plugin. text = g.u(Qt.escape(fragment.text())) # turns chars like < into entities < font_size = char_format.font().pointSize() # a fragment can only be an anchor, italics or bold if char_format.isAnchor(): ref = text if text.startswith('http://') else 'http://{0}'.format(text) # too lazy right now to check if URL has already been referenced but should references += " [{0}]: {1}\n".format(i,ref) text = "[{0}][{1}]".format(text,i) i+=1 elif font_size > 10: if font_size > 15: text = '#{0}'.format(text) elif font_size > 12: text = '##{0}'.format(text) else: text = '###{0}'.format(text) elif char_format.fontFixedPitch(): #or format.fontFamily=='courier': text = QString("`%1`").arg(text) elif char_format.fontItalic(): text = QString("*%1*").arg(text) elif char_format.fontWeight() > QFont.Normal: #font-weight:600; same as for an H1; H1 font-size:xx-large; H1 20; H2 15 H3 12 text = QString("**%1**").arg(text) para += text iterator += 1 doc += para+'\n\n' block = block.next() return doc+references
def start_conflict_resolution(self): self.log(u'...target file {0} already exists'.format( self.upload.target)) if self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_REPLACE: self.log(u'...replacing {0}'.format(self.upload.target)) self.continue_upload_file(True) elif self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_SKIP: self.log('...skipped') self.upload_next_file() else: self.progress_file.setVisible(False) try: target_file = REDFile(self.wizard().session).open( self.target_path, REDFile.FLAG_READ_ONLY, 0, 1000, 1000) # FIXME: async_call self.label_existing_stats.setText( '{0}, last modified on {1}'.format( get_file_display_size(target_file.length), timestamp_to_date_at_time( int(target_file.modification_time)))) target_file.release() except (Error, REDError) as e: self.label_existing_stats.setText( u'<b>Error</b>: Could not open target file: {0}', Qt.escape(unicode(e))) self.label_new_stats.setText('{0}, last modified on {1}'.format( self.chunked_uploader.source_display_size, timestamp_to_date_at_time( int(self.chunked_uploader.source_stat.st_mtime)))) self.label_replace_help.setText( self.replace_help_template.replace( '<FILE>', Qt.escape(self.upload.target))) self.check_rename_new_file.setChecked( self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_RENAME) self.edit_new_name.setText('') # force a new-name check self.edit_new_name.setText(posixpath.split(self.upload.target)[1]) self.conflict_resolution_in_progress = True self.update_ui_state()
def log(self, message, bold=False, pre=False): if bold: self.edit_log.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message))) elif pre: self.edit_log.appendHtml(u'<pre>{0}</pre>'.format(message)) else: self.edit_log.appendPlainText(message) self.edit_log.verticalScrollBar().setValue(self.edit_log.verticalScrollBar().maximum())
def log(self, message, bold=False, pre=False): if bold: self.edit_log.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message))) elif pre: self.edit_log.appendHtml(u'<pre>{0}</pre>'.format(message)) else: self.edit_log.appendPlainText(message) self.edit_log.verticalScrollBar().setValue(self.edit_log.verticalScrollBar().maximum())
def download_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True)
def download_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True)
def _chatMessage( self, msg, fromUser ) : msg = unicode( msg, 'utf8', 'replace' ) msg = unicode( Qt.escape(msg) ) msg = msg.replace( '\r\n', '<br/>' ) msg = msg.replace( '\n', '<br/>' ) msg = msg.replace( '\t', ' ' ) msg = msg.replace( ' ', ' ' ) color = (fromUser == self.peerName) and '#FF821C' or 'black' self.ui.chatLogView.append( u'<font face="Verdana" size=-1 color="%s"><b>%s: </b></font>%s' % (color,fromUser,msg) ) self.flash()
def report_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.widget.progress.close() QMessageBox.critical(get_main_window(), 'Import Error', message)
def report_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.widget.progress.close() QMessageBox.critical(get_main_window(), 'Export Error', message)
def start_conflict_resolution(self): self.log(u'...target file {0} already exists'.format(self.target_path)) if self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_REPLACE: self.log(u'...replacing {0}'.format(self.download.target)) self.continue_download_file(True) elif self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_SKIP: self.log('...skipped') self.download_next_file() else: self.progress_file.setVisible(False) try: target_stat = os.stat(self.target_path) self.label_existing_stats.setText( '{0}, last modified on {1}'.format( get_file_display_size(target_stat.st_size), timestamp_to_date_at_time(int(target_stat.st_mtime)))) except Exception as e: self.label_existing_stats.setText( u'<b>Error</b>: Could not get informarion for target file: {0}', Qt.escape(unicode(e))) self.label_new_stats.setText('{0}, last modified on {1}'.format( self.chunked_downloader.source_display_size, timestamp_to_date_at_time( int(self.chunked_downloader.source_file.modification_time)) )) self.label_replace_help.setText( self.replace_help_template.replace( '<FILE>', Qt.escape(self.download.target))) self.check_rename_new_file.setChecked( self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_RENAME) self.edit_new_name.setText('') # force a new-name check self.edit_new_name.setText(os.path.split(self.download.target)[1]) self.conflict_resolution_in_progress = True self.update_ui_state()
def upload_warning(self, message, *args): self.warnings += 1 string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True)
def _chatMessage(self, msg, fromUser): msg = unicode(msg, 'utf8', 'replace') msg = unicode(Qt.escape(msg)) msg = msg.replace('\r\n', '<br/>') msg = msg.replace('\n', '<br/>') msg = msg.replace('\t', ' ') msg = msg.replace(' ', ' ') color = (fromUser == self.peerName) and '#FF821C' or 'black' self.ui.chatLogView.append( u'<font face="Verdana" size=-1 color="%s"><b>%s: </b></font>%s' % (color, fromUser, msg)) self.flash()
def upload_warning(self, message, *args): self.warnings += 1 string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True)
def cb_walk(result): okay, message = check_script_result(result, decode_stderr=True) if not okay: self.label_error.setText('<b>Error:</b> ' + Qt.escape(message)) self.label_error.setVisible(True) self.refresh_files_done() return self.label_error.setVisible(False) def expand_async(data): try: walk = json.loads( zlib.decompress(buffer(data)).decode('utf-8')) except: walk = None if walk == None or not isinstance(walk, dict): available_files = [] available_directories = [] walk = None else: available_files, available_directories = expand_walk_to_lists( walk) return walk, available_files, available_directories def cb_expand_success(result): walk, available_files, available_directories = result self.available_files = available_files self.available_directories = available_directories if walk != None: expand_walk_to_model(walk, self.tree_files_model, self.folder_icon, self.file_icon) else: self.label_error.setText( '<b>Error:</b> Received invalid data') self.label_error.setVisible(True) self.tree_files.header().setSortIndicator(0, Qt.AscendingOrder) self.refresh_files_done() def cb_expand_error(): self.label_error.setText('<b>Error:</b> Internal async error') self.label_error.setVisible(True) self.refresh_files_done() async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
def write_description_content(handle, data): """ This function generates the xml content of the description file. """ stream = QTextStream(handle) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<sconcho>\n" " <knittingSymbol>\n" " <svgName>%s</svgName>\n" " <category>%s</category>\n" " <symbolName>%s</symbolName>\n" " <symbolDescription>%s</symbolDescription>\n" " <symbolWidth>%d</symbolWidth>\n" " </knittingSymbol>\n" "</sconcho>\n" % (Qt.escape(data["svgName"]), Qt.escape(data["category"]), Qt.escape(data["name"]), Qt.escape(data["description"]), data["width"]))
def escapeHTML(text, nl2br=True): r""" Escape HTML to be used in a widget displaying HMTL code. Example: >>> escapeHTML('<a>text</a>') u'<a>text</a>' >>> print escapeHTML('one\ntwo') one<br />two """ text = Qt.escape(text) text = unicode(text) if nl2br: text = text.replace("\n", "<br />") return text
def upload_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True) if not self.edit_mode and self.program_defined: try: self.program.purge() # FIXME: async_call except (Error, REDError): pass # FIXME: report this error?
def upload_error(self, message, *args): string_args = [] for arg in args: string_args.append(Qt.escape(unicode(arg))) if len(string_args) > 0: message = unicode(message).format(*tuple(string_args)) self.log(message, bold=True) if not self.edit_mode and self.program_defined: try: self.program.purge() # FIXME: async_call except (Error, REDError): pass # FIXME: report this error?
def cb_walk(result): okay, message = check_script_result(result, decode_stderr=True) if not okay: self.label_error.setText('<b>Error:</b> ' + Qt.escape(message)) self.label_error.setVisible(True) self.refresh_files_done() return self.label_error.setVisible(False) def expand_async(data): try: walk = json.loads(zlib.decompress(buffer(data)).decode('utf-8')) except: walk = None if walk == None or not isinstance(walk, dict): available_files = [] available_directories = [] walk = None else: available_files, available_directories = expand_walk_to_lists(walk) return walk, available_files, available_directories def cb_expand_success(result): walk, available_files, available_directories = result self.available_files = available_files self.available_directories = available_directories if walk != None: expand_walk_to_model(walk, self.tree_files_model, self.folder_icon, self.file_icon) else: self.label_error.setText('<b>Error:</b> Received invalid data') self.label_error.setVisible(True) self.tree_files.header().setSortIndicator(0, Qt.AscendingOrder) self.refresh_files_done() def cb_expand_error(): self.label_error.setText('<b>Error:</b> Internal async error') self.label_error.setVisible(True) self.refresh_files_done() async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
def cb_read(result): done() if result.error != None: if result.error.error_code != REDError.E_OPERATION_ABORTED: log.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True) return try: content = result.data.decode('utf-8') except UnicodeDecodeError: # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails log.log(u'Error: Log file is not UTF-8 encoded', bold=True) return log.set_content(content)
def cb_read(result): done() if result.error != None: if result.error.error_code != REDError.E_OPERATION_ABORTED: log.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True) return try: content = result.data.decode('utf-8') except UnicodeDecodeError: # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails log.log(u'Error: Log file is not UTF-8 encoded', bold=True) return log.set_content(content)
def toSimpleHtml(self): html = QString() black = QColor(Qt.black) block = self.document().begin() while block.isValid(): iterator = block.begin() while iterator != block.end(): fragment = iterator.fragment() if fragment.isValid(): format = fragment.charFormat() family = format.fontFamily() color = format.foreground().color() text = Qt.escape(fragment.text()) if (format.verticalAlignment() == QTextCharFormat.AlignSubScript): text = QString("<sub>%1</sub>").arg(text) elif (format.verticalAlignment() == QTextCharFormat.AlignSuperScript): text = QString("<sup>%1</sup>").arg(text) if format.fontUnderline(): text = QString("<u>%1</u>").arg(text) if format.fontItalic(): text = QString("<i>%1</i>").arg(text) if format.fontWeight() > QFont.Normal: text = QString("<b>%1</b>").arg(text) if format.fontStrikeOut(): text = QString("<s>%1</s>").arg(text) if color != black or not family.isEmpty(): attribs = "" if color != black: attribs += ' color="{0}"'.format(color.name()) if not family.isEmpty(): attribs += ' face="{0}"'.format(family) text = (QString("<font%1>%2</font>").arg(attribs).arg( text)) html += text iterator += 1 block = block.next() return html
def toSimpleHtml(self): html = QString() black = QColor(Qt.black) block = self.document().begin() while block.isValid(): iterator = block.begin() while iterator != block.end(): fragment = iterator.fragment() if fragment.isValid(): format = fragment.charFormat() family = format.fontFamily() color = format.foreground().color() text = Qt.escape(fragment.text()) if (format.verticalAlignment() == QTextCharFormat.AlignSubScript): text = QString("<sub>%1</sub>").arg(text) elif (format.verticalAlignment() == QTextCharFormat.AlignSuperScript): text = QString("<sup>%1</sup>").arg(text) if format.fontUnderline(): text = QString("<u>%1</u>").arg(text) if format.fontItalic(): text = QString("<i>%1</i>").arg(text) if format.fontWeight() > QFont.Normal: text = QString("<b>%1</b>").arg(text) if format.fontStrikeOut(): text = QString("<s>%1</s>").arg(text) if color != black or not family.isEmpty(): attribs = "" if color != black: attribs += ' color="{0}"'.format(color.name()) if not family.isEmpty(): attribs += ' face="{0}"'.format(family) text = (QString("<font%1>%2</font>") .arg(attribs).arg(text)) html += text iterator += 1 block = block.next() return html
def log_error(self, message): self.edit_errors.show() self.edit_errors.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
def log_error(self, message): self.edit_errors.show() self.edit_errors.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
def update(self, zoom_only = False): self.update_ticks() line_color = self.plot.color(OWPalette.Axis) text_color = self.plot.color(OWPalette.Text) if not self.graph_line or not self.scene(): return self.line_item.setLine(self.graph_line) self.line_item.setPen(line_color) if self.title: self.title_item.setHtml('<b>' + self.title + '</b>') self.title_item.setDefaultTextColor(text_color) if self.title_location == AxisMiddle: title_p = 0.5 elif self.title_location == AxisEnd: title_p = 0.95 else: title_p = 0.05 title_pos = self.graph_line.pointAt(title_p) v = self.graph_line.normalVector().unitVector() dense_text = False if hasattr(self, 'title_margin'): offset = self.title_margin elif self._ticks: if self.should_be_expanded(): offset = 55 dense_text = True else: offset = 35 else: offset = 10 if self.title_above: title_pos = title_pos + (v.p2() - v.p1())*(offset + QFontMetrics(self.title_item.font()).height()) else: title_pos = title_pos - (v.p2() - v.p1())*offset ## TODO: Move it according to self.label_pos self.title_item.setVisible(self.show_title) self.title_item.setRotation(-self.graph_line.angle()) c = self.title_item.mapToParent(self.title_item.boundingRect().center()) tl = self.title_item.mapToParent(self.title_item.boundingRect().topLeft()) self.title_item.setPos(title_pos - c + tl) ## Arrows if not zoom_only: if self.start_arrow_item: self.scene().removeItem(self.start_arrow_item) self.start_arrow_item = None if self.end_arrow_item: self.scene().removeItem(self.end_arrow_item) self.end_arrow_item = None if self.arrows & AxisStart: if not zoom_only or not self.start_arrow_item: self.start_arrow_item = QGraphicsPathItem(self.arrow_path, self) self.start_arrow_item.setPos(self.graph_line.p1()) self.start_arrow_item.setRotation(-self.graph_line.angle() + 180) self.start_arrow_item.setBrush(line_color) self.start_arrow_item.setPen(line_color) if self.arrows & AxisEnd: if not zoom_only or not self.end_arrow_item: self.end_arrow_item = QGraphicsPathItem(self.arrow_path, self) self.end_arrow_item.setPos(self.graph_line.p2()) self.end_arrow_item.setRotation(-self.graph_line.angle()) self.end_arrow_item.setBrush(line_color) self.end_arrow_item.setPen(line_color) ## Labels n = len(self._ticks) resize_plot_item_list(self.label_items, n, QGraphicsTextItem, self) resize_plot_item_list(self.label_bg_items, n, QGraphicsRectItem, self) resize_plot_item_list(self.tick_items, n, QGraphicsLineItem, self) test_rect = QRectF(self.graph_line.p1(), self.graph_line.p2()).normalized() test_rect.adjust(-1, -1, 1, 1) n_v = self.graph_line.normalVector().unitVector() if self.title_above: n_p = n_v.p2() - n_v.p1() else: n_p = n_v.p1() - n_v.p2() l_v = self.graph_line.unitVector() l_p = l_v.p2() - l_v.p1() for i in range(n): pos, text, size, step = self._ticks[i] hs = 0.5 * step tick_pos = self.map_to_graph( pos ) if not test_rect.contains(tick_pos): self.tick_items[i].setVisible(False) self.label_items[i].setVisible(False) continue item = self.label_items[i] item.setVisible(True) if not zoom_only: if self.id in XAxes or getattr(self, 'is_horizontal', False): item.setHtml( '<center>' + Qt.escape(text.strip()) + '</center>') else: item.setHtml(Qt.escape(text.strip())) item.setTextWidth(-1) text_angle = 0 if dense_text: w = min(item.boundingRect().width(), self.max_text_width) item.setTextWidth(w) if self.title_above: label_pos = tick_pos + n_p * (w + self.text_margin) + l_p * item.boundingRect().height()/2 else: label_pos = tick_pos + n_p * self.text_margin + l_p * item.boundingRect().height()/2 text_angle = -90 if self.title_above else 90 else: w = min(item.boundingRect().width(), QLineF(self.map_to_graph(pos - hs), self.map_to_graph(pos + hs) ).length()) label_pos = tick_pos + n_p * self.text_margin - l_p * w/2 item.setTextWidth(w) if not self.always_horizontal_text: if self.title_above: item.setRotation(-self.graph_line.angle() - text_angle) else: item.setRotation(self.graph_line.angle() - text_angle) item.setPos(label_pos) item.setDefaultTextColor(text_color) self.label_bg_items[i].setRect(item.boundingRect()) self.label_bg_items[i].setPen(QPen(Qt.NoPen)) self.label_bg_items[i].setBrush(self.plot.color(OWPalette.Canvas)) item = self.tick_items[i] item.setVisible(True) tick_line = QLineF(v) tick_line.translate(-tick_line.p1()) tick_line.setLength(size) if self.title_above: tick_line.setAngle(tick_line.angle() + 180) item.setLine( tick_line ) item.setPen(line_color) item.setPos(self.map_to_graph(pos))
def initializePage(self): self.set_formatted_sub_title( u'The complete configuration of the {language} program [{name}].') language = self.get_field('language') language_display_name = Constants.language_display_names[language] language_api_name = Constants.language_api_names[language] # general information html = u'<b>General Information</b><br/>' html += u'Name: {0}<br/>'.format(Qt.escape(self.get_field('name'))) html += u'Identifier: {0}<br/>'.format( Qt.escape(self.get_field('identifier'))) html += u'Language: {0}<br/>'.format(Qt.escape(language_display_name)) html += u'Description: {0}<br/>'.format( Qt.escape(self.get_field('description'))) html += u'<br/>' # files html += u'<b>Files</b>' items = self.wizard().page(Constants.PAGE_FILES).get_items() if len(items) == 0: html += u' (none)' html += u'<br/>' for item in items: html += u'{0}<br/>'.format(Qt.escape(item)) html += u'<br/>' # language specific configuration html += u'<b>{0} Configuration</b><br/>'.format( Qt.escape(language_display_name)) html += self.wizard().page( Constants.get_language_page(language_api_name)).get_html_summary() html += u'<br/>' if self.wizard().hasVisitedPage(Constants.PAGE_ARGUMENTS): # arguments html += u'<b>Arguments</b>' arguments = self.wizard().page( Constants.PAGE_ARGUMENTS).get_arguments() if len(arguments) == 0: html += u' (none)' html += u'<br/>' for argument in arguments: html += u'{0}<br/>'.format(Qt.escape(argument)) html += u'<br/>' # environment html += u'<b>Environment</b>' environment = self.wizard().page( Constants.PAGE_ARGUMENTS).get_environment() if len(environment) == 0: html += u' (empty)' html += u'<br/>' for variable in environment: html += u'{0}<br/>'.format(Qt.escape(variable)) html += u'<br/>' # stdio redirection if self.wizard().hasVisitedPage(Constants.PAGE_STDIO): html += u'<b>Stdio Redirection</b><br/>' stdin_redirection = self.get_field('stdin_redirection') stdout_redirection = self.get_field('stdout_redirection') stderr_redirection = self.get_field('stderr_redirection') if stdin_redirection == Constants.STDIN_REDIRECTION_FILE: html += u'Standard Input: {0}<br/>'.format( self.get_field('stdin_file')) else: html += u'Standard Input: {0}<br/>'.format( Constants.get_stdin_redirection_display_name( stdin_redirection)) if stdout_redirection == Constants.STDOUT_REDIRECTION_FILE: html += u'Standard Output: {0}<br/>'.format( self.get_field('stdout_file')) else: html += u'Standard Output: {0}<br/>'.format( Constants.get_stdout_redirection_display_name( stdout_redirection)) if stderr_redirection == Constants.STDERR_REDIRECTION_FILE: html += u'Standard Error: {0}<br/>'.format( self.get_field('stderr_file')) else: html += u'Standard Error: {0}<br/>'.format( Constants.get_stderr_redirection_display_name( stderr_redirection)) html += u'<br/>' # schedule if self.wizard().hasVisitedPage(Constants.PAGE_SCHEDULE): html += u'<b>Schedule</b><br/>' start_mode = self.get_field('start_mode') if start_mode == Constants.START_MODE_ONCE: html += u'Mode: Once After Upload<br/>' else: html += u'Mode: {0}<br/>'.format( Constants.get_start_mode_display_name(start_mode)) if start_mode != Constants.START_MODE_NEVER and start_mode != Constants.START_MODE_ONCE: if self.get_field('continue_after_error'): html += u'Continue After Error: Enabled<br/>' else: html += u'Continue After Error: Disabled<br/>' if start_mode == Constants.START_MODE_INTERVAL: html += u'Interval: {0} seconds<br/>'.format( self.get_field('start_interval')) elif start_mode == Constants.START_MODE_CRON: html += u'Fields: {0}<br/>'.format( self.get_field('start_fields')) self.text_summary.setHtml(html) self.update_ui_state()
def cb_program_logs_list(result): okay, message = check_script_result(result, decode_stderr=True) if not okay: self.label_error.setText('<b>Error:</b> ' + Qt.escape(message)) self.label_error.setVisible(True) self.refresh_logs_done() return try: # FIXME: do decompress in an async_call program_logs_list = json.loads(zlib.decompress(buffer(result.stdout)).decode('utf-8')) except: program_logs_list = None if program_logs_list == None or not isinstance(program_logs_list, dict): self.label_error.setText('<b>Error:</b> Received invalid data') self.label_error.setVisible(True) self.refresh_logs_done() return self.label_error.setVisible(False) def create_file_size_item(size): item = QStandardItem(get_file_display_size(size)) item.setData(size, USER_ROLE_SIZE) return item def update_file_size_item(item, additional_size): current_size = item.data(USER_ROLE_SIZE) new_size = current_size + additional_size item.setText(get_file_display_size(new_size)) item.setData(new_size, USER_ROLE_SIZE) continuous_row = None date_rows = {} time_rows = {} for file_name, file_size in program_logs_list.iteritems(): QApplication.processEvents() file_name_parts = file_name.split('_') if file_name_parts[0] == "continuous": if len(file_name_parts) != 2: continue if continuous_row == None: continuous_item = QStandardItem("Continuous") continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE) continuous_row = [continuous_item, create_file_size_item(0)] self.tree_logs_model.appendRow(continuous_row) log_item = QStandardItem(file_name_parts[1]) log_item.setData(self.file_icon, Qt.DecorationRole) log_item.setData(file_name, USER_ROLE_FILE_NAME) log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE) continuous_row[0].appendRow([log_item, create_file_size_item(file_size)]) update_file_size_item(continuous_row[1], file_size) else: if len(file_name_parts) != 3: continue try: timestamp = int(file_name_parts[1].split('+')[0]) / 1000000 except ValueError: continue date = QDateTime.fromTime_t(timestamp).toString('yyyy-MM-dd') time = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss') date_time = date + 'T' + time if date in date_rows: date_row = date_rows[date] else: date_item = QStandardItem(date) date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE) date_row = [date_item, create_file_size_item(0)] date_rows[date] = date_row self.tree_logs_model.appendRow(date_row) if date_time in time_rows: time_row = time_rows[date_time] else: time_item = QStandardItem(time) time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE) time_row = [time_item, create_file_size_item(0)] time_rows[date_time] = time_row date_row[0].appendRow(time_row) log_item = QStandardItem(file_name_parts[2]) log_item.setData(self.file_icon, Qt.DecorationRole) log_item.setData(file_name, USER_ROLE_FILE_NAME) log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE) time_row[0].appendRow([log_item, create_file_size_item(file_size)]) update_file_size_item(time_row[1], file_size) update_file_size_item(date_row[1], file_size) self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder) self.refresh_logs_done()
def update(self, zoom_only=False): self.update_ticks() line_color = self.plot.color(OWPalette.Axis) text_color = self.plot.color(OWPalette.Text) if not self.graph_line or not self.scene(): return self.line_item.setLine(self.graph_line) self.line_item.setPen(line_color) if self.title: self.title_item.setHtml('<b>' + self.title + '</b>') self.title_item.setDefaultTextColor(text_color) if self.title_location == AxisMiddle: title_p = 0.5 elif self.title_location == AxisEnd: title_p = 0.95 else: title_p = 0.05 title_pos = self.graph_line.pointAt(title_p) v = self.graph_line.normalVector().unitVector() dense_text = False if hasattr(self, 'title_margin'): offset = self.title_margin elif self._ticks: if self.should_be_expanded(): offset = 55 dense_text = True else: offset = 35 else: offset = 10 if self.title_above: title_pos = title_pos + (v.p2() - v.p1()) * ( offset + QFontMetrics(self.title_item.font()).height()) else: title_pos = title_pos - (v.p2() - v.p1()) * offset ## TODO: Move it according to self.label_pos self.title_item.setVisible(self.show_title) self.title_item.setRotation(-self.graph_line.angle()) c = self.title_item.mapToParent( self.title_item.boundingRect().center()) tl = self.title_item.mapToParent( self.title_item.boundingRect().topLeft()) self.title_item.setPos(title_pos - c + tl) ## Arrows if not zoom_only: if self.start_arrow_item: self.scene().removeItem(self.start_arrow_item) self.start_arrow_item = None if self.end_arrow_item: self.scene().removeItem(self.end_arrow_item) self.end_arrow_item = None if self.arrows & AxisStart: if not zoom_only or not self.start_arrow_item: self.start_arrow_item = QGraphicsPathItem( self.arrow_path, self) self.start_arrow_item.setPos(self.graph_line.p1()) self.start_arrow_item.setRotation(-self.graph_line.angle() + 180) self.start_arrow_item.setBrush(line_color) self.start_arrow_item.setPen(line_color) if self.arrows & AxisEnd: if not zoom_only or not self.end_arrow_item: self.end_arrow_item = QGraphicsPathItem(self.arrow_path, self) self.end_arrow_item.setPos(self.graph_line.p2()) self.end_arrow_item.setRotation(-self.graph_line.angle()) self.end_arrow_item.setBrush(line_color) self.end_arrow_item.setPen(line_color) ## Labels n = len(self._ticks) resize_plot_item_list(self.label_items, n, QGraphicsTextItem, self) resize_plot_item_list(self.label_bg_items, n, QGraphicsRectItem, self) resize_plot_item_list(self.tick_items, n, QGraphicsLineItem, self) test_rect = QRectF(self.graph_line.p1(), self.graph_line.p2()).normalized() test_rect.adjust(-1, -1, 1, 1) n_v = self.graph_line.normalVector().unitVector() if self.title_above: n_p = n_v.p2() - n_v.p1() else: n_p = n_v.p1() - n_v.p2() l_v = self.graph_line.unitVector() l_p = l_v.p2() - l_v.p1() for i in range(n): pos, text, size, step = self._ticks[i] hs = 0.5 * step tick_pos = self.map_to_graph(pos) if not test_rect.contains(tick_pos): self.tick_items[i].setVisible(False) self.label_items[i].setVisible(False) continue item = self.label_items[i] item.setVisible(True) if not zoom_only: if self.id in XAxes or getattr(self, 'is_horizontal', False): item.setHtml('<center>' + Qt.escape(text.strip()) + '</center>') else: item.setHtml(Qt.escape(text.strip())) item.setTextWidth(-1) text_angle = 0 if dense_text: w = min(item.boundingRect().width(), self.max_text_width) item.setTextWidth(w) if self.title_above: label_pos = tick_pos + n_p * ( w + self.text_margin ) + l_p * item.boundingRect().height() / 2 else: label_pos = tick_pos + n_p * self.text_margin + l_p * item.boundingRect( ).height() / 2 text_angle = -90 if self.title_above else 90 else: w = min( item.boundingRect().width(), QLineF(self.map_to_graph(pos - hs), self.map_to_graph(pos + hs)).length()) label_pos = tick_pos + n_p * self.text_margin - l_p * w / 2 item.setTextWidth(w) if not self.always_horizontal_text: if self.title_above: item.setRotation(-self.graph_line.angle() - text_angle) else: item.setRotation(self.graph_line.angle() - text_angle) item.setPos(label_pos) item.setDefaultTextColor(text_color) self.label_bg_items[i].setRect(item.boundingRect()) self.label_bg_items[i].setPen(QPen(Qt.NoPen)) self.label_bg_items[i].setBrush(self.plot.color(OWPalette.Canvas)) item = self.tick_items[i] item.setVisible(True) tick_line = QLineF(v) tick_line.translate(-tick_line.p1()) tick_line.setLength(size) if self.title_above: tick_line.setAngle(tick_line.angle() + 180) item.setLine(tick_line) item.setPen(line_color) item.setPos(self.map_to_graph(pos))
def initializePage(self): self.set_formatted_sub_title(u'The complete configuration of the {language} program [{name}].') language = self.get_field('language') language_display_name = Constants.language_display_names[language] language_api_name = Constants.language_api_names[language] # general information html = u'<b>General Information</b><br/>' html += u'Name: {0}<br/>'.format(Qt.escape(self.get_field('name'))) html += u'Identifier: {0}<br/>'.format(Qt.escape(self.get_field('identifier'))) html += u'Language: {0}<br/>'.format(Qt.escape(language_display_name)) html += u'Description: {0}<br/>'.format(Qt.escape(self.get_field('description'))) html += u'<br/>' # files html += u'<b>Files</b>' items = self.wizard().page(Constants.PAGE_FILES).get_items() if len(items) == 0: html += u' (none)' html += u'<br/>' for item in items: html += u'{0}<br/>'.format(Qt.escape(item)) html += u'<br/>' # language specific configuration html += u'<b>{0} Configuration</b><br/>'.format(Qt.escape(language_display_name)) html += self.wizard().page(Constants.get_language_page(language_api_name)).get_html_summary() html += u'<br/>' if self.wizard().hasVisitedPage(Constants.PAGE_ARGUMENTS): # arguments html += u'<b>Arguments</b>' arguments = self.wizard().page(Constants.PAGE_ARGUMENTS).get_arguments() if len(arguments) == 0: html += u' (none)' html += u'<br/>' for argument in arguments: html += u'{0}<br/>'.format(Qt.escape(argument)) html += u'<br/>' # environment html += u'<b>Environment</b>' environment = self.wizard().page(Constants.PAGE_ARGUMENTS).get_environment() if len(environment) == 0: html += u' (empty)' html += u'<br/>' for variable in environment: html += u'{0}<br/>'.format(Qt.escape(variable)) html += u'<br/>' # stdio redirection if self.wizard().hasVisitedPage(Constants.PAGE_STDIO): html += u'<b>Stdio Redirection</b><br/>' stdin_redirection = self.get_field('stdin_redirection') stdout_redirection = self.get_field('stdout_redirection') stderr_redirection = self.get_field('stderr_redirection') if stdin_redirection == Constants.STDIN_REDIRECTION_FILE: html += u'Standard Input: {0}<br/>'.format(self.get_field('stdin_file')) else: html += u'Standard Input: {0}<br/>'.format(Constants.get_stdin_redirection_display_name(stdin_redirection)) if stdout_redirection == Constants.STDOUT_REDIRECTION_FILE: html += u'Standard Output: {0}<br/>'.format(self.get_field('stdout_file')) else: html += u'Standard Output: {0}<br/>'.format(Constants.get_stdout_redirection_display_name(stdout_redirection)) if stderr_redirection == Constants.STDERR_REDIRECTION_FILE: html += u'Standard Error: {0}<br/>'.format(self.get_field('stderr_file')) else: html += u'Standard Error: {0}<br/>'.format(Constants.get_stderr_redirection_display_name(stderr_redirection)) html += u'<br/>' # schedule if self.wizard().hasVisitedPage(Constants.PAGE_SCHEDULE): html += u'<b>Schedule</b><br/>' start_mode = self.get_field('start_mode') if start_mode == Constants.START_MODE_ONCE: html += u'Mode: Once After Upload<br/>' else: html += u'Mode: {0}<br/>'.format(Constants.get_start_mode_display_name(start_mode)) if start_mode != Constants.START_MODE_NEVER and start_mode != Constants.START_MODE_ONCE: if self.get_field('continue_after_error'): html += u'Continue After Error: Enabled<br/>' else: html += u'Continue After Error: Disabled<br/>' if start_mode == Constants.START_MODE_INTERVAL: html += u'Interval: {0} seconds<br/>'.format(self.get_field('start_interval')) elif start_mode == Constants.START_MODE_CRON: html += u'Fields: {0}<br/>'.format(self.get_field('start_fields')) self.text_summary.setHtml(html) self.update_ui_state()
def cb_program_logs_list(result): okay, message = check_script_result(result, decode_stderr=True) if not okay: self.label_error.setText('<b>Error:</b> ' + Qt.escape(message)) self.label_error.setVisible(True) self.refresh_logs_done() return try: # FIXME: do decompress in an async_call program_logs_list = json.loads( zlib.decompress(buffer(result.stdout)).decode('utf-8')) except: program_logs_list = None if program_logs_list == None or not isinstance( program_logs_list, dict): self.label_error.setText('<b>Error:</b> Received invalid data') self.label_error.setVisible(True) self.refresh_logs_done() return self.label_error.setVisible(False) def create_file_size_item(size): item = QStandardItem(get_file_display_size(size)) item.setData(size, USER_ROLE_SIZE) return item def update_file_size_item(item, additional_size): current_size = item.data(USER_ROLE_SIZE) new_size = current_size + additional_size item.setText(get_file_display_size(new_size)) item.setData(new_size, USER_ROLE_SIZE) continuous_row = None date_rows = {} time_rows = {} for file_name, file_size in program_logs_list.iteritems(): QApplication.processEvents() file_name_parts = file_name.split('_') if file_name_parts[0] == "continuous": if len(file_name_parts) != 2: continue if continuous_row == None: continuous_item = QStandardItem("Continuous") continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE) continuous_row = [ continuous_item, create_file_size_item(0) ] self.tree_logs_model.appendRow(continuous_row) log_item = QStandardItem(file_name_parts[1]) log_item.setData(self.file_icon, Qt.DecorationRole) log_item.setData(file_name, USER_ROLE_FILE_NAME) log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE) continuous_row[0].appendRow( [log_item, create_file_size_item(file_size)]) update_file_size_item(continuous_row[1], file_size) else: if len(file_name_parts) != 3: continue try: timestamp = int( file_name_parts[1].split('+')[0]) / 1000000 except ValueError: continue date = QDateTime.fromTime_t(timestamp).toString( 'yyyy-MM-dd') time = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss') date_time = date + 'T' + time if date in date_rows: date_row = date_rows[date] else: date_item = QStandardItem(date) date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE) date_row = [date_item, create_file_size_item(0)] date_rows[date] = date_row self.tree_logs_model.appendRow(date_row) if date_time in time_rows: time_row = time_rows[date_time] else: time_item = QStandardItem(time) time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE) time_row = [time_item, create_file_size_item(0)] time_rows[date_time] = time_row date_row[0].appendRow(time_row) log_item = QStandardItem(file_name_parts[2]) log_item.setData(self.file_icon, Qt.DecorationRole) log_item.setData(file_name, USER_ROLE_FILE_NAME) log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE) time_row[0].appendRow( [log_item, create_file_size_item(file_size)]) update_file_size_item(time_row[1], file_size) update_file_size_item(date_row[1], file_size) self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder) self.refresh_logs_done()
def start_conflict_resolution(self): self.log(u'...target file {0} already exists'.format(self.upload.target)) if self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_REPLACE: self.log(u'...replacing {0}'.format(self.upload.target)) self.continue_upload_file(True) elif self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_SKIP: self.log('...skipped') self.upload_next_file() else: self.progress_file.setVisible(False) try: target_file = REDFile(self.wizard().session).open(self.target_path, REDFile.FLAG_READ_ONLY, 0, 1000, 1000) # FIXME: async_call self.label_existing_stats.setText('{0}, last modified on {1}' .format(get_file_display_size(target_file.length), timestamp_to_date_at_time(int(target_file.modification_time)))) target_file.release() except (Error, REDError) as e: self.label_existing_stats.setText(u'<b>Error</b>: Could not open target file: {0}', Qt.escape(unicode(e))) self.label_new_stats.setText('{0}, last modified on {1}' .format(self.chunked_uploader.source_display_size, timestamp_to_date_at_time(int(self.chunked_uploader.source_stat.st_mtime)))) self.label_replace_help.setText(self.replace_help_template.replace('<FILE>', Qt.escape(self.upload.target))) self.check_rename_new_file.setChecked(self.auto_conflict_resolution == ProgramPageUpload.CONFLICT_RESOLUTION_RENAME) self.edit_new_name.setText('') # force a new-name check self.edit_new_name.setText(posixpath.split(self.upload.target)[1]) self.conflict_resolution_in_progress = True self.update_ui_state()
def start_conflict_resolution(self): self.log(u'...target file {0} already exists'.format(self.target_path)) if self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_REPLACE: self.log(u'...replacing {0}'.format(self.download.target)) self.continue_download_file(True) elif self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_SKIP: self.log('...skipped') self.download_next_file() else: self.progress_file.setVisible(False) try: target_stat = os.stat(self.target_path) self.label_existing_stats.setText('{0}, last modified on {1}' .format(get_file_display_size(target_stat.st_size), timestamp_to_date_at_time(int(target_stat.st_mtime)))) except Exception as e: self.label_existing_stats.setText(u'<b>Error</b>: Could not get informarion for target file: {0}', Qt.escape(unicode(e))) self.label_new_stats.setText('{0}, last modified on {1}' .format(self.chunked_downloader.source_display_size, timestamp_to_date_at_time(int(self.chunked_downloader.source_file.modification_time)))) self.label_replace_help.setText(self.replace_help_template.replace('<FILE>', Qt.escape(self.download.target))) self.check_rename_new_file.setChecked(self.auto_conflict_resolution == ProgramPageDownload.CONFLICT_RESOLUTION_RENAME) self.edit_new_name.setText('') # force a new-name check self.edit_new_name.setText(os.path.split(self.download.target)[1]) self.conflict_resolution_in_progress = True self.update_ui_state()