Exemplo n.º 1
1
 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()
Exemplo n.º 2
1
 def getErrorDialog(self,text,infoText,detailedText):
     dlg = QMessageBox(self)
     dlg.setIcon(QMessageBox.Warning)
     dlg.setWindowModality(QtCore.Qt.WindowModal)
     dlg.setWindowTitle("Error")
     dlg.setText(text)
     dlg.setInformativeText(infoText)
     dlg.setDetailedText(detailedText)
     dlg.setStandardButtons(QMessageBox.Ok)
     
     return dlg
Exemplo n.º 3
0
 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 _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 show_err_dialog(s):
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Warning)
    msg.setText(s)
    msg.setWindowTitle("Warning!")
    msg.setStandardButtons(QMessageBox.Ok)
    msg.exec_()
Exemplo n.º 6
0
def confirmDialog(message):
    """
    Make a simple Yes / No confirmation dialog box with a message
    :type message: str
    """
    msgBox = QMessageBox()
    msgBox.setText(message)
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msgBox.setDefaultButton(QMessageBox.No)
    return msgBox
Exemplo n.º 7
0
def confirmDialog(message):
    """
    Make a simple Yes / No confirmation dialog box with a message
    :type message: str
    """
    msgBox = QMessageBox()
    msgBox.setText(message)
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msgBox.setDefaultButton(QMessageBox.No)
    return msgBox
Exemplo n.º 8
0
 def msgbox(hsgui, title, msg):
     # Make a non modal critical QMessageBox
     msgBox = QMessageBox( hsgui );
     msgBox.setAttribute( Qt.WA_DeleteOnClose )
     msgBox.setStandardButtons( QMessageBox.Ok )
     msgBox.setWindowTitle( title )
     msgBox.setText( msg )
     msgBox.setModal( False )
     msgBox.open( msgBox.close )
     msgBox.show()
     hsgui.non_modal_qt_handles.append(msgBox)
Exemplo n.º 9
0
def emergency_msgbox(title, msg):
    'Make a non modal critical QMessageBox.'
    from PyQt4.Qt import QMessageBox
    msgBox = QMessageBox(None)
    msgBox.setAttribute(Qt.WA_DeleteOnClose)
    msgBox.setStandardButtons(QMessageBox.Ok)
    msgBox.setWindowTitle(title)
    msgBox.setText(msg)
    msgBox.setModal(False)
    msgBox.open(msgBox.close)
    msgBox.show()
    return msgBox
    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 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
Exemplo n.º 12
0
 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_()
Exemplo n.º 13
0
class MessageWindow:
    def __init__(self,
                 title,
                 text,
                 type="ok",
                 default=None,
                 customButtons=None,
                 customIcon=None,
                 run=True,
                 destroyAfterRun=True,
                 detailed=False,
                 longText=""):
        self.rc = None
        self.dialog = None
        self.msgBox = QMessageBox()
        self.doCustom = False
        self.customButtons = customButtons

        icon = None
        buttons = None

        if type == 'ok':
            buttons = QMessageBox.Ok
            icon = "question"
        elif type == 'error':
            icon = "error"
            buttons = QMessageBox.Ok
        elif type == 'warning':
            icon = "warning"
            buttons = QMessageBox.Ok
        elif type == 'okcancel':
            icon = "question"
            buttons = QMessageBox.Ok | QMessageBox.Cancel
        elif type == 'question':
            icon = "question"
            buttons = QMessageBox.Ok | QMessageBox.Cancel
        elif type == 'yesno':
            icon = "question"
            buttons = QMessageBox.Yes | QMessageBox.No
        elif type == 'custom':
            self.doCustom = True
            if customIcon:
                icon = customIcon
            else:
                icon = "question"

        text = "<qt>%s</qt>" % text.replace("\n", " ")
        self.msgBox.setText(text)
        if detailed:
            self.msgBox.setDetailedText(unicode(longText))

        if self.doCustom:
            button = None
            for index, text in enumerate(self.customButtons):
                button = self.msgBox.addButton(text, QMessageBox.ActionRole)
                if default is not None and default == index:
                    self.msgBox.setDefaultButton(button)
        else:
            self.msgBox.setStandardButtons(buttons)

            if default == "no":
                default = QMessageBox.No
            elif default == "yes":
                default = QMessageBox.Yes
            elif default == "ok":
                default = QMessageBox.Ok
            else:
                default = None

        self.msgBox.setDefaultButton(default)

        self.dialog = Dialog(_(title),
                             self.msgBox,
                             closeButton=False,
                             isDialog=True,
                             icon=icon)
        self.dialog.resize(QSize(0, 0))
        if run:
            self.run(destroyAfterRun)

    def run(self, destroyAfterRun=True):
        self.rc = self.dialog.exec_()
        if self.msgBox.clickedButton():
            if not self.doCustom:
                if self.msgBox.clickedButton().text() in [_("Ok"), _("Yes")]:
                    self.rc = 1
                elif self.msgBox.clickedButton().text() in [
                        _("Cancel"), _("No")
                ]:
                    self.rc = 0
            else:
                if self.msgBox.clickedButton().text() in self.customButtons:
                    self.rc = self.customButtons.index(
                        self.msgBox.clickedButton().text())

        if destroyAfterRun:
            self.dialog = None

        return self.rc
