def mark_all_as_read(self): msg = QMessageBox(self.app.window.ui) msg.setIcon(QMessageBox.Question) msg.setWindowTitle("Mark all as read ...") msg.setText("Are you sure you want all posts marked as read?") msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) if msg.exec_() == QMessageBox.Yes: self.app.window.update_messages_as_read() self.app.db.set_all_unread_status(False) self.update()
def show_err_dialog(s): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText(s) msg.setWindowTitle("Warning!") msg.setStandardButtons(QMessageBox.Ok) msg.exec_()
def run(self, path_to_ebook): from calibre.gui2 import is_ok_to_use_qt from PyQt4.Qt import QMessageBox PID = self.site_customization data_file = file(path_to_ebook, 'rb').read() ar = PID.split(',') for i in ar: try: unlocked_file = DrmStripper(data_file, i).getResult() except DrmException: # ignore the error pass else: of = self.temporary_file('.mobi') of.write(unlocked_file) of.close() return of.name if is_ok_to_use_qt(): d = QMessageBox( QMessageBox.Warning, "MobiDeDRM Plugin", "Couldn't decode: %s\n\nImporting encrypted version." % path_to_ebook) d.show() d.raise_() d.exec_() return path_to_ebook
def install(self): pref = self.app.preferences.ui ct = pref.configTable curi = int(pref.filtersComboBox_new.currentIndex()) filter = self._filters[self._keys[curi]] config, hash = {}, gen_hash() settings = self.filter_settings(filter.id, hash) for i in range(ct.rowCount()): config[unicode(ct.item(i,0).text())] = unicode(ct.item(i,1).text()) try: filter.install(settings, config) except Exception as e: msg = QMessageBox(pref) msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Installation Error ...") msg.setText("An Error occured during installation.") msg.setInformativeText("Could install filter '%s'." % filter.name) msg.setStandardButtons(QMessageBox.Ok) msg.setDetailedText(format_exc()) msg.exec_() return # success self.add_filter_instance(filter, hash) pref.filtersComboBox_new.currentIndexChanged.emit(curi) pref.filtertabWidget.setCurrentIndex(0)
def show_popup(set_text, detailed, window_title, message_type): mess = QMessageBox() mess.setText(set_text) if len(detailed) > 0: mess.setInformativeText("For more information click \"Show Details\"") mess.setDetailedText(detailed) mess.setIcon(message_type) mess.setWindowTitle(window_title) mess.setMinimumWidth(500) mess.exec_()
def on_timeout(self): self.systemTrayIcon.setToolTip("TImeout") self.reset_timer() msgBox = QMessageBox(QMessageBox.Information, "== Notification ==", "On timer!", QMessageBox.NoButton, None) screenrect = QDesktopWidget().screen().rect() msgBox.move(QPoint(screenrect.width() / 2 - msgBox.sizeHint().width() / 2, screenrect.height() / 2 - msgBox.sizeHint().height() / 2)) msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) msgBox.exec_()
def startDeleting(self): reply = QtGui.QMessageBox.warning( self, "Caution: Deleting Permanently", "You are about to PERMANENTLY remove accounts and ALL the saved data related to those accounts. Are you sure you want to continue?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: delDate = self.ui.delDate.date().toPyDate() UsrFuncs.cleanOutDeletedAccounts(delDate) alert = QMessageBox() alert.setWindowTitle("Complete") alert.setText("Clean up completed") alert.exec_() return
def sendBookData(self, author, title, genre, genre2, dateRead, grade, comments): if self.dialog.isHidden(): global sock try: sock.send('SEND_ROW_DATA "' + author + '", "' + title + '", "' + genre + '", "' + genre2 + '", ' + dateRead + ', ' + grade + ', "' + comments + '"\n') data = sock.recv(1024) if data == '200 OK': dialog = QMessageBox() dialog.setText("Data added successfully") dialog.exec_() except socket.timeout: dialog = QMessageBox() dialog.set dialog.setText("Connection timed out...") dialog.exec_() except: self.parent().setWindowTitle("Book Library (Disconnected)") dialog = QMessageBox() dialog.set dialog.setText("Connect to server to be able to send data.") dialog.exec_() else: dialog = QMessageBox() dialog.set dialog.setText("Connect to server to be able to send data.") dialog.exec_()
def displayDialog(message, detailedMessage=None, title=None, level=logging.CRITICAL, dialogWidth=150): ''' A generic function to display the dialog in a QMessageBox message: Primary message to be displayed detailedMessage: detail message that is shown after user clicks on the button level: Message level dialogWidth: width of the messageBox ''' width = dialogWidth mainWin = WorkbenchHelper.window msgBox = QMessageBox (parent=mainWin) if detailedMessage: detailedMessage = 'Application ' + " encountered following problem :" + detailedMessage if len(message) < width: message += ' ' * (width - len(message)) msgBox.setWindowTitle(__getTitleFromLevel(level)) msgBox.setIcon(__getIconFromLevel(level)) msgBox.setText(message) if detailedMessage: msgBox.setDetailedText(detailedMessage) ret = msgBox.exec_()
def _save_dialog(self, parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) return d.exec_()
def LoadAction(self): if not self.MainProgramm.DataSaved : msgbox = QMessageBox(QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No| QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return filename = QFileDialog.getOpenFileName(self,"Messung laden") if not filename == '': self.MainProgramm.LoadFile(filename) return
def LoadAction(self): if not self.MainProgramm.DataSaved: msgbox = QMessageBox( QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No | QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return filename = QFileDialog.getOpenFileName(self, "Messung laden") if not filename == '': self.MainProgramm.LoadFile(filename) return
def handleInfo(self): msg = QMessageBox() #msg.setFixedSize(500, 300) #msg.setGeometry(100,100, 400, 200) msg.setIcon(QMessageBox.Information) msg.setText("Axel Schneider") msg.setInformativeText(unicode(u"©2016")) msg.setWindowTitle("Cut Video") msg.setDetailedText("Python Qt4") msg.setStandardButtons(QMessageBox.Ok) retval = msg.exec_() print "value of pressed message box button:", retval
def run(self, path_to_ebook): from calibre.gui2 import is_ok_to_use_qt from PyQt4.Qt import QMessageBox PID = self.site_customization data_file = file(path_to_ebook, 'rb').read() ar = PID.split(',') for i in ar: try: unlocked_file = DrmStripper(data_file, i).getResult() except DrmException: # ignore the error pass else: of = self.temporary_file('.mobi') of.write(unlocked_file) of.close() return of.name if is_ok_to_use_qt(): d = QMessageBox(QMessageBox.Warning, "MobiDeDRM Plugin", "Couldn't decode: %s\n\nImporting encrypted version." % path_to_ebook) d.show() d.raise_() d.exec_() return path_to_ebook
def RecButtonToggled(self): if self.rec.text() == 'Aufnehmen': if not self.MainProgramm.DataSaved : msgbox = QMessageBox(QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No| QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return self.MainProgramm.StartRecording() self.Panel.setRecFrame(True) self.rec.setText('Stop') else: self.MainProgramm.StopRecording() self.rec.setText("Aufnehmen") self.Panel.setRecFrame(False) self.playback_radio.setEnabled(True)
def RecButtonToggled(self): if self.rec.text() == 'Aufnehmen': if not self.MainProgramm.DataSaved: msgbox = QMessageBox( QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No | QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return self.MainProgramm.StartRecording() self.Panel.setRecFrame(True) self.rec.setText('Stop') else: self.MainProgramm.StopRecording() self.rec.setText("Aufnehmen") self.Panel.setRecFrame(False) self.playback_radio.setEnabled(True)
def atom_limit_exceeded_and_confirmed(parent, natoms, limit = 200): """ Displays a warning message if 'natoms' exceeds 'limit'. Returns False if the number of atoms does not exceed the limit or if the user confirms that the jigs should still be created even though the limit was exceeded. If parent is 0, the message box becomes an application-global modal dialog box. If parent is a widget, the message box becomes modal relative to parent. """ if natoms < limit: return False # Atom limit not exceeded. wmsg = "Warning: Creating a jig with " + str(natoms) \ + " atoms may degrade performance.\nDo you still want to add the jig?" dialog = QMessageBox("Warning", wmsg, QMessageBox.Warning, QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton, parent) # We want to add a "Do not show this message again." checkbox to the dialog # like this: # checkbox = QCheckBox("Do not show this message again.", dialog) # The line of code above works, but places the checkbox in the upperleft # corner of the dialog, obscuring important text. I'll fix this later. # Mark 051122. ret = dialog.exec_() if ret != QMessageBox.Yes: return True # Print warning msg in history widget whenever the user adds new jigs with # more than 'limit' atoms. wmsg = "Warning: " + str(natoms) + " atoms selected. A jig with more " \ "than " + str(limit) + " atoms may degrade performance." env.history.message(orangemsg(wmsg)) return False # from atom_limit_exceeded_and_confirmed
def atom_limit_exceeded_and_confirmed(parent, natoms, limit = 200): """ Displays a warning message if 'natoms' exceeds 'limit'. Returns False if the number of atoms does not exceed the limit or if the user confirms that the jigs should still be created even though the limit was exceeded. If parent is 0, the message box becomes an application-global modal dialog box. If parent is a widget, the message box becomes modal relative to parent. """ if natoms < limit: return False # Atom limit not exceeded. wmsg = "Warning: Creating a jig with " + str(natoms) \ + " atoms may degrade performance.\nDo you still want to add the jig?" dialog = QMessageBox("Warning", wmsg, QMessageBox.Warning, QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton, parent) # We want to add a "Do not show this message again." checkbox to the dialog # like this: # checkbox = QCheckBox("Do not show this message again.", dialog) # The line of code above works, but places the checkbox in the upperleft # corner of the dialog, obscuring important text. I'll fix this later. # Mark 051122. ret = dialog.exec_() if ret != QMessageBox.Yes: return True # Print warning msg in history widget whenever the user adds new jigs with # more than 'limit' atoms. wmsg = "Warning: " + str(natoms) + " atoms selected. A jig with more " \ "than " + str(limit) + " atoms may degrade performance." env.history.message(orangemsg(wmsg)) return False # from atom_limit_exceeded_and_confirmed
def checkSaveState(self): close = False if self._unsavedChanges: msgBox = QMessageBox() msgBox.setText("A list or setting has been changed.") msgBox.setInformativeText("Do you want to save your changes?") msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Save) ret = msgBox.exec_() if ret == QMessageBox.Save: self.saveState() close = True elif ret == QMessageBox.Discard: close = True elif ret == QMessageBox.Cancel: close = False else: close = False else: close = True return close
def _save_dialog(self, parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) return d.exec_()
class OpenCellId(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) #Exit Actions self.actionExit.triggered.connect(QtGui.qApp.quit) #Select CSV File for import self.actionImport.triggered.connect(self.importFileSelect) self.select_csv_button.clicked.connect(self.importFileSelect) #Select SQLite file for export self.actionExport.triggered.connect(self.exportFileSelect) self.select_sql_export_button.clicked.connect(self.exportFileSelect) #Initiate import-export action (CSV2SQLite) self.import_button.clicked.connect(self.exportSQLite) #Select SQLite input file for filtering self.select_sql_source_button.clicked.connect(self.filterSelectFile) #Exporting filtered files self.export_button.clicked.connect(self.filterOutput) #search Nominatim for Bounding Box self.bb_nominatim_button.clicked.connect(self.bbNominatim) self.show_bounding_box.clicked.connect(self.showBoundingBox) def showBoundingBox(self): if (self.lat1_input.text() != "" and self.lat2_input.text() != ""\ and self.long1_input.text() != "" and self.long2_input.text() != ""): kml = simplekml.Kml() b_box = kml.newgroundoverlay( name=smart_unicode(self.bounding_box_entry.text())) b_box.color = '371400FF' #this is transparent red b_box.latlonbox.north = float(self.lat2_input.text()) b_box.latlonbox.south = float(self.lat1_input.text()) b_box.latlonbox.east = float(self.long2_input.text()) b_box.latlonbox.west = float(self.long1_input.text()) #save kml file with name based on the full location name kml_filename = smart_unicode( self.bounding_box_entry.text()).replace(', ', '-').replace( ' ', '_') + '_bounding_box.kml' kml.save(kml_filename) Popen( '"C:/Program Files (x86)/Google/Google Earth Pro/client/googleearth.exe" "{}"' .format(kml_filename), stdin=None, stdout=None, stderr=None, close_fds=True, shell=True) else: self.popupWindow( "No Coordinates For Box", "You are missing one or more coordinates for your bounding box. Try searching a location to populate lat/long values." ) def importFileSelect(self): import_name = QtGui.QFileDialog.getOpenFileName() if import_name != "": self.file_import_box.setText(import_name) def exportFileSelect(self): export_name = QtGui.QFileDialog.getSaveFileName() if export_name != "": self.file_export_box.setText(export_name) def exportSQLite(self): db_filename = str(self.file_export_box.text().toUtf8()) if os.path.isfile(db_filename): os.remove(db_filename) csv_filename = str(self.file_import_box.text().toUtf8()) con = sqlite3.Connection(db_filename) cur = con.cursor() cur.execute( 'CREATE TABLE "towers" ("radio" varchar(12), "mcc" varchar(12), "net" varchar(12),"area" varchar(12),"cell" varchar(12),"unit" varchar(12),"lon" varchar(12),"lat" varchar(12),"range" varchar(12),"samples" varchar(12),"changeable" varchar(12),"created" varchar(12),"updated" varchar(12),"averageSignal" varchar(12));' ) input_file = open(csv_filename) check = input_file.readline() if check.split(',')[0] != "radio": input_file.seek(0) csv_reader = csv.reader(input_file, delimiter=',') cur.executemany( 'INSERT INTO towers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', csv_reader) cur.close() con.commit() con.close() input_file.close() #just let the user know the file was created successfully self.popupWindow('Successful Conversion', 'File successfully converted to SQLite ') def popupWindow(self, title, message): self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Information) self.msg.setWindowTitle(title) self.msg.setText(message) self.msg.setStandardButtons(QMessageBox.Ok) self.msg.exec_() def filterSelectFile(self): filter_input_file = str(QtGui.QFileDialog.getOpenFileName()) if filter_input_file != "": self.source_SQLite_box.setText(filter_input_file) def filterOutput(self): output_base = str(QtGui.QFileDialog.getSaveFileName()) count = 0 CREATE_SQLITE = False CREATE_KMZ = False CREATE_CSV = False if self.export_sqlite_check.isChecked(): CREATE_SQLITE = True if os.path.isfile('output_base' + '.db'): self.popupWindow( "SQLite Database already exists", "This file exist already. This will append to the current DB, adding the table if necessary." ) output_con = sqlite3.Connection(output_base + '.db') output_cur = output_con.cursor() output_cur.execute( 'CREATE TABLE IF NOT EXISTS "towers" ("radio" varchar(12), "mcc" varchar(12), "net" varchar(12),"area" varchar(12),"cell" varchar(12),"unit" varchar(12),"lon" varchar(12),"lat" varchar(12),"range" varchar(12),"samples" varchar(12),"changeable" varchar(12),"created" varchar(12),"updated" varchar(12),"averageSignal" varchar(12));' ) if self.export_kmz_check.isChecked(): CREATE_KMZ = True if os.path.isfile(output_base + '.kmz'): self.popupWindow('Already Existing File', 'The KMZ file already exists. Will replace.') os.remove(output_base + '.kmz') kml = simplekml.Kml() if self.export_csv_check.isChecked(): CREATE_CSV = True csv_file = open(output_base + '.csv', 'wb') writer = csv.writer(csv_file, delimiter=',') writer.writerow(('radio', 'mcc', 'net', 'area', 'cell', 'unit', 'lon', 'lat', 'range', 'samples', 'changeable', 'created', 'updated', 'averageSignal')) #read lat/long values and get them in the proper order try: lat1 = float(self.lat1_input.text().toUtf8()) lat2 = float(self.lat2_input.text().toUtf8()) long1 = float(self.long1_input.text().toUtf8()) long2 = float(self.long2_input.text().toUtf8()) if max(lat1, lat2) == max(abs(lat1), abs(lat2)): pass else: lat1, lat2 = lat2, lat1 if max(long1, long2) == max(abs(long1), abs(long2)): pass else: long1, long2 = long2, long1 if lat1 != '' and lat2 != '' and long1 != '' and long2 != '': loc_string = ' AND lat BETWEEN {a} AND {b} AND lon BETWEEN {c} AND {d}'.format( a=lat1, b=lat2, c=long1, d=long2) else: loc_string = '' except ValueError: lat1, lat2, long1, long2 = '', '', '', '' loc_string = '' if self.MCC_input.text().toUtf8() == "": mob_cc = ' LIKE "%"' else: mob_cc = '={a}'.format(a=self.MCC_input.text().toUtf8()) if self.MNC_input.text().toUtf8() == "": mnc = ' LIKE "%"' else: mnc = '={a}'.format(a=self.MNC_input.text().toUtf8()) if self.LAC_input.text().toUtf8() == "": lac = ' LIKE "%"' else: lac = '={a}'.format(a=self.LAC_input.text().toUtf8()) if self.CID_input.text().toUtf8() == "": cid = ' LIKE "%"' else: cid = '={a}'.format(a=self.CID_input.text().toUtf8()) input_con = sqlite3.Connection( str(self.source_SQLite_box.text().toUtf8())) input_cur = input_con.cursor() query = 'SELECT * FROM towers WHERE mcc{a} AND net{b} AND area{c} AND cell{d}{e};'.format( a=mob_cc, b=mnc, c=lac, d=cid, e=loc_string) input_cur.execute(query) def ResultIter(cursor, array_size=5000): while True: results = cursor.fetchmany(array_size) if not results: break for result in results: yield result for result in ResultIter(input_cur): if CREATE_SQLITE: output_cur.executemany( 'INSERT INTO towers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', (result, )) if CREATE_KMZ: desc = '{a}:{b}:{c}:{d}'.format(a=result[1], b=result[2], c=result[3], d=result[4]) nm = desc #'CID: {a}'.format(a=result[4]) pnt = kml.newpoint(name = nm, description = desc, coords = \ [(float(result[6]), float(result[7]))]) pnt.style.iconstyle.icon.href = 'greentower.png' if CREATE_CSV: writer.writerow(result) if CREATE_SQLITE: count += 1 output_con.commit() output_con.close() if CREATE_CSV: count += 1 csv_file.close() if CREATE_KMZ: count += 1 kml.save('doc.kml') zf = zipfile.ZipFile(output_base + '.kmz', 'a') zf.write('doc.kml') zf.write('greentower.png') os.remove('doc.kml') zf.close() if os.path.getsize(output_base + '.kmz') > 10000000: self.popupWindow( 'Enormous KMZ file', 'Your KMZ file is enormous. Google Earth may have problems opening it in a reasonable fashion.' ) if self.open_earth_button.isChecked(): Popen( '"C:\Program Files (x86)\Google\Google Earth Pro\client\googleearth.exe" "{}"' .format(output_base + '.kmz'), stdin=None, stdout=None, stderr=None, close_fds=True) if count == 0: self.popupWindow('Unsuccessful', 'No files were exported') else: self.popupWindow('Successful File Exports', str(count) + ' files were exported. ') input_con.close() def bbNominatim(self): geolocator = Nominatim() location_name = self.bounding_box_entry.text().toUtf8() location = geolocator.geocode(location_name, language='en') try: geo_box = location.raw[u'boundingbox'] self.lat1_input.setText(geo_box[0].encode('utf-8')) self.lat2_input.setText(geo_box[1].encode('utf-8')) self.long1_input.setText(geo_box[2].encode('utf-8')) self.long2_input.setText(geo_box[3].encode('utf-8')) self.bounding_box_entry.setText( smart_unicode(location.raw[u'display_name'])) except AttributeError: self.bounding_box_entry.setText( '''No location found. Maybe it's you.''') self.popupWindow( 'Location Not Found', '''I can't find that location. Maybe you can try going back in time and learning how to spell.''' )
class DecoderMain(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) #just sets the theme of the UI, in this case cleanlooks QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('cleanlooks')) #menu options self.actionExit.triggered.connect(self.closeApplication) self.actionSave.triggered.connect(self.saveOutput) #buttons #all other button actions are handled via the UI directly self.execute_btn.clicked.connect(self.decoderSelect) self.save_btn.clicked.connect(self.saveOutput) #turn on statusBar below self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.updateStatus() #initially set the hash and length options to disabled, unless #if the proper function is chosen, then enable the options #there are two things here, both of which serve fine #one hides the entire group, the other disables it self.hash_options_group.hide() #self.hash_options_group.setEnabled(False) #this just deactivates, but doesn't hide self.length_group.hide() #if the user changes the combo box, run the function to #update the show/hide or enable/disabled status of the #hash options and/or length options self.func_select.currentIndexChanged.connect(self.enableOptions) #close the application, however that may happen def closeApplication(self): choice = QtGui.QMessageBox.question(self, 'Exit', 'Exit the Super Decoder?',\ QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if choice == QtGui.QMessageBox.Yes: exit() else: return def updateStatus(self): message = 'Input Length: {} Output Length: {}'.\ format(len(self.input_line.text()),len(self.output_box.toPlainText())) self.statusBar.showMessage(message) #generic popup window for messages and good times def popupWindow(self, title, message): self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Information) self.msg.setWindowTitle(title) self.msg.setText(message) self.msg.setStandardButtons(QMessageBox.Ok) self.msg.exec_() #save whatever output data there is to a text file #if there is none, it won't save def saveOutput(self): output_text = unicode(self.output_box.toPlainText()) if len(output_text) != 0: output_text = 'Input Text:\n{}\n\nOutput Text:\n{}'.format( self.input_line.text(), output_text) export_name = QtGui.QFileDialog.getSaveFileName( filter=self.tr("Text file (*.txt)")) if export_name != "": f = open(export_name, 'wb') f.write(output_text) f.close() self.popupWindow( 'File Saved', 'Data has been saved to {}. '.format(export_name)) else: self.popupWindow('No Data for Export', 'Sorry, there is no data to save.') #enable or disable the options groups for different functions def enableOptions(self): #hide or show hash options if self.func_select.currentText() == 'Hash Text': self.hash_options_group.show() else: self.hash_options_group.hide() #hide or show length options, depending on function #could do this as one big if statement, but... if self.func_select.currentText() == 'Hex to ASCII': self.length_group.show() self.pad_radio.hide() elif self.func_select.currentText() == 'Base64 Decode': self.length_group.show() self.pad_radio.show() elif self.func_select.currentText() == 'Reverse Nibble': self.length_group.show() self.pad_radio.show() elif self.func_select.currentText() == 'Switch Endianness': self.length_group.show() self.pad_radio.show() elif self.func_select.currentText() == 'Hex to Decimal IP': self.length_group.hide() self.pad_radio.hide() else: self.length_group.hide() #checks the state of the combo box "func_select" #to determine which function to run def decoderSelect(self): self.updateStatus() if self.func_select.currentText() == 'Decimal to Hex': self.decimaltoHex() elif self.func_select.currentText() == 'Decimal to Binary': self.decimaltoBinary() elif self.func_select.currentText() == 'ASCII to Hex': self.asciitoHex() elif self.func_select.currentText() == 'Hex to ASCII': self.hextoAscii() elif self.func_select.currentText() == 'Base64 Encode': self.base64Encode() elif self.func_select.currentText() == 'Base64 Decode': self.base64Decode() elif self.func_select.currentText() == 'Reverse Nibble': self.reverseNibble() elif self.func_select.currentText() == 'Switch Endianness': self.switchEndian() elif self.func_select.currentText() == 'ROT13': self.rot13() elif self.func_select.currentText() == 'Hash Text': self.hashText() elif self.func_select.currentText() == 'Find OUI Vendor': self.findOUIVendor() elif self.func_select.currentText() == 'Hex to Decimal IP': self.hexToDecIP() #convert decimal to hex, pad with leading zero if necessary def decimaltoHex(self): try: input_num = int(self.input_line.text()) except ValueError: self.popupWindow('Invalid Input', 'Sorry, input is not proper decimal. ') self.output_box.clear() return hex_num = hex(input_num)[2:] hex_num = '0' * (len(hex_num) % 2) + hex_num self.output_box.setText(hex_num.rstrip('L')) self.updateStatus() #convert decimal to binary, pad zeroes depending on bit length def decimaltoBinary(self): try: input_num = int(self.input_line.text()) except ValueError: self.popupWindow('Invalid Input', 'Sorry, input is not proper decimal. ') self.output_box.clear() return bits = input_num.bit_length() zero_pad = '0' * (4 - (bits % 4)) bin_num = bin(input_num)[2:] bin_num = zero_pad + bin_num self.output_box.setText(bin_num) self.updateStatus() #encode base64 def base64Encode(self): input_text = unicode(self.input_line.text()) output_text = b64encode(input_text) self.output_box.setText(output_text) self.updateStatus() #decode base64, check length, etc. def base64Decode(self): input_text = unicode(self.input_line.text()) #check if the input has a length that's a multiple of 4 #pad if necessary if len(input_text) % 4 != 0: pad_length = len(input_text) % 4 input_text += '=' * pad_length self.input_line.setText(input_text) try: output_text = b64decode(input_text) except TypeError: self.output_box.clear() self.popupWindow('Invalid Input', 'Sorry, input is not proper base64. ') return self.output_box.setText(output_text) self.updateStatus() #reverse nibble stuff, check length def reverseNibble(self): input_text = unicode(self.input_line.text()) #check to see if input length is multiple of 2 #depending on the radio button selected, it #will truncate, pad, or refuse to decode if len(input_text) % 2: if self.truncate_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Truncating. ') elif self.pad_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Padding with "F". ') input_text += "F" elif self.refuse_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Failure to decode. ') self.output_box.clear() return output_text = ''.join([y + x for x, y in zip(*[iter(input_text)] * 2)]) self.output_box.setText(output_text) self.updateStatus() #switch from LE to BE and vice versa def switchEndian(self): input_text = unicode(self.input_line.text()) if len(input_text) == 0: return if len(input_text) % 2: if self.truncate_radio.isChecked(): input_text = input_text[:-1] self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Truncating. ') elif self.pad_radio.isChecked(): input_text += 'F' self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Padding with "F". ') elif self.refuse_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Failure to decode. ') self.output_box.clear() return self.output_box.setText("".join( reversed( [input_text[i:i + 2] for i in range(0, len(input_text), 2)]))) self.updateStatus() #get all the hashes of the input text def hashText(self): input_text = unicode(self.input_line.text()) output_text = '' if self.crc32_check.isChecked(): crc32_hash = hex((crc32(input_text) + (1 << 32)) % (1 << 32))[2:-1].upper().zfill(8) output_text += 'CRC32 Hash: {}\n'.format(crc32_hash) if self.adler_check.isChecked(): adler32_hash = hex(adler32(input_text))[2:].upper().zfill(8) output_text += 'Adler32 Hash: {}\n'.format(adler32_hash) if self.md5_check.isChecked(): md5_hash = md5(input_text).hexdigest() output_text += 'MD5 Hash: {}\n'.format(md5_hash) if self.sha1_check.isChecked(): sha1_hash = sha1(input_text).hexdigest() output_text += 'SHA1 Hash: {}\n'.format(sha1_hash) if self.sha256_check.isChecked(): sha256_hash = sha256(input_text).hexdigest() output_text += 'SHA256 Hash: {}\n'.format(sha256_hash) if self.b64_256_check.isChecked(): sha256_64_hash = b64encode(sha256(input_text).digest()) output_text += 'Base64 SHA256 Hash: {}\n'.format(sha256_64_hash) self.output_box.setText(output_text.rstrip()) self.updateStatus() #get a vendor for a given mac address or OUI using sqlite db def findOUIVendor(self): #remove colons, dashes, uppercase and only take first 3 bytes (6 characters when it's text) input_text = unicode(self.input_line.text()).replace(':', '').replace( '-', '').upper()[0:6] #just gonna see if it's hex or not by trying to int it try: int(input_text, 16) except ValueError: self.popupWindow('Invalid Input', 'Sorry, input is not a proper MAC or OUI. ') self.output_box.clear() return result = mutator(input_text) output_text = 'Original OUI: {}\nMatching OUI: {}\nVendor: {}\nMutation: {}\n'.\ format(result[0], result[1], result[2], result[3]) self.output_box.setText(output_text) self.updateStatus() #convert ascii to hex def asciitoHex(self): input_text = self.input_line.text().encode('utf8') output_text = hexlify(input_text).upper() self.output_box.setText(output_text) self.updateStatus() #convert hex to ascii, check for validity def hextoAscii(self): valid_chars = 'ABCDEF0123456789' input_text = unicode(self.input_line.text()) if all(c in valid_chars for c in input_text): if len(input_text) % 2: if self.truncate_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Truncated. ') input_text = input_text[:-1] elif self.refuse_radio.isChecked(): self.popupWindow('Improper Input Length',\ 'Input length is not a multiple of 2. Failure to decode. ') self.output_box.clear() return #check for valid characters (A-F and 0-9) from valid_chars above output_text = str(unhexlify(input_text)) self.output_box.setText(output_text) self.updateStatus() else: self.popupWindow('Invalid Input', 'Sorry, input is not proper hexadecimal. ') self.output_box.clear() def rot13(self): try: input_text = unicode(self.input_line.text()).encode('ascii') except UnicodeEncodeError: self.popupWindow('Invalid Input', 'Sorry, input is not properly formatted. ') self.output_box.clear() return rot13 = maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",\ "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm") output_text = translate(input_text, rot13) self.output_box.setText(output_text) self.updateStatus() #needs error checking... not finished def hexToDecIP(self): input_text = str(self.input_line.text()) flipped_ip = ("".join( reversed( [input_text[i:i + 2] for i in range(0, len(input_text), 2)]))) output_text = ":".join( [str(int(flipped_ip[x:x + 2], 16)) for x in range(0, 8, 2)]) self.output_box.setText(output_text)
def step_dialog(parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) return d.exec_() & QMessageBox.Cancel