Exemplo n.º 1
0
    def load_symbols(self, rom_variant: RomVariant, silent: bool) -> None:

        maps = {
            RomVariant.CUSTOM: 'tmc.map',
            RomVariant.CUSTOM_EU: 'tmc_eu.map',
            RomVariant.CUSTOM_JP: 'tmc_jp.map',
            RomVariant.CUSTOM_DEMO_USA: 'tmc_demo_usa.map',
            RomVariant.CUSTOM_DEMO_JP: 'tmc_demo_jp.map',
        }

        map_file = path.join(settings.get_repo_location(), maps[rom_variant])
        if not path.isfile(map_file):
            if silent:
                print(f'Could not find tmc.map file at {map_file}.')
            else:
                QMessageBox.critical(
                    self, 'Load symbols from .map file',
                    f'Could not find tmc.map file at {map_file}.')
            return

        get_symbol_database().load_symbols_from_map(rom_variant, map_file)
        if not silent:
            QMessageBox.information(
                self, 'Load symbols',
                f'Successfully loaded symbols for {rom_variant} rom from tmc.map file.'
            )
Exemplo n.º 2
0
 def CheckForKill(self):
     if AppGlobals.ProgramRunner().GetTickDelta() > 2:
         self.updateWorker.terminate()
         self.updateWorker.wait()
         AppGlobals.ProgramRunner().StopAll()
         self.updateWorker.start()
         QMessageBox.critical(self, "Timeout", "Program timed out.")
Exemplo n.º 3
0
	def openSelectedFiles(self):
		failedToOpen = []
		files = set()

		for index in self.tree.selectionModel().selectedIndexes():
			if self.model.fileInfo(index).isFile():
				files.add(self.model.fileInfo(index).absoluteFilePath())

		for filename in files:
				QSettings().setValue("triage/recentFile", filename)

				f = FileContext.openFilename(filename)
				if not f:
					failedToOpen.append(filename)
					continue

				for data in f.getAllDataViews():
					Settings().set_string("analysis.mode", Settings().get_string("triage.analysisMode"), data)
					Settings().set_bool("triage.preferSummaryView", True, data)
					if data.view_type != "Raw":
						linearSweepMode = Settings().get_string("triage.linearSweep")
						if linearSweepMode == "none":
							Settings().set_bool("analysis.linearSweep.autorun", False, data)
						elif linearSweepMode == "partial":
							Settings().set_bool("analysis.linearSweep.autorun", True, data)
							Settings().set_bool("analysis.linearSweep.controlFlowGraph", False, data)
						elif linearSweepMode == "full":
							Settings().set_bool("analysis.linearSweep.autorun", True, data)
							Settings().set_bool("analysis.linearSweep.controlFlowGraph", True, data)

				self.context.openFileContext(f)

		if len(failedToOpen) > 0:
			QMessageBox.critical(self, "Error", "Unable to open:\n" + "\n".join(failedToOpen))
Exemplo n.º 4
0
    def check_input(self):
        name = self.txtName.text()
        path = self.txtPath.text()
        password1 = self.txtPassword1.text()
        password2 = self.txtPassword2.text()

        illegal, msg = Key.is_password_illegal(password1)

        if illegal:
            QMessageBox.critical(self, "错误", msg)
            return False

        if password1 != password2:
            QMessageBox.critical(self, "错误", "两次输入的密码不一致")
            return False

        if len(name.strip()) == 0:
            QMessageBox.critical(self, "错误", "名称不能为空")
            return False

        if len(path.strip()) == 0:
            QMessageBox.critical(self, "错误", "路径不能为空")
            return False

        if os.path.exists(path):
            QMessageBox.critical(self, "错误", "目标文件已经存在")
            return False

        return True
    def save_options(self):
        """
        Saves options selected in the first time welcome window.
        """
        self.filepath = self.first_time_welcome_input_box.text()
        self.csv_path = self.clinical_data_csv_input_box.text()
        if self.filepath == "" and self.csv_path == "":
            QMessageBox.about(self, "Unable to proceed",
                              "No directories selected.")
        elif not os.path.exists(self.filepath) or not \
                os.path.exists(self.csv_path):
            QMessageBox.about(self, "Unable to proceed",
                              "Directories do not exist")
        else:
            config = Configuration()
            try:
                config.update_default_directory(self.filepath)

                # Update CSV path if it exists
                if self.csv_path != "" and os.path.exists(self.csv_path):
                    config.update_clinical_data_csv_dir(self.csv_path)
            except SqlError:
                config.set_up_config_db()
                QMessageBox.critical(
                    self, "Config file error",
                    "Failed to access configuration file.\nPlease try again.")
            else:
                self.configured.emit(self.filepath)
Exemplo n.º 6
0
    def slot_show_goto_dialog(self):
        (input_str, res) = QInputDialog.getText(
            self.dock, 'Goto', 'Enter local address to jump to')
        if res:
            # Parse as hex (TODO maybe as decimal, if no 0x and no ABCDEF)
            # TODO handle errors
            try:
                local_address = int(input_str, 16)
            except ValueError:
                # maybe it is a symbol?
                if self.symbols is not None:
                    symbol = self.symbols.find_symbol_by_name(input_str)
                    if symbol is not None:
                        local_address = symbol.address
                    else:
                        QMessageBox.critical(self.parent(), 'Goto', f'{input_str} is not an address or symbol.')
                        return
                else:
                    QMessageBox.critical(self.parent(), 'Goto', f'{input_str} is not an address and symbols are not loaded for {self.rom_variant}.')
                    return

            if local_address > ROM_OFFSET:
                local_address -= ROM_OFFSET
            # TODO error for everything that is not in [0x00000000, 0x00FFFFFF] or [0x08000000, 0x08FFFFFF]
            self.update_cursor(self.address_resolver.to_virtual(local_address))
Exemplo n.º 7
0
    def reload_key_action(self):
        item = self.get_selected_item()
        key: Key = item.data()
        password = None
        if Key.need_password(key.path):
            ok_pressed = True
            while ok_pressed:
                password, ok_pressed = QInputDialog.getText(
                    self, "需要密码", "输入密码:", QLineEdit.Password, "")
                if ok_pressed:
                    illegal, msg = Key.is_password_illegal(password)
                    if illegal:
                        QMessageBox.information(self, '错误', msg)
                        continue
                    break
                else:
                    return

        try:
            key.load(key.path, password)
        except Exception as e:
            QMessageBox.critical(self, '错误', '不是有效的密钥文件<br/>' + str(e))
            return

        self.update_key_icon(item)
Exemplo n.º 8
0
    def add_hex_editor_dock(self, rom_variant: RomVariant,
                            object_name: str) -> HexViewerController:
        '''
        Internally used to add a new or existing hex editor
        '''

        rom = get_rom(rom_variant)
        if rom is None:
            QMessageBox.critical(self.parent, 'Load ROM',
                                 f'Unable to load rom {rom_variant}')
            return None

        dockWidget = HexViewerDock(self.parent, 'Hex Viewer ' + rom_variant)
        # Not only hide docks on close TODO still remove them here
        dockWidget.setAttribute(Qt.WA_DeleteOnClose)
        dockWidget.setObjectName(object_name)
        self.parent.addDockWidget(Qt.DockWidgetArea.TopDockWidgetArea,
                                  dockWidget)

        controller = HexViewerController(dockWidget, rom_variant, rom)
        self.hex_viewer_manager.register_controller(controller)

        dock = Dock(object_name, dockWidget, rom_variant, controller)
        self.docks[object_name] = dock
        dockWidget.destroyed.connect(lambda: self.remove_dock(object_name))
        return controller
Exemplo n.º 9
0
    def populate_list(self):
        try:
            try:
                if not splash.isHidden():
                    splash.showMessage(f"Connecting to server..", color=splash_color)
            except NameError:
                pass

            # Get apps json
            loaded_json = metadata.get_apps(host_name=HOST_NAME)
            i = 0

            for package in loaded_json:
                try:
                    self.ui.listAppsWidget.addItem(f"{package['display_name']}\n"
                                                   f"{metadata.file_size(package['extracted'])} | "
                                                   f"{package['version']} | "
                                                   f"{package['coder']} | "
                                                   f"{package['short_description']}")
                    list_item = self.ui.listAppsWidget.item(i)

                    list_item.setData(Qt.UserRole, package)
                    # Set category icon
                    category = package["category"]

                    # real icons test: if realicons is specified, set icon
                    if utils.is_test("realicons"):
                        list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/testicon.png")))
                    else:
                        if category == "utilities":
                            list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/utility.png")))
                        elif category == "games":
                            list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/game.png")))
                        elif category == "emulators":
                            list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/emulator.png")))
                        elif category == "media":
                            list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/media.png")))
                        elif category == "demos":
                            list_item.setIcon(QIcon(resource_path("assets/gui/icons/category/demo.png")))
                    try:
                        if not splash.isHidden():
                            splash.showMessage(f"Loaded {i} apps..", color=splash_color)
                    except NameError:
                        pass
                    i += 1
                except IndexError:
                    pass
            self.sort_list_alphabetically()
            self.ui.listAppsWidget.setCurrentRow(0)
            self.ui.AppsAmountLabel.setText(str(self.ui.listAppsWidget.count()) + " Apps")

        except Exception as e:
            QMessageBox.critical(self, 'OSCDL: Critical Network Error',
                                 'Could not connect to the Open Shop Channel server.\n'
                                 'Cannot continue. :(\n'
                                 'Please check your internet connection, or report this incident.\n\n'
                                 f'{e}')
            sys.exit(1)
Exemplo n.º 10
0
 def dropEvent(self, event):
     mime = event.mimeData()
     if mime.hasUrls():
         urls = mime.urls()
         for url in urls:
             try:
                 self.open_data(url.toLocalFile())
             except FileNotFoundError as e:
                 QMessageBox.critical(self, "File not found", str(e))
Exemplo n.º 11
0
def errorMessage(parent: Optional[QWidget], message: str, dismissable: bool = False) -> None:
    if dismissable:
        _dismissableMessage(parent,
                            message,
                            QMessageBox.Critical,
                            QMessageBox.Ok,
                            _dismissed_error_messages)
    else:
        QMessageBox.critical(parent, QApplication.applicationName(), message)
Exemplo n.º 12
0
 def import_file(self, f, text, ffilter="*"):
     """Import file."""
     fname = QFileDialog.getOpenFileName(self, text, filter=ffilter)[0]
     if fname:
         try:
             f(fname)
         except LabelsNotFoundError as e:
             QMessageBox.critical(self, "Channel labels not found", str(e))
         except InvalidAnnotationsError as e:
             QMessageBox.critical(self, "Invalid annotations", str(e))
Exemplo n.º 13
0
    def add_new_constraint(self, constraint: Constraint) -> None:
        # Check that constraint is valid
        constraint_manager = ConstraintManager({RomVariant.USA, RomVariant.DEMO, RomVariant.EU, RomVariant.JP, RomVariant.DEMO_JP, RomVariant.CUSTOM, RomVariant.CUSTOM_EU, RomVariant.CUSTOM_JP, RomVariant.CUSTOM_DEMO_USA, RomVariant.CUSTOM_DEMO_JP})
        constraint_manager.add_all_constraints(
            get_constraint_database().get_constraints())
        try:
            constraint_manager.add_constraint(constraint)
            constraint_manager.rebuild_relations()
        except InvalidConstraintError as e:
            QMessageBox.critical(self.parent(), 'Add constraint', 'Invalid Constraint')
            return

        get_constraint_database().add_constraint(constraint)
Exemplo n.º 14
0
 def _error_event(
     self,
     error: str,
     choice: bool = False,
     btn: QMessageBox = QMessageBox.Abort
 ) -> Union[QMessageBox.Ignore, QMessageBox.Abort, None]:
     """Displays an error message with the given error."""
     if choice:
         response = QMessageBox.critical(self, self.tr("Error"), error, btn,
                                         QMessageBox.Ignore)
         return response
     else:
         QMessageBox.critical(self, self.tr("Error"), error, QMessageBox.Ok)
         return None
Exemplo n.º 15
0
 def edit_rom(self, name, lineEdit, expected_sha1):
     (rom,
      _) = QFileDialog.getOpenFileName(self,
                                       f'Select location of {name} rom',
                                       lineEdit.text(), '*.gba')
     if rom is not None:
         sha1 = calculate_sha1(rom)
         if sha1 == expected_sha1:
             lineEdit.setText(rom)
         else:
             QMessageBox.critical(
                 self, 'Wrong sha1',
                 f'The sha1 of file {rom} does not correspond with the sha1 of the {name} rom.\nExpected: {expected_sha1}\nActual: {sha1}'
             )
Exemplo n.º 16
0
def open_file_with_editor(parent, fname: str) -> None:
    editor = cfg.PLATFORM_SETTINGS.get('editor')
    try:
        if editor:
            Popen([editor, fname])
        else:
            raise MissingPreferencesEntry
    except MissingPreferencesEntry:
        msg = f"You should provide a text editor in {cfg.PREFERENCES_INI}"
        QMessageBox.warning(parent, "Warning", msg)
    except:
        msg = f"""The file can't be opened with {editor}.

Please verify your text editor in {cfg.PREFERENCES_INI}
""".strip()
        QMessageBox.critical(parent, "Error", msg)
Exemplo n.º 17
0
def open_file_with_gimp(parent, fname: str) -> None:
    gimp = cfg.PLATFORM_SETTINGS.get('gimp')
    try:
        if gimp:
            Popen([gimp, fname], stderr=DEVNULL)
        else:
            raise MissingPreferencesEntry
    except MissingPreferencesEntry:
        msg = f"You should provide Gimp in {cfg.PREFERENCES_INI}"
        QMessageBox.warning(parent, "Warning", msg)
    except:
        msg = f"""The file can't be opened with {gimp}.

Please verify your Gimp entry in {cfg.PREFERENCES_INI}
""".strip()
        QMessageBox.critical(parent, "Error", msg)
Exemplo n.º 18
0
    def slot_remove_redundant(self) -> None:
        '''
        Disables all constraints that only contain redundant information and don't create more relations
        '''

        progress_dialog = self.api.get_progress_dialog(
            'Constraint Cleaner', 'Removing redundant constraints...', False)
        progress_dialog.show()

        self.thread = QThread()
        self.worker = RemoveRedundantWorker()
        self.worker.moveToThread(self.thread)

        self.worker.signal_progress.connect(
            lambda progress: progress_dialog.set_progress(progress))
        self.worker.signal_done.connect(
            lambda: (  # https://stackoverflow.com/a/13672943
                self.thread.quit(), progress_dialog.close(),
                QMessageBox.information(
                    self.api.main_window, 'Constraint Cleaner',
                    'All redundant constraints are removed.')))
        self.worker.signal_fail.connect(lambda: (
            self.thread.quit(), progress_dialog.close(),
            QMessageBox.critical(
                self.api.main_window, 'Constraint Cleaner',
                'Failed to add a constraint.\nSee console for more information.'
            )))

        self.thread.started.connect(self.worker.process)
        self.thread.start()
Exemplo n.º 19
0
 def update_constraints(self):
     if settings.is_using_constraints():
         print('update constraints')
         print(self.linked_variants)
         self.constraint_manager.reset()
         if len(self.linked_variants) > 1:
             print('Add constraints')
             try:
                 self.constraint_manager.add_all_constraints(
                     get_constraint_database().get_constraints())
             except InvalidConstraintError as e:
                 print(e)
                 QMessageBox.critical(self.parent(), 'Constraint Error', 'The current constraints are not valid.')
         for controller in self.linked_controllers:
             controller.request_repaint()
             controller.setup_scroll_bar()
Exemplo n.º 20
0
 def set_montage(self):
     """Set montage."""
     montages = mne.channels.get_builtin_montages()
     # TODO: currently it is not possible to remove an existing montage
     dialog = MontageDialog(self, montages)
     if dialog.exec():
         name = dialog.montages.selectedItems()[0].data(0)
         montage = mne.channels.make_standard_montage(name)
         ch_names = self.model.current["data"].info["ch_names"]
         # check if at least one channel name matches a name in the montage
         if set(ch_names) & set(montage.ch_names):
             self.model.set_montage(name)
         else:
             QMessageBox.critical(
                 self, "No matching channel names",
                 "Channel names defined in the "
                 "montage do not match any channel name in the data.")
Exemplo n.º 21
0
 def _error_event(
     self,
     error: str,
     choice: bool = False
 ) -> Union[QtWidgets.QMessageBox.Ignore, QtWidgets.QMessageBox.Abort,
            None]:
     """Displays an error message with the given error."""
     if choice:
         response = QMessageBox.critical(self, self.tr("Error"), error,
                                         QtWidgets.QMessageBox.Abort,
                                         QtWidgets.QMessageBox.Ignore)
         return response
     else:
         QMessageBox.critical(self, self.tr("Error"), error,
                              QtWidgets.QMessageBox.Ok)
         self.setEnabled(True)
         return None
Exemplo n.º 22
0
    def do_it(self):
        if not self.check_input():
            return
        pd = QProgressDialog(self)
        pd.setMinimumDuration(10)
        pd.setAutoClose(True)
        pd.setAutoReset(False)
        pd.setLabelText('正在处理')
        pd.setCancelButtonText('取消')
        pd.setRange(0, len(self.file_list))
        pd.setValue(0)
        pd.setWindowModality(Qt.WindowModal)
        pd.show()

        try:
            for index, file_path in enumerate(self.file_list):

                if pd.wasCanceled():
                    break

                pd.setLabelText('正在处理 {}/{}'.format(str(index + 1),
                                                    len(self.file_list)))

                if os.path.exists(file_path):

                    p, n = os.path.split(file_path)
                    file_content = read_file(file_path)

                    if self.before_process(file_content):
                        encrypt_content = self.processor(
                            self.key.key, file_content)
                        output_file = os.path.join(self.output_dir_path, n)
                        write_file(output_file, encrypt_content)

                pd.setValue(pd.value() + 1)

            if not pd.wasCanceled():
                QMessageBox.information(pd, '处理完成', self.success_msg)
            else:
                QMessageBox.information(pd, '已经终止', '用户取消')
        except Exception as e:
            pass
            QMessageBox.critical(pd, '处理失败', str(e))
        pd.close()
        self.close()
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(
                self, "Threaded Fortune Server",
                "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address(
            ) != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                            "Run the Fortune Client example now." %
                            (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemplo n.º 24
0
 def save_default_dir(self):
     self.filepath = self.first_time_welcome_input_box.text()
     if self.filepath == "":
         QMessageBox.about(self, "Unable to proceed",
                           "No directory selected.")
     elif not os.path.exists(self.filepath):
         QMessageBox.about(self, "Unable to proceed",
                           "Directory does not exist")
     else:
         config = Configuration()
         try:
             config.update_default_directory(self.filepath)
         except SqlError:
             config.set_up_config_db()
             QMessageBox.critical(
                 self, "Config file error",
                 "Failed to access configuration file.\nPlease try again.")
         else:
             self.configured.emit(self.filepath)
Exemplo n.º 25
0
 def start_plot(self):
     self.action_run.setEnabled(False)
     self.action_stop.setEnabled(True)
     try:
         port = self.ui.port_combobox.get_current_port_info().device
         with serial.Serial(port, 9600, parity=serial.PARITY_ODD) as ser:
             ser.close()
             ser.parity = serial.PARITY_NONE
             ser.open()
             time = 0
             while self.action_stop.isEnabled():
                 time = time + 0.1
                 analog_value = ser.readline().decode().rstrip()
                 voltage = float(analog_value) * 5 / 1024
                 self.ui.graph_voltage.curve.append_data(time, voltage)
     except Exception as e:
         QMessageBox.critical(self, "ERROR", str(e))
         self.action_run.setEnabled(False)
         self.action_stop.setEnabled(False)
Exemplo n.º 26
0
    def save_settings(self):
        # General
        settings.set_username(self.ui.lineEditUserName.text())
        settings.set_default_selection_size(
            self.ui.spinBoxDefaultSelectionSize.value())
        settings.set_always_load_symbols(
            self.ui.checkBoxAlwaysLoadSymbols.isChecked())
        settings.set_highlight_8_bytes(
            self.ui.checkBoxHighlight8Bytes.isChecked())
        settings.set_bytes_per_line(self.ui.spinBoxBytesPerLine.value())
        settings.set_auto_save(self.ui.checkBoxAutoSave.isChecked())
        settings.set_is_using_constrings(
            self.ui.checkBoxUseConstraints.isChecked())
        settings.set_repo_location(self.ui.lineEditRepoLocation.text())
        settings.set_build_command(self.ui.lineEditBuildCommand.text())
        settings.set_tidy_command(self.ui.lineEditTidyCommand.text())

        # ROMs
        settings.set_rom_usa(self.ui.lineEditRomUsa.text())
        settings.set_rom_demo(self.ui.lineEditRomDemo.text())
        settings.set_rom_eu(self.ui.lineEditRomEu.text())
        settings.set_rom_jp(self.ui.lineEditRomJp.text())
        settings.set_rom_demo_jp(self.ui.lineEditRomDemoJp.text())

        # Layouts
        settings.set_layouts(self.layouts_model.layouts)

        # Plugins
        for plugin in self.plugins:
            name = plugin.get_settings_name()
            enabled = self.plugin_checkboxes[name].isChecked()
            if enabled != settings.is_plugin_enabled(name):
                settings.set_plugin_enabled(name, enabled)
                print(enabled)
                if enabled:
                    if not enable_plugin(plugin):
                        self.plugin_checkboxes[name].setChecked(False)
                        QMessageBox.critical(
                            self, 'Load Plugin Failed',
                            f'Unable to load plugin {plugin.name}.\nCheck console output for more information.'
                        )
                else:
                    disable_plugin(plugin)
Exemplo n.º 27
0
    def loadFile(self, fileName):
        file = QFile(fileName)

        if not file.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, self.windowTitle(),
                                 "Can't open file:\n" + fileName)
            return

        # Set filename
        self.m_programFileName = fileName

        # Prepare text stream
        textStream = QTextStream(file)

        # Read lines
        data = []
        while not textStream.atEnd():
            data.append(textStream.readLine())

        # Load lines
        self.loadData(data)