Exemplo n.º 14
0
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.'''
            )
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
class MessageWindow:
    def __init__(self, title, text, type="ok", default=None, customButtons =None, customIcon=None, run=True, destroyAfterRun=True, detailed=False, longText=""):
        self.rc = None
        self.dialog = None
        self.msgBox = QMessageBox()
        self.doCustom = False
        self.customButtons = customButtons

        icon  = None
        buttons = None

        if type == 'ok':
            buttons = QMessageBox.Ok
            icon = "question"
        elif type == 'error':
            icon = "error"
            buttons =  QMessageBox.Ok
        elif type == 'warning':
            icon = "warning"
            buttons =  QMessageBox.Ok
        elif type == 'okcancel':
            icon = "question"
            buttons = QMessageBox.Ok | QMessageBox.Cancel
        elif type == 'question':
            icon = "question"
            buttons = QMessageBox.Ok | QMessageBox.Cancel
        elif type == 'yesno':
            icon = "question"
            buttons = QMessageBox.Yes | QMessageBox.No
        elif type == 'custom':
            self.doCustom = True
            if customIcon:
                icon = customIcon
            else:
                icon = "question"

        text = "<qt>%s</qt>" % text.replace("\n", " ")
        self.msgBox.setText(text)
        if detailed:
            self.msgBox.setDetailedText(unicode(longText))

        if self.doCustom:
            button = None
            for index, text in enumerate(self.customButtons):
                button = self.msgBox.addButton(text, QMessageBox.ActionRole)
                if default is not None and default == index:
                    self.msgBox.setDefaultButton(button)
        else:
            self.msgBox.setStandardButtons(buttons)

            if default == "no":
                default = QMessageBox.No
            elif default == "yes":
                default = QMessageBox.Yes
            elif default == "ok":
                default = QMessageBox.Ok
            else:
                default = None

        self.msgBox.setDefaultButton(default)

        self.dialog = Dialog(_(title), self.msgBox, closeButton=False, isDialog=True, icon=icon)
        self.dialog.resize(QSize(0,0))
        if run:
            self.run(destroyAfterRun)

    def run(self, destroyAfterRun=True):
        self.rc = self.dialog.exec_()
        if self.msgBox.clickedButton():
            if not self.doCustom:
                if self.msgBox.clickedButton().text() in [_("Ok"), _("Yes")]:
                    self.rc = 1
                elif self.msgBox.clickedButton().text() in [_("Cancel"), _("No")]:
                    self.rc = 0
            else:
                if self.msgBox.clickedButton().text() in self.customButtons:
                    self.rc = self.customButtons.index(self.msgBox.clickedButton().text())

        if destroyAfterRun:
            self.dialog = None

        return self.rc
Exemplo n.º 17
0
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