Exemplo n.º 28
0
    def add_key_action(self):
        file_name, _ = QFileDialog.getOpenFileName(self, '选择密钥文件')

        if len(file_name.strip()) == 0:
            return

        password = None
        if Key.need_password(file_name):
            ok_pressed = True
            while ok_pressed:
                password, ok_pressed = QInputDialog.getText(
                    self, "需要密码", "输入密码:", QLineEdit.Password, "")
                if ok_pressed:
                    illegal, msg = Key.is_password_illegal(password)
                    if illegal:
                        QMessageBox.information(self, '错误', msg)
                        continue
                    break
                else:
                    return

        key = Key()
        try:
            key.load(file_name, password)
        except Exception as e:
            QMessageBox.critical(self, '错误', '不是有效的密钥文件<br/>' + str(e))
            return

        row_len = self.list_model.rowCount()
        for i in range(0, row_len):
            item: QStandardItem = self.list_model.item(i, 0)
            k: Key = item.data()
            if k.id == key.id:
                QMessageBox.information(self, '信息', '相同的密钥已经加载')
                return

        item = self.make_item(key)
        self._add_key(item, key)

        return
Exemplo n.º 29
0
    def slot_multiple_pointers_discovered(self, controller: HexViewerController, base_address: int, count: int) -> None:
        print(base_address)
        for i in range(0, count):
            address = base_address + i * 4
            points_to = controller.get_as_pointer(address)

            if points_to < ROM_OFFSET or points_to > ROM_OFFSET + ROM_SIZE:
                        QMessageBox.critical(self.parent(), 'Add pointer and constraints', f'Address {hex(points_to)} is not inside the rom.')
                        return
            pointer = Pointer(controller.rom_variant, controller.address_resolver.to_local(
                address), points_to, 5, settings.get_username())
            
            try:
                if self.add_pointers_and_constraints(pointer):
                    if i == count -1:
                        QMessageBox.information(self.parent(), 'Add constraints', 'A constraint that changes the relations was added.')
                    elif QMessageBox.question(self.parent(), 'Add pointer and constraints', 'A constraint that changes the relations was added.\nDo you want to continue adding the rest of the pointers?') != QMessageBox.Yes:
                        return

            except InvalidConstraintError as e:
                QMessageBox.critical(self.parent(), 'Add constraints', 'Invalid Constraint')
                return
Exemplo n.º 30
0
    def ok(self):

        if not self.check_input():
            return

        name = self.txtName.text()
        path = self.txtPath.text()
        password1 = self.txtPassword1.text()
        password2 = self.txtPassword2.text()

        self.key = Key()
        self.key.name = name
        self.key.key = os.urandom(32)

        try:
            self.key.save(path, password1)
        except Exception as e:
            QMessageBox.critical(self, "错误", str(e))
            return

        QMessageBox.information(self, '保存成功', '密钥文件已经保存到<br/>' + path)

        self.close()