Example #1
0
def conv_save_pressed(P, W):
    head = _translate('HandlerClass', 'Save Error')
    with open(P.fNgc, 'r') as inFile:
        for line in inFile:
            if '(new conversational file)' in line:
                msg0 = _translate('HandlerClass',
                                  'An empty file cannot be saved')
                P.dialog_show_ok(QMessageBox.Warning, '{}'.format(head),
                                 '{}\n'.format(msg0))
                return
    P.vkb_show()
    dlg = QFileDialog(W)
    dlg.setOptions(QFileDialog.DontUseNativeDialog)
    dlg.setAcceptMode(QFileDialog.AcceptSave)
    dlg.setNameFilters(['G-Code Files (*.ngc *.nc *.tap)', 'All Files (*)'])
    dlg.setDefaultSuffix('ngc')
    dlg.setDirectory(P.programPrefix)
    name = ''
    if dlg.exec_():
        name = dlg.selectedFiles()[0]
    if name:
        COPY(P.fNgc, name)
        W.conv_save.setEnabled(False)
        conv_enable_tabs(P, W)
    P.vkb_show(True)
Example #2
0
 def instalar_biblioteca(self):
     caminho_bibliotecas = os.path.join(get_caminho_padrao(), "bibliotecas")
     dialogo = QFileDialog()
     dialogo.setWindowTitle("Escolher biblioteca")
     dialogo.setLabelText(QFileDialog.FileName, "Arquivo:")
     dialogo.setLabelText(QFileDialog.LookIn, "Buscar em:")
     dialogo.setLabelText(QFileDialog.FileType, "Tipo de arquivo:")
     dialogo.setLabelText(QFileDialog.Accept, "Escolher")
     dialogo.setLabelText(QFileDialog.Reject, "Cancelar")
     dialogo.setFileMode(QFileDialog.DirectoryOnly)
     dialogo.setDirectory(get_caminho_padrao())
     if dialogo.exec_() == QFileDialog.Accepted:
         caminho = dialogo.selectedUrls()[0].path()
         if (caminho.startswith("/") and os.name == 'nt'):
             caminho = caminho[1:]
         # Testa se o arquivo existe
         if os.path.exists(caminho):
             try:
                 shutil.copytree(
                     caminho,
                     os.path.join(caminho_bibliotecas,
                                  os.path.basename(caminho)))
                 # Directories are the same
             except shutil.Error as e:
                 print('Directory not copied. Error: %s' % e)
                 # Any error saying that the directory doesn't exist
             except OSError as e:
                 print('Directory not copied. Error: %s' % e)
         else:
             QMessageBox(QMessageBox.Warning, "Erro",
                         "O arquivo não existe", QMessageBox.NoButton,
                         self).show()
     else:
         return
Example #3
0
    def getImageFileNamesToOpen(cls, parent_window, defaultDirectory):
        """
        Launch an "Open File" dialog to ask the user for one or more image files.
        """
        extensions = OpDataSelection.SupportedExtensions
        filter_strs = ["*." + x for x in extensions]
        filters = ["{filt} ({filt})".format(filt=x) for x in filter_strs]
        filt_all_str = "Image files (" + ' '.join(filter_strs) + ')'

        fileNames = []
        
        if ilastik_config.getboolean("ilastik", "debug"):
            # use Qt dialog in debug mode (more portable?)
            file_dialog = QFileDialog(parent_window, "Select Images")
            file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
            # do not display file types associated with a filter
            # the line for "Image files" is too long otherwise
            file_dialog.setNameFilters([filt_all_str] + filters)
            #file_dialog.setNameFilterDetailsVisible(False)
            # select multiple files
            file_dialog.setFileMode(QFileDialog.ExistingFiles)
            file_dialog.setDirectory( defaultDirectory )

            if file_dialog.exec_():
                fileNames = file_dialog.selectedFiles()
        else:
            # otherwise, use native dialog of the present platform
            fileNames, _filter = QFileDialog.getOpenFileNames(parent_window, "Select Images", defaultDirectory, filt_all_str)
        return fileNames
Example #4
0
    def file_open_pressed(self):
        unsaved_decision = None

        if self.changes_made:
            unsaved_decision = self.ask_if_to_save()
            if unsaved_decision == QMessageBox.Save:
                self.file_save_pressed()

        if not self.changes_made or unsaved_decision == QMessageBox.Discard:
            open_dialog = QFileDialog()

            open_dialog.setWindowTitle("Open…")
            open_dialog.setFileMode(QFileDialog.ExistingFile)
            open_dialog.setNameFilter('Text files (*.txt)')
            open_dialog.setViewMode(QFileDialog.List)
            open_dialog.setDirectory(self.last_path)
            open_dialog.setProxyModel(None)

            if open_dialog.exec_():
                filepaths = open_dialog.selectedFiles()
                self.opened_filepath = filepaths[0]

                with open(filepaths[0], mode='r',
                          encoding='utf-8') as opened_file:
                    opened_text = opened_file.read()
                    self.ui.textField.setPlainText(opened_text)

                base_filename = ntpath.basename(filepaths[0])
                self.setWindowTitle(base_filename + ' — Notepad')
                self.reset_changes_made()
 def new_campaign(self):
     dialog = QFileDialog(self)
     dialog.setDirectory(helper.one_up(self.current_dir))
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.setWindowTitle('Select folder name')
     if dialog.exec_():
         directory = dialog.selectedFiles()[0]
         qdir = QDir(directory)
         if not qdir.exists():
             self.current_dir = qdir.path()
             for folder_name in resource.folders:
                 qdir.mkpath('./' + folder_name)
             helper.save_json_data(
                 '{}/{}/health{}'.format(self.current_dir,
                                         resource.health_stat.folder,
                                         resource.health_stat.ext),
                 resource.health_stat.default)
             qdir.mkpath('./.settings/std')
             qdir.mkpath('./.settings/debug')
             resource.create_config_files(self.current_dir, qdir.dirName())
             self.refresh_tree_view()
         else:
             helper.display_error('Directory for campaign already exists.'
                                  )  # This shouldn't happen
Example #6
0
def get_save_file_name(initial_name: str, wav_only=False, caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        filter = "Complex files (*.complex);;Complex16 files (2 unsigned int8) (*.complex16u);;Complex16 files (2 signed int8) (*.complex16s);;Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            filter = "wav files (*.wav);;all files (*)"
    elif caption == "Save fuzz profile":
        filter = "Fuzzfiles (*.fuzz);;All files (*)"
    elif caption == "Save encoding":
        filter = ""
    else:
        filter = "Protocols (*.proto);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(filter)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(RECENT_PATH)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setWindowTitle(caption)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.selectFile(initial_name)

    if dialog.exec():
        filename = dialog.selectedFiles()[0]

    if filename:
        RECENT_PATH = os.path.split(filename)[0]

    return filename
Example #7
0
    def __on_activated(self, index):
        data = self.currentData()
        if data != 'CHOOSE':
            self.__prev_value = data
            return

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setViewMode(QFileDialog.Detail)
        dialog.setDirectory(self.__search_dir)
        if not dialog.exec_():
            return

        sound_file_path = dialog.selectedFiles()[0]
        self.__search_dir, sound_file_name = os.path.split(sound_file_path)
        self.__set_settings('search_dir', self.__search_dir)
        if self.count() == self.__max_entries:
            self.remove_item(self.__max_recent - 1)

        self.insert_item(0, sound_file_name, sound_file_path)
        # XXX: Setting current index sets the value of handled key in
        # ConfigManager to the text instead of the data. So would have to
        # select again manually. Seems to have been fixed?
        self.__on_entries_updated()
        self.setCurrentIndex(0)

        # Resize settings window to show full name of chosen sound file.
        parent = self.parent()
        grandparent = parent.parent()
        parent.resize(parent.sizeHint())
        grandparent.resize(grandparent.sizeHint())
Example #8
0
    def open(self):
        dialog = QFileDialog(self)
        dialog.setViewMode(QFileDialog.List)
        dialog.setDirectory(os.getcwd())

        filename = dialog.getOpenFileName(self, "Save")
        
        if filename[0]:
            filePath = filename[0]
            
            try:
                with open(filePath, 'r') as f:
                    text = f.read()
                
                editor = CodeEditor(self)
                editor.setText(text) 
                editor.filename = filePath
                
                self.notebook.newTab(editor)
                x = self.notebook.count()   # number of tabs
                index = x - 1
                self.notebook.setCurrentIndex(index)
                
                tabName = os.path.basename(editor.filename)    
                self.notebook.setTabText(x, tabName)
                self.textPad = editor    
            
            except Exception as e:
                self.statusBar.showMessage(str(e), 3000)
Example #9
0
    def onLoadClicked(self, fileType):
        mySettings = QSettings()
        fileDir = mySettings.value(self.DEFAULT_DIR_KEY)
        if fileDir is None:
            fileDir = os.path.dirname(__file__)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileDialog = QFileDialog()
        fileDialog.setDirectory(fileDir)

        defaultFile = os.path.join(fileDir, defaultFiles[fileType])

        fileName, _ = \
          fileDialog.getOpenFileName(self,
                                     "QFileDialog.getOpenFileName()",
                                     defaultFile, "All Files (*);"
                                     "MHD Files (*.mhd);"
                                     "VTP Files (*.vtp)",
                                     options=options)
        if fileName:
            # Update default dir
            currentDir = QFileInfo(fileName).absoluteDir()
            mySettings.setValue(self.DEFAULT_DIR_KEY,
                                currentDir.absolutePath())
            info = QFileInfo(fileName)
            if (info.completeSuffix() == "mhd") and fileType == 0:
                # Load data
                self.loadFile(fileName)
            elif (info.completeSuffix() == "vtp") and fileType == 1:
                self.loadSurface(fileName, index=0)
            elif (info.completeSuffix() == "vtp") and fileType == 2:
                self.loadSurface(fileName, index=1)
            elif (info.completeSuffix() == "mhd") and fileType == 3:
                self.loadUSFile(fileName)
Example #10
0
 def select_folder(self):
     dialog = QFileDialog(self, "Please select a folder")
     dialog.setDirectory(os.path.expanduser('~'))
     dialog.setFileMode(QFileDialog.Directory)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     if dialog.exec_():
         self.add_folders(dialog.selectedFiles())
Example #11
0
    def saveAs(self):
        ## to do ....
        dialog = QFileDialog(self)
        dialog.setViewMode(QFileDialog.List)
        dialog.setDirectory(os.getcwd())

        filename = dialog.getSaveFileName(self, "Save")
        
        if filename[0]:
            fullpath = filename[0]
            text = self.textPad.text()
            try:
                with open(fullpath, 'w') as file:
                    file.write(text)
                    self.statusBar.showMessage(fullpath + " saved", 3000)
                                    
                    # update all widgets
                    
                    self.textPad.filename = fullpath
                    self.refresh(self.textPad)
                    self.fileBrowser.refresh()
                    fname = os.path.basename(fullpath)
                    index = self.notebook.currentIndex()
                    self.notebook.setTabText(index, fname)

            except Exception as e:
                self.statusBar.showMessage(str(e), 3000)
        
        else:
            self.statusBar.showMessage('File not saved !', 3000)
Example #12
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     state = settings.saveFileDialogState()
     path = self._font.path or self._font.binaryPath
     if path:
         directory = os.path.dirname(path)
     else:
         directory = None if state else QStandardPaths.standardLocations(
             QStandardPaths.DocumentsLocation)[0]
     # TODO: switch to directory dlg on platforms that need it
     dialog = QFileDialog(
         self, self.tr("Save File"), directory,
         ";;".join(fileFormats.keys()))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if directory:
         dialog.setDirectory(directory)
     ok = dialog.exec_()
     settings.setSaveFileDialogState(dialog.saveState())
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         self.saveFile(path, fileFormats[nameFilter])
         self.setWindowTitle(self.fontTitle())
Example #13
0
def make_file_dialog(name_filters, file_mode, directory, parent, native):
    dialog = QFileDialog(parent)
    dialog.setOption(QFileDialog.DontUseNativeDialog, not native)
    dialog.setDirectory(directory)
    dialog.setFileMode(file_mode)
    dialog.setNameFilter(dialog.tr(name_filters))
    return dialog
Example #14
0
    def on_openButton_clicked(self):
        dialog = QFileDialog(self)
        if PATH.IS_SCREEN:
            DIR = PATH.SCREENDIR
        else:
            DIR = PATH.PANELDIR
        dialog.setDirectory(DIR)
        fileName, _ = dialog.getOpenFileName()
        if fileName:
            file = QFile(fileName)
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            try:
                # Python v2.
                styleSheet = unicode(styleSheet, encoding='utf8')
            except NameError:
                # Python v3.
                styleSheet = str(styleSheet, encoding='utf8')

            self.styleTextView.setPlainText(styleSheet)
            model = self.styleSheetCombo.model()
            item = QtGui.QStandardItem(os.path.basename(fileName))
            item.setData( fileName, role = QtCore.Qt.UserRole + 1)
            model.appendRow(item)
            self.styleSheetCombo.setCurrentIndex(self.styleSheetCombo.count()-1)
Example #15
0
def file_dialog(dir='', for_open=True, fmt='', is_folder=False):
    """Dialog z eksploratorem Windows. Otwieranie/tworzenie folderów i plików."""
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    options |= QFileDialog.DontUseCustomDirectoryIcons
    dialog = QFileDialog()
    dialog.setOptions(options)
    dialog.setFilter(dialog.filter() | QDir.Hidden)
    if is_folder:  # Otwieranie folderu
        dialog.setFileMode(QFileDialog.DirectoryOnly)
    else:  # Otwieranie pliku
        dialog.setFileMode(QFileDialog.AnyFile)
    # Otwieranie / zapisywanie:
    dialog.setAcceptMode(
        QFileDialog.AcceptOpen) if for_open else dialog.setAcceptMode(
            QFileDialog.AcceptSave)
    # Ustawienie filtrowania rozszerzeń plików:
    if fmt != '' and not is_folder:
        dialog.setDefaultSuffix(fmt)
        dialog.setNameFilters([f'{fmt} (*.{fmt})'])
    # Ścieżka startowa:
    if dir != '':
        dialog.setDirectory(str(dir))
    else:
        dialog.setDirectory(str(os.environ["HOMEPATH"]))
    # Przekazanie ścieżki folderu/pliku:
    if dialog.exec_() == QDialog.Accepted:
        path = dialog.selectedFiles()[0]
        return path
    else:
        return ''
Example #16
0
    def on_saveButton_clicked(self):
        if PATH.IS_SCREEN:
            DIR = PATH.SCREENDIR
        else:
            DIR = PATH.PANELDIR

        dialog = QFileDialog(self)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        dialog.setOptions(options)
        dialog.setDirectory(DIR)
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("style files (*.qss *.style);;All files (*.*)")
        dialog.setWindowTitle('Save StyleSheet')
        dialog.setLabelText(QFileDialog.Accept, "Save")

        # sidebar links
        urls = []
        urls.append(QUrl.fromLocalFile(os.path.expanduser('~')))
        urls.append(QUrl.fromLocalFile(DIR))
        urls.append(
            QUrl.fromLocalFile(
                os.path.join(os.getcwd(), 'qtvcp/screens', PATH.BASENAME)))

        dialog.setSidebarUrls(urls)

        result = dialog.exec_()
        if result:
            fileName = dialog.selectedFiles()[0]
            self.saveStyleSheet(fileName)
Example #17
0
    def export_csv(self):
        """
        Creates and saves a csv file with the table data.
        """
        file_dialog = QFileDialog()
        file_dialog.setWindowTitle('Save File')
        file_dialog.setDirectory(os.getcwd())
        file_dialog.setAcceptMode(QFileDialog.AcceptSave)
        file_dialog.setNameFilter('Csv files (*.csv)')
        file_dialog.setDefaultSuffix('csv')

        if file_dialog.exec_() == QFileDialog.Accepted:
            path = file_dialog.selectedFiles()[0]

            if path:
                with open(path, mode="w", newline='',
                          encoding='utf8') as csv_file:
                    field_names = ["", "Unit", "Vap", "Liq", "Overall"]
                    writer = csv.DictWriter(csv_file, fieldnames=field_names)
                    writer.writeheader()

                    for row in range(self.table.rowCount()):
                        row_data = {}
                        row_data[""] = self.table.verticalHeaderItem(
                            row).text()

                        for col in range(self.table.columnCount()):
                            item = self.table.item(row, col)

                            if item is not None:
                                row_data[field_names[col + 1]] = item.text()
                            else:
                                row_data[field_names[col + 1]] = ''

                        writer.writerow(row_data)
def open_as_filter(parent, my_filter, path="", multi_files=False):
    selected_filter = ""
    if path == "":
        open_path = os.getcwd()
    else:
        open_path = path

    dialog = QFileDialog(parent, _("Open file"))
    dialog.setDirectory(open_path)

    dialog.setNameFilter(my_filter)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    if multi_files == True:
        dialog.setFileMode(QFileDialog.ExistingFiles)

    if dialog.exec_() == QDialog.Accepted:
        ret_list = []
        s = dialog.selectedNameFilter()
        if s.count("(*") == 1:
            s = s.split("(*")[1]
            s = s[:-1]

        filenames = dialog.selectedFiles()
        for f in filenames:
            if f.endswith(s) == False:
                ret_list.append(f + s)
            else:
                ret_list.append(f)

        if multi_files == True:
            return ret_list
        else:
            return ret_list[0]
    else:
        return None
Example #19
0
 def _select_file(self):
     dialog = QFileDialog(self.parent, "Select a Recovery Key")
     dialog.setDirectory(os.path.expanduser("~"))
     dialog.setFileMode(QFileDialog.ExistingFile)
     if dialog.exec_():
         return dialog.selectedFiles()[0]
     return None
Example #20
0
class FileDialog:
    def __init__(self, title):
        self.callback = None
        self.file_dialog = QFileDialog()
        self.file_dialog.setWindowModality(Qt.ApplicationModal)
        self.filename = ""

        def on_selected(path):
            self.filename = path

        self.file_dialog.fileSelected.connect(on_selected)

    def run(self, callback):
        self.callback = callback
        if self.callback:
            self.file_dialog.fileSelected.connect(self.callback)

        self.file_dialog.exec_()

    def get_filename(self):
        return self.filename

    def set_directory(self, *dirs):
        path = os.path.join(*dirs)
        self.filename = path
        self.file_dialog.setDirectory(path)
Example #21
0
    def handlebuttonbrowse(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        dlg.setLabelText(QFileDialog.Accept, "Save comparison")
        dlg.setDefaultSuffix(self.expected_extension.strip('.'))

        inputfilename = self.settings.get_object('inputfilename')
        dirname = os.path.dirname(inputfilename)
        suggested_filename = os.path.splitext(
            os.path.basename(inputfilename))[0] + self.expected_extension
        dlg.setDirectory(dirname)
        dlg.selectFile(suggested_filename)

        filternames = [
            "%s files (*%s)" % (ext.strip('.'), ext)
            for ext in [self.expected_extension]
        ]
        filternames += ["all files (*)"]
        dlg.setNameFilters(filternames)

        if dlg.exec_():
            self.outputfilename = str(dlg.selectedFiles()[0])
        self.settings.register('outputfilename', self)
        self.outputfile.setText(shorten_path(self.outputfilename))

        if self.outputfilename:
            self.compare()
            self.issaved = True

            print('Complete!')

            self.buttonshow.setEnabled(True)
Example #22
0
    def getImageFileNamesToOpen(cls, parent_window, defaultDirectory):
        """
        opens a QFileDialog for importing files
        """
        extensions = ['nn']
        filter_strs = ["*." + x for x in extensions]
        filters = ["{filt} ({filt})".format(filt=x) for x in filter_strs]
        filt_all_str = "Image files (" + ' '.join(filter_strs) + ')'

        fileNames = []

        if ilastik_config.getboolean("ilastik", "debug"):
            # use Qt dialog in debug mode (more portable?)
            file_dialog = QFileDialog(parent_window, "Select Model")
            file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
            # do not display file types associated with a filter
            # the line for "Image files" is too long otherwise
            file_dialog.setNameFilters([filt_all_str] + filters)
            #file_dialog.setNameFilterDetailsVisible(False)
            # select multiple files
            file_dialog.setFileMode(QFileDialog.ExistingFiles)
            file_dialog.setDirectory(defaultDirectory)

            if file_dialog.exec_():
                fileNames = file_dialog.selectedFiles()
        else:
            # otherwise, use native dialog of the present platform
            fileNames, _ = QFileDialog.getOpenFileNames(parent_window, "Select Model", defaultDirectory, filt_all_str)

        return fileNames
Example #23
0
 def onLoadClicked(self, fileType):
     mySettings = QSettings()
     fileDir = mySettings.value(self.DEFAULT_DIR_KEY)
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     fileDialog = QFileDialog()
     fileDialog.setDirectory(fileDir)
     fileName, _ = \
       fileDialog.getOpenFileName(self,
                                  "QFileDialog.getOpenFileName()",
                                  "", "All Files (*);"
                                  ";MHD Files (*.mhd);"
                                  ";VTP Files (*.vtp)",
                                  options=options)
     if fileName:
         # Update default dir
         currentDir = QFileInfo(fileName).absoluteDir()
         mySettings.setValue(self.DEFAULT_DIR_KEY,
                             currentDir.absolutePath())
         info = QFileInfo(fileName)
         if (info.completeSuffix() == "vtp") and fileType == 1:
             self.loadSurface(fileName)
         elif (info.completeSuffix() == "mhd") and fileType == 0:
             # Load data
             self.loadFile(fileName)
Example #24
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     state = settings.saveFileDialogState()
     path = self._font.path or self._font.binaryPath
     if path:
         directory = os.path.dirname(path)
     else:
         directory = (None if state else QStandardPaths.standardLocations(
             QStandardPaths.DocumentsLocation)[0])
     # TODO: switch to directory dlg on platforms that need it
     dialog = QFileDialog(self, self.tr("Save File"), directory,
                          ";;".join(fileFormats.keys()))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if directory:
         dialog.setDirectory(directory)
     ok = dialog.exec_()
     settings.setSaveFileDialogState(dialog.saveState())
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         if not os.path.basename(path).endswith(".ufo"):
             path += ".ufo"
         self.saveFile(path, fileFormats[nameFilter])
         app = QApplication.instance()
         app.setCurrentFile(self._font.path)
         self.setWindowTitle(self.fontTitle())
Example #25
0
 def spellsSoundSelectButtonClicked(self):
     fd = QFileDialog(self)
     fd.setDirectory("./data/mp3")
     f = fd.getOpenFileName(filter="*.mp3")
     if f[0]:
         self.spellsSoundFileLabel.setText(f[0])
     fd.setParent(None)
Example #26
0
    def getModelFileNameToOpen(cls, parent_window, defaultDirectory):
        """
        opens a QFileDialog for importing files
        """
        extensions = ["pytorch"]
        filter_strs = ["*." + x for x in extensions]
        filters = ["{filt} ({filt})".format(filt=x) for x in filter_strs]
        filt_all_str = "Neural nets (" + " ".join(filter_strs) + ")"

        fileName = None

        if ilastik_config.getboolean("ilastik", "debug"):
            # use Qt dialog in debug mode (more portable?)
            file_dialog = QFileDialog(parent_window, "Select Model")
            file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
            # do not display file types associated with a filter
            # the line for "Image files" is too long otherwise
            file_dialog.setNameFilters([filt_all_str] + filters)
            # file_dialog.setNameFilterDetailsVisible(False)
            file_dialog.setFileMode(QFileDialog.ExistingFile)
            file_dialog.setDirectory(defaultDirectory)

            if file_dialog.exec_():
                fileName = file_dialog.selectedFiles()[0]
        else:
            # otherwise, use native dialog of the present platform
            fileName, _ = QFileDialog.getOpenFileName(parent_window,
                                                      "Select Model",
                                                      defaultDirectory,
                                                      filt_all_str)

        return fileName
Example #27
0
 def on_btnExportLog_clicked(self):
     """
     Export the contents of the log tab to .csv file
     """
     # get filename to save as
     dlg = QFileDialog()
     dlg.setAcceptMode(QFileDialog.AcceptSave)
     dlg.setDefaultSuffix("csv")
     dlg.setNameFilters(["Log File (*.csv)", "all files (*.*)"])
     dlg.setDirectory(self.parent.settings.value("Default/ProjPath"))
     if dlg.exec_():
         fileNames = dlg.selectedFiles()
         try:
             if fileNames:
                 self.fileName = fileNames[0]
                 # save the file
                 with open(self.fileName, 'w', newline='') as csvfile:
                     csvWriter = csv.writer(csvfile,
                                            delimiter=',',
                                            quotechar='"',
                                            quoting=csv.QUOTE_MINIMAL)
                     for row in range(self.gridLog.model().rowCount()):
                         rowItems = []
                         for col in range(
                                 self.gridLog.model().columnCount()):
                             value = self.gridLog.model().index(
                                 row, col,
                                 QModelIndex()).data(Qt.DisplayRole)
                             rowItems.append(value)
                         csvWriter.writerow(c for c in rowItems)
         except BaseException as e:
             msg = "{} - {} failed.".format("Write CSV", repr(e))
             self.helper.displayErrMsg("Export CSV Error", msg)
Example #28
0
def get_save_file_name(initial_name: str,
                       wav_only=False,
                       parent=None,
                       caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        filter = "Complex files (*.complex);;Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            filter = "wav files (*.wav);;all files (*)"
    else:
        filter = "Textfiles (*.txt);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(filter)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(RECENT_PATH)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setWindowTitle(caption)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.selectFile(initial_name)

    if (dialog.exec()):
        filename = dialog.selectedFiles()[0]
        filter = dialog.selectedNameFilter()
        ext = filter[filter.index('*'):filter.index(')')][1:]
        if not os.path.exists(
                filename) and len(ext) > 0 and not filename.endswith(ext):
            filename += ext

    if filename:
        RECENT_PATH = os.path.split(filename)[0]

    return filename
Example #29
0
 def on_btnExportTrace_clicked(self):
     """
     Export the contents of the trace tab to .txt file
     """
     # get filename to save as
     dlg = QFileDialog()
     dlg.setAcceptMode(QFileDialog.AcceptSave)
     dlg.setDefaultSuffix("txt")
     dlg.setNameFilters(["Trace File (*.txt)", "all files (*.*)"])
     dlg.setDirectory(self.parent.settings.value("Default/ProjPath"))
     if dlg.exec_():
         fileNames = dlg.selectedFiles()
         if fileNames:
             self.fileName = fileNames[0]
             # save the file
             file = QFile(self.fileName)
             if not file.open(QFile.WriteOnly | QFile.Text):
                 self.helper.displayErrMsg(
                     "Export Trace Error", "Cannot write file {} {}".format(
                         self.fileName, file.errorString()))
                 return
             outstr = QTextStream(file)
             QApplication.setOverrideCursor(Qt.WaitCursor)
             outstr << self.textTrace.toPlainText()
             QApplication.restoreOverrideCursor()
Example #30
0
    def get_files(self):
        global default_bkg_img_path
        global bkg_img_path
        global bkg_changed_event

        home_dir = os.path.expanduser('~')
        picture_dir = os.path.join(home_dir, 'Pictures')
        open_dir = home_dir
        if os.path.isdir(picture_dir):
            open_dir = picture_dir

        file_dialog = QFileDialog()
        file_dialog.setWindowTitle('Open background image')
        file_dialog.setDirectory(open_dir)
        file_full_path = None
        if file_dialog.exec_() == QtWidgets.QDialog.Accepted:
            file_full_path = str(file_dialog.selectedFiles()[0])

        with bkg_lock:
            if file_full_path is None:
                bkg_img_path = default_bkg_img_path
            else:
                bkg_img_path = file_full_path
                bkg_changed_event.set()
        return file_full_path
Example #31
0
def get_save_file_name(initial_name: str, wav_only=False, caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = "Complex files (*.complex);;Complex16 files (2 unsigned int8) " \
                 "(*.complex16u);;Complex16 files (2 signed int8) (*.complex16s);;" \
                 "Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            name_filter = "wav files (*.wav);;all files (*)"
    elif caption == "Save fuzz profile":
        name_filter = "Fuzzfiles (*.fuzz);;All files (*)"
    elif caption == "Save encoding":
        name_filter = ""
    else:
        name_filter = "Protocols (*.proto);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(name_filter)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(RECENT_PATH)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setWindowTitle(caption)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.selectFile(initial_name)

    if dialog.exec():
        filename = dialog.selectedFiles()[0]

    if filename:
        RECENT_PATH = os.path.split(filename)[0]

    return filename
Example #32
0
def open_as_filter(parent, my_filter, path=""):
    selected_filter = ""
    if path == "":
        open_path = os.getcwd()
    else:
        open_path = path

    dialog = QFileDialog(parent, _("Open file"))
    dialog.setDirectory(open_path)
    print(">>>>>", open_path)
    dialog.setNameFilter(my_filter)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    if dialog.exec_() == QDialog.Accepted:
        filename = dialog.selectedFiles()[0]
        s = dialog.selectedNameFilter()
        if s.count("(*") == 1:
            s = s.split("(*")[1]
            s = s[:-1]

            if filename.endswith(s) == False:
                filename = filename + s
            else:
                filename = filename

        return filename
    else:
        return None
Example #33
0
    def show_file_dialog(self):
        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        # dialog.setNameFilter("Images (*.png)")
        dialog.setViewMode(QFileDialog.List)
        # dialog.setDirectory("/home/shibon/Projects/AutoIMT/CODE/working_code/plotter_test_images/wasted")
        # dialog.setDirectory("/home/quest/Projects/AutoIMT/data_dumps/datasets/random_crop/test_output/ph3/thinned/grey")
        dialog.setDirectory("/home/quest/Projects/AutoIMT/data_dumps/datasets/transferbacktoimages/test_output/wasted")
        img_flag=0
        if dialog.exec_():
            if img_flag==1:
                self.filenames = dialog.selectedFiles()
                self.pixmapLeft = QPixmap(self.filenames[0])
                self.img = cv2.imread(self.filenames[0])
                self.imgGrey = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
                self.imgheight, self.imgwidth = self.imgGrey.shape
                imgcopy = self.img.copy()
                imgcopy[:, 0] = (0, 255, 0)

                bytesPerLine = 3 * self.imgwidth
                qImg = QImage(imgcopy, self.imgwidth, self.imgheight, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
                self.pixmapLeft = QPixmap.fromImage(qImg)
                self.img_label_left.setPixmap(self.pixmapLeft)
                self.img_label_left.setAlignment(Qt.AlignCenter)
                print("satyhar stahar")
                self.file_edit.setText(self.filenames[0])
                text_path=self.file_edit.text()

                print(text_path)
            if img_flag==0:
                self.filenames = dialog.selectedFiles()
                self.file_edit.setText(self.filenames[0])
                text_path = self.file_edit.text()
Example #34
0
 def on_hdf5_dir_pushButton_clicked(self):
     dlg = QFileDialog()
     dlg.setFileMode(QFileDialog.Directory)
     config = self.getCurrentConfig()
     dlg.setDirectory(config['hdf5']['dir'])
     if dlg.exec_():
         dirname = dlg.selectedFiles()
         self.hdf5_dir_lineEdit.setText(dirname[0])
Example #35
0
 def __open_dialog__(title, file_types, dir, setup_dialog, parent=None):
     dialog = QFileDialog(parent)
     if file_types: dialog.setNameFilter(file_types)
     dialog.setDirectory(dir)
     dialog.setWindowTitle(title)
     setup_dialog(dialog)
     dialog.finished.connect(lambda: dialog.deleteLater())
     dialog.show()
Example #36
0
 def _get_log_file(self, event):
     file_dialog = QFileDialog()
     file_dialog.setDirectory(self.settings.get_value('general', 'eq_directory'))
     file = file_dialog.getOpenFileName()[0]
     if file and os.path.exists(file):
         try:
             self._log_file.setText(file)
             self._log_file.setToolTip(file)
         except Exception as e:
             print('_get_log_file:', e)
Example #37
0
 def navigate_directory(self):
     dialog = QFileDialog()
     dialog.setDirectory(self._root_dir)
     dialog.setFileMode(QFileDialog.Directory)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.exec()
     path = dialog.selectedFiles()
     if path and path[0]:
         self._root_dir = path[0]
         self.localPathEdit.setText(self._root_dir)
         self.update_file_tree()
    def load_regime_dialog(self):
        regime_path = os.path.join(os.curdir)

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setDirectory(regime_path)
        dialog.setNameFilter("Simulation Regime files (*.sreg)")

        if dialog.exec_():
            file = dialog.selectedFiles()[0]
            self.load_regimes_from_file(file)
    def exportAction(self):
        dialog = QFileDialog(self)
        dialog.setWindowModality(Qt.WindowModal)    # check for mac only
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setWindowTitle(QApplication.translate("MainWindow", "Export Calculation"))
        dialog.setDirectory(os.path.expanduser("~"))
        dialog.setNameFilter(QApplication.translate("MainWindow",
                "PNG files (*.png);;JPG files (*.jpg);;TIFF files (*.tif)"))

        if dialog.exec():
            filename = dialog.selectedFiles()
            self.plotWidget.plotWidget.plotWidget.export(filename.pop())
    def load_result_files(self):
        path = self._settings.value("path/simulation_results")

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFiles)
        dialog.setDirectory(path)
        dialog.setNameFilter("PyMoskito Result files (*.pmr)")

        if dialog.exec_():
            files = dialog.selectedFiles()
            for single_file in files:
                if single_file:
                    self._load_result_file(single_file)
    def load_post_result_files(self):
        path = self._settings.value("path/processing_results")

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFiles)
        dialog.setDirectory(path)
        dialog.setNameFilter("Postprocessing Output files (*.pof)")

        if dialog.exec_():
            files = dialog.selectedFiles()
            for single_file in files:
                if single_file:
                    self._load_post_result_file(single_file)
Example #42
0
 def _open_radiograph(self):
     file_dialog = QFileDialog(self)
     file_dialog.setDirectory("./data/Radiographs")
     file_dialog.setFileMode(QFileDialog.ExistingFile)
     file_dialog.setNameFilter("Radiograph (*.tif)")
     if file_dialog.exec_() and len(file_dialog.selectedFiles()) == 1:
         radiograph = Radiograph()
         radiograph.path_to_img = file_dialog.selectedFiles()[0]
         #self.image = radiograph.image
         #crop_translation = -Filter.get_cropping_region(radiograph.image).left_top
         self.image = Filter.crop_image(radiograph.image)
         self.lines = None
         self._redraw()
Example #43
0
 def _ioDialog(self, mode):
     if mode == QFileDialog.AcceptOpen:
         title = self.tr("Open File")
     else:
         title = self.tr("Save File")
     dialog = QFileDialog(self, title, None, self.tr("Python file (*.py)"))
     dialog.setAcceptMode(mode)
     dialog.setDirectory(self.fileChooser.currentFolder())
     dialog.setFileMode(QFileDialog.ExistingFile)
     ok = dialog.exec_()
     if ok:
         return dialog.selectedFiles()[0]
     return None
Example #44
0
 def action_open_handler(self):
     p = QFileDialog()
     p.setViewMode(QFileDialog.List)
     p.setFileMode(QFileDialog.ExistingFiles)
     p.setDirectory(config.src_path)
     p.exec()
     paths = p.selectedFiles()
     for pth in paths:
         i = self.file_already_open(pth)
         if i:
             self.mdi.setActiveSubWindow(i.sub_window)
         else:
             m = FsmModel.load_file(pth)
             vm = InstanceVM(m, self, pth)
    def openAction(self):
        # first check save state of the current calculation
        if self.checkSaveState():
            dialog = QFileDialog(self)
            dialog.setWindowModality(Qt.WindowModal)    # check for mac only
            dialog.setWindowTitle(QApplication.translate("MainWindow", "Open Calculation"))
            dialog.setDirectory(os.path.expanduser("~"))
            dialog.setNameFilter(QApplication.translate("MainWindow",
                    "XML files (*.xml);;All Files (*)"))

            dialog.exec()
            filename = dialog.selectedFiles()
            if filename:
                self.model.readFile(filename.pop())
Example #46
0
    def choose_directory(self):
        fileDialog = QFileDialog(self)
        fileDialog.setAcceptMode(QFileDialog.AcceptOpen)
        fileDialog.setFileMode(QFileDialog.Directory)
        fileDialog.setViewMode(QFileDialog.Detail)
        fileDialog.setWindowTitle("Choose Media Directory")
        try:
            fileDialog.setDirectory(QtCore.QStandardPaths.standardLocations(
                                    QtCore.QStandardPaths.MusicLocation)[0])
        except IndexError:
            fileDialog.setDirectory(QtCore.QDir.homePath())

        if fileDialog.exec_() == QDialog.Accepted:
            return fileDialog.selectedFiles()
Example #47
0
 def _open_radiograph(self):
     file_dialog = QFileDialog(self)
     file_dialog.setDirectory("./data/Radiographs")
     file_dialog.setFileMode(QFileDialog.ExistingFile)
     file_dialog.setNameFilter("Radiograph (*.tif)")
     if file_dialog.exec_() and len(file_dialog.selectedFiles()) == 1:
         if self.animator is not None:
             self.animator.stop()
         radiograph = Radiograph()
         radiograph.path_to_img = file_dialog.selectedFiles()[0]
         self.image = radiograph.image
         self.radiograph_image = Filter.crop_image(radiograph.image)
         self.cached_init_poses = None
         self._redraw(self.active_shape_model.current_tooth)
Example #48
0
 def slotAddMount(self):
     fileDialog = QFileDialog(self, Qt.Dialog)
     fileDialog.setFileMode(QFileDialog.Directory)
     fileDialog.setOption(QFileDialog.ShowDirsOnly, True)
     fileDialog.setViewMode(QFileDialog.List)
     fileDialog.setDirectory(os.environ["HOME"])
     if fileDialog.exec():
         selected = fileDialog.selectedFiles()[0]
         if selected in self.newMounts:
             return
         row = self.table_mounts.rowCount()
         self.table_mounts.insertRow(row)
         self.table_mounts.setItem(row, 0, QTableWidgetItem(selected))
         self.table_mounts.setItem(row, 1, QTableWidgetItem("新近添加"))
         self.table_mounts.setItem(row, 2, QTableWidgetItem("新近添加"))
    def saveAsAction(self):
        dialog = QFileDialog(self)
        dialog.setWindowModality(Qt.WindowModal)    # check for mac only
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setWindowTitle(QApplication.translate("MainWindow", "Save Calculation"))
        dialog.setDirectory(os.path.expanduser("~"))
        dialog.setNameFilter(QApplication.translate("MainWindow",
                "XML files (*.xml);;All Files (*)"))

        dialog.exec()
        filename = dialog.selectedFiles()
        if filename:
            self.model.saveFile(filename.pop())
            return True
        else:
            return False
Example #50
0
    def action_save_as_handler(self):
        w = self.mdi.activeSubWindow()
        if w is None:
            return

        p = QFileDialog()
        p.setViewMode(QFileDialog.List)
        p.setDirectory(config.src_path)
        p.exec()
        paths = p.selectedFiles()
        if len(paths) == 0:
            return
        w.instance.file_path = os.path.abspath(paths[0])
        w.instance.update_title()
        model = w.instance.model
        model.dump_file(w.instance.file_path)
        w.instance.set_modified(False)
Example #51
0
    def mousePressEvent(self, event):

        fileNames = ''

        path, file = os.path.split(self.text())

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter( self.tr(self.file_type))
        dialog.setDirectory(path)

        if dialog.exec_():
            fileNames = dialog.selectedFiles()

        if len(fileNames):
            if fileNames[0] != '':
                self.setText(fileNames[0])
Example #52
0
 def _ioDialog(self, mode):
     state = settings.scriptingFileDialogState()
     if mode == QFileDialog.AcceptOpen:
         title = self.tr("Open File")
     else:
         title = self.tr("Save File")
     dialog = QFileDialog(
         self, title, None, self.tr("Python file (*.py)"))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(mode)
     dialog.setDirectory(self.fileChooser.currentFolder())
     dialog.setFileMode(QFileDialog.ExistingFile)
     ok = dialog.exec_()
     settings.setScriptingWindowFileDialogState(state)
     if ok:
         return dialog.selectedFiles()[0]
     return None
Example #53
0
 def slotAddMount(self):
     fileDialog = QFileDialog(self, Qt.Dialog)
     fileDialog.setFileMode(QFileDialog.Directory)
     fileDialog.setOption(QFileDialog.ShowDirsOnly, True)
     fileDialog.setViewMode(QFileDialog.List)
     fileDialog.setDirectory(os.environ["HOME"])
     if fileDialog.exec():
         selected = fileDialog.selectedFiles()[0]
         if selected in self.newMounts:
             return
         row = self.table_mounts.rowCount()
         self.table_mounts.insertRow(row)
         self.table_mounts.setItem(
             row, 0,
             QTableWidgetItem(app.adapterManager[0].mountsFaker.driveIndexToLetter(row) +
                              "\\TDDOWNLOAD"))
         self.table_mounts.setItem(row, 1, QTableWidgetItem(selected))
         self.table_mounts.setItem(row, 2, QTableWidgetItem("新近添加"))
Example #54
0
def directories_dialog(path=None,name='Select Directories'):
    ok = True
    def _pressed_cancel():
        nonlocal ok
        Fi.close()
        app.quit()
        ok &= False

    path = path or CURDIR

    app = QCoreApplication.instance() or QApplication([])

    Fi = QFileDialog()
    Fi.setWindowTitle(name)
    Fi.setOption(Fi.DontUseNativeDialog, True)
    qr = Fi.frameGeometry()
    cp = QDesktopWidget().availableGeometry().center()
    qr.moveCenter(cp)
    Fi.move(qr.topLeft())

    Fi.setFileMode(Fi.DirectoryOnly)
    Fi.setDirectory(path)
    for view in Fi.findChildren((QListView,QTreeView)):
        if isinstance(view.model(), QFileSystemModel):
             view.setSelectionMode(QAbstractItemView.MultiSelection)
    for view in Fi.findChildren(QPushButton):
        if view.text().lower().startswith('&cancel'):
            view.clicked.connect(_pressed_cancel)

    Fi.show()
    app.exec_()

    # The folder selection is also selecting its parent:
    sel_files = Fi.selectedFiles()
    sel_files2 = set(sel_files)
    for fi1 in sel_files:
        for fi2 in sel_files:
            if fi2 != fi1 and fi1 in fi2:
                sel_files2 -= {fi1}
                break

    return ok, list(sel_files2)
Example #55
0
    def on_openButton_clicked(self):
        dialog = QFileDialog(self)
        if self.path.IS_SCREEN:
            DIR = self.path.SCREENDIR
        else:
            DIR =self.path.PANELDIR
        print DIR
        dialog.setDirectory(DIR)
        fileName, _ = dialog.getOpenFileName()
        if fileName:
            file = QFile(fileName)
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            try:
                # Python v2.
                styleSheet = unicode(styleSheet, encoding='utf8')
            except NameError:
                # Python v3.
                styleSheet = str(styleSheet, encoding='utf8')

            self.styleTextView.setPlainText(styleSheet)
Example #56
0
File: main.py Project: dani-l/PaPI
    def triggered_load(self):
        """
        Used to start the 'load config' dialog.

        :return:
        """
        fileNames = ''

        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setNameFilter( self.tr("PaPI-Cfg (*.xml)"))
        dialog.setDirectory(pc.CONFIG_DEFAULT_DIRECTORY)
        dialog.setWindowTitle("Load Configuration")

        if dialog.exec_():
            fileNames = dialog.selectedFiles()

        if len(fileNames):
            if fileNames[0] != '':
                self.last_config = fileNames[0]
                self.load_config(fileNames[0])
    def browse(self):
        """
        Open a file dialog and select a user specified file.
        """
        formats = [
            "Text - comma separated (*.csv, *)",
            "Text - tab separated (*.tsv, *)",
            "Text - all files (*)"
        ]

        dlg = QFileDialog(
            self, windowTitle="Open Data File",
            acceptMode=QFileDialog.AcceptOpen,
            fileMode=QFileDialog.ExistingFile
        )
        dlg.setNameFilters(formats)
        state = self.dialog_state
        lastdir = state.get("directory", "")
        lastfilter = state.get("filter", "")

        if lastdir and os.path.isdir(lastdir):
            dlg.setDirectory(lastdir)
        if lastfilter:
            dlg.selectNameFilter(lastfilter)

        status = dlg.exec_()
        dlg.deleteLater()
        if status == QFileDialog.Accepted:
            self.dialog_state["directory"] = dlg.directory().absolutePath()
            self.dialog_state["filter"] = dlg.selectedNameFilter()

            selected_filter = dlg.selectedNameFilter()
            path = dlg.selectedFiles()[0]
            # pre-flight check; try to determine the nature of the file
            mtype = _mime_type_for_path(path)
            if not mtype.inherits("text/plain"):
                mb = QMessageBox(
                    parent=self,
                    windowTitle="",
                    icon=QMessageBox.Question,
                    text="The '{basename}' may be a binary file.\n"
                         "Are you sure you want to continue?".format(
                            basename=os.path.basename(path)),
                    standardButtons=QMessageBox.Cancel | QMessageBox.Yes
                )
                mb.setWindowModality(Qt.WindowModal)
                if mb.exec() == QMessageBox.Cancel:
                    return

            # initialize dialect based on selected extension
            if selected_filter in formats[:-1]:
                filter_idx = formats.index(selected_filter)
                if filter_idx == 0:
                    dialect = csv.excel()
                elif filter_idx == 1:
                    dialect = csv.excel_tab()
                else:
                    dialect = csv.excel_tab()
                header = True
            else:
                try:
                    dialect, header = sniff_csv_with_path(path)
                except Exception:
                    dialect, header = csv.excel(), True

            options = None
            # Search for path in history.
            # If found use the stored params to initialize the import dialog
            items = self.itemsFromSettings()
            idx = index_where(items, lambda t: samepath(t[0], path))
            if idx is not None:
                _, options_ = items[idx]
                if options_ is not None:
                    options = options_

            if options is None:
                if not header:
                    rowspec = []
                else:
                    rowspec = [(range(0, 1), RowSpec.Header)]
                options = Options(
                    encoding="utf-8", dialect=dialect, rowspec=rowspec)

            dlg = CSVImportDialog(
                self, windowTitle="Import Options",  sizeGripEnabled=True)
            dlg.setWindowModality(Qt.WindowModal)
            dlg.setPath(path)
            dlg.setOptions(options)
            status = dlg.exec_()
            dlg.deleteLater()
            if status == QDialog.Accepted:
                self.set_selected_file(path, dlg.options())
    def requestWrite(self, node, file_name = None, limit_mimetypes = None):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        dialog = QFileDialog()
        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        default_save_path = os.path.expanduser("~/")
        dialog.setDirectory(default_save_path)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None
        last_used_type = Preferences.getInstance().getValue("local_file/last_used_type")

        file_types = Application.getInstance().getMeshFileHandler().getSupportedFileTypesWrite()
        file_types.sort(key = lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(filter(lambda i: i["mime_type"] in limit_mimetypes, file_types))

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError()

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"], item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if last_used_type == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        dialog.setNameFilters(filters)
        if selected_filter != None:
            dialog.selectNameFilter(selected_filter)

        if file_name != None:
            dialog.selectFile(file_name)

        dialog.restoreState(Preferences.getInstance().getValue("local_file/dialog_state").encode())

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        Preferences.getInstance().setValue("local_file/dialog_state", str(dialog.saveState()))

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Preferences.getInstance().setValue("local_file/last_used_type", selected_type["mime_type"])

        file_name = dialog.selectedFiles()[0]

        if os.path.exists(file_name):
            result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)
        mesh_writer = Application.getInstance().getMeshFileHandler().getWriter(selected_type["id"])
        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode", file_name)
                stream = open(file_name, "wt")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode", file_name)
                stream = open(file_name, "wb")

            job = WriteMeshJob(mesh_writer, stream, node, mode)
            job.setFileName(file_name)
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(catalog.i18nc("@info:progress", "Saving to <filename>{0}</filename>").format(file_name), 0, False, -1)
            message.show()

            job._message = message
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status", "Permission denied when trying to save <filename>{0}</filename>").format(file_name)) from e
        except OSError as e:
            Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format()) from e
Example #59
0
class MainController(QMainWindow):
    def __init__(self, *args):
        super().__init__(*args)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        OptionsController.write_default_options()

        self.project_save_timer = QTimer()
        self.project_manager = ProjectManager(self)
        self.plugin_manager = PluginManager()
        self.signal_tab_controller = SignalTabController(self.project_manager,
                                                         parent=self.ui.tab_interpretation)
        self.ui.tab_interpretation.layout().addWidget(self.signal_tab_controller)
        self.compare_frame_controller = CompareFrameController(parent=self.ui.tab_protocol,
                                                               plugin_manager=self.plugin_manager,
                                                               project_manager=self.project_manager)
        self.compare_frame_controller.ui.splitter.setSizes([1, 1000000])


        self.ui.tab_protocol.layout().addWidget(self.compare_frame_controller)

        self.generator_tab_controller = GeneratorTabController(self.compare_frame_controller,
                                                               self.project_manager,
                                                               parent=self.ui.tab_generator)

        self.undo_group = QUndoGroup()
        self.undo_group.addStack(self.signal_tab_controller.signal_undo_stack)
        self.undo_group.addStack(self.compare_frame_controller.protocol_undo_stack)
        self.undo_group.addStack(self.generator_tab_controller.generator_undo_stack)
        self.undo_group.setActiveStack(self.signal_tab_controller.signal_undo_stack)

        self.participant_legend_model = ParticipantLegendListModel(self.project_manager.participants)
        self.ui.listViewParticipants.setModel(self.participant_legend_model)

        gtc = self.generator_tab_controller
        gtc.ui.splitter.setSizes([gtc.width() / 0.7, gtc.width() / 0.3])

        self.ui.tab_generator.layout().addWidget(self.generator_tab_controller)

        self.signal_protocol_dict = {}  # type: dict[SignalFrameController, ProtocolAnalyzer]

        self.ui.lnEdtTreeFilter.setClearButtonEnabled(True)

        group = QActionGroup(self)
        self.ui.actionFSK.setActionGroup(group)
        self.ui.actionOOK.setActionGroup(group)
        self.ui.actionNone.setActionGroup(group)
        self.ui.actionPSK.setActionGroup(group)

        self.recentFileActionList = []
        self.create_connects()
        self.init_recent_file_action_list(constants.SETTINGS.value("recentFiles", []))

        self.filemodel = FileSystemModel(self)
        path = QDir.homePath()

        self.filemodel.setIconProvider(FileIconProvider())
        self.filemodel.setRootPath(path)
        self.file_proxy_model = FileFilterProxyModel(self)
        self.file_proxy_model.setSourceModel(self.filemodel)
        self.ui.fileTree.setModel(self.file_proxy_model)

        self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(path)))
        self.ui.fileTree.setToolTip(path)
        self.ui.fileTree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.ui.fileTree.header().setSectionResizeMode(1, QHeaderView.Stretch)
        self.ui.fileTree.setFocus()

        self.generator_tab_controller.table_model.cfc = self.compare_frame_controller

        self.ui.actionConvert_Folder_to_Project.setEnabled(False)

        undo_action = self.undo_group.createUndoAction(self)
        undo_action.setIcon(QIcon.fromTheme("edit-undo"))
        undo_action.setShortcut(QKeySequence.Undo)
        self.ui.menuEdit.insertAction(self.ui.actionDecoding, undo_action)

        redo_action = self.undo_group.createRedoAction(self)
        redo_action.setIcon(QIcon.fromTheme("edit-redo"))
        redo_action.setShortcut(QKeySequence.Redo)
        self.ui.menuEdit.insertAction(self.ui.actionDecoding, redo_action)
        self.ui.menuEdit.insertSeparator(self.ui.actionDecoding)

        self.ui.actionAbout_Qt.setIcon(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"))

        self.ui.splitter.setSizes([0, 1])
        self.refresh_main_menu()

        self.apply_default_view(constants.SETTINGS.value('default_view', type=int))
        self.project_save_timer.start(ProjectManager.AUTOSAVE_INTERVAL_MINUTES * 60 * 1000)

        self.ui.actionProject_settings.setVisible(False)
        self.ui.actionSave_project.setVisible(False)

    def create_connects(self):
        self.ui.actionFullscreen_mode.setShortcut(QKeySequence.FullScreen)
        self.ui.actionOpen.setShortcut(QKeySequence(QKeySequence.Open))
        self.ui.actionOpen_directory.setShortcut(QKeySequence("Ctrl+Shift+O"))

        self.ui.menuEdit.aboutToShow.connect(self.on_edit_menu_about_to_show)

        self.ui.actionNew_Project.triggered.connect(self.on_new_project_action_triggered)
        self.ui.actionNew_Project.setShortcut(QKeySequence.New)
        self.ui.actionProject_settings.triggered.connect(self.on_project_settings_action_triggered)
        self.ui.actionSave_project.triggered.connect(self.project_manager.saveProject)

        self.ui.actionAbout_AutomaticHacker.triggered.connect(self.on_show_about_clicked)
        self.ui.actionRecord.triggered.connect(self.on_show_record_dialog_action_triggered)

        self.ui.actionFullscreen_mode.triggered.connect(self.on_fullscreen_action_triggered)
        self.ui.actionSaveAllSignals.triggered.connect(self.signal_tab_controller.save_all)
        self.ui.actionClose_all.triggered.connect(self.on_close_all_action_triggered)
        self.ui.actionOpen.triggered.connect(self.on_open_file_action_triggered)
        self.ui.actionOpen_directory.triggered.connect(self.on_open_directory_action_triggered)
        self.ui.actionDecoding.triggered.connect(self.on_show_decoding_dialog_triggered)
        self.ui.actionSpectrum_Analyzer.triggered.connect(self.on_show_spectrum_dialog_action_triggered)
        self.ui.actionOptions.triggered.connect(self.show_options_dialog_action_triggered)
        self.ui.actionSniff_protocol.triggered.connect(self.show_proto_sniff_dialog)
        self.ui.actionAbout_Qt.triggered.connect(QApplication.instance().aboutQt)

        self.ui.btnFileTreeGoUp.clicked.connect(self.on_btn_file_tree_go_up_clicked)
        self.ui.fileTree.directory_open_wanted.connect(self.project_manager.set_project_folder)

        self.signal_tab_controller.frame_closed.connect(self.close_signal_frame)
        self.signal_tab_controller.signal_created.connect(self.add_signal)
        self.signal_tab_controller.ui.scrollArea.files_dropped.connect(self.on_files_dropped)
        self.signal_tab_controller.files_dropped.connect(self.on_files_dropped)
        self.signal_tab_controller.frame_was_dropped.connect(self.set_frame_numbers)

        self.compare_frame_controller.show_interpretation_clicked.connect(
            self.show_protocol_selection_in_interpretation)
        self.compare_frame_controller.files_dropped.connect(self.on_files_dropped)
        self.compare_frame_controller.show_decoding_clicked.connect(self.on_show_decoding_dialog_triggered)
        self.compare_frame_controller.ui.treeViewProtocols.files_dropped_on_group.connect(
            self.on_files_dropped_on_group)
        self.compare_frame_controller.participant_changed.connect(self.signal_tab_controller.on_participant_changed)
        self.compare_frame_controller.ui.treeViewProtocols.close_wanted.connect(self.on_cfc_close_wanted)
        self.compare_frame_controller.show_config_field_types_triggered.connect(
            self.on_show_field_types_config_action_triggered)

        self.ui.lnEdtTreeFilter.textChanged.connect(self.on_file_tree_filter_text_changed)

        self.ui.tabWidget.currentChanged.connect(self.on_selected_tab_changed)
        self.project_save_timer.timeout.connect(self.project_manager.saveProject)

        self.ui.actionConvert_Folder_to_Project.triggered.connect(self.project_manager.convert_folder_to_project)
        self.project_manager.project_loaded_status_changed.connect(self.ui.actionProject_settings.setVisible)
        self.project_manager.project_loaded_status_changed.connect(self.ui.actionSave_project.setVisible)
        self.project_manager.project_loaded_status_changed.connect(self.ui.actionConvert_Folder_to_Project.setDisabled)
        self.project_manager.project_updated.connect(self.on_project_updated)

        self.ui.textEditProjectDescription.textChanged.connect(self.on_text_edit_project_description_text_changed)
        self.ui.tabWidget_Project.tabBarDoubleClicked.connect(self.on_project_tab_bar_double_clicked)

        self.ui.listViewParticipants.doubleClicked.connect(self.on_project_settings_action_triggered)

        self.ui.actionShowFileTree.triggered.connect(self.on_action_show_filetree_triggered)
        self.ui.actionShowFileTree.setShortcut(QKeySequence("F10"))

        self.ui.menuFile.addSeparator()
        for i in range(constants.MAX_RECENT_FILE_NR):
            recent_file_action = QAction(self)
            recent_file_action.setVisible(False)
            recent_file_action.triggered.connect(self.on_open_recent_action_triggered)
            self.recentFileActionList.append(recent_file_action)
            self.ui.menuFile.addAction(self.recentFileActionList[i])

    def add_plain_bits_from_txt(self, filename: str):
        protocol = ProtocolAnalyzer(None)
        protocol.filename = filename
        with open(filename) as f:
            for line in f:
                protocol.messages.append(Message.from_plain_bits_str(line.strip()))

        self.compare_frame_controller.add_protocol(protocol)
        self.compare_frame_controller.refresh()
        self.__add_empty_frame_for_filename(protocol, filename)

    def __add_empty_frame_for_filename(self, protocol: ProtocolAnalyzer, filename: str):
        sf = self.signal_tab_controller.add_empty_frame(filename, protocol)
        self.signal_protocol_dict[sf] = protocol
        self.set_frame_numbers()
        self.file_proxy_model.open_files.add(filename)

    def add_protocol_file(self, filename):
        proto = self.compare_frame_controller.add_protocol_from_file(filename)
        if proto:
            self.__add_empty_frame_for_filename(proto, filename)

    def add_fuzz_profile(self, filename):
        self.ui.tabWidget.setCurrentIndex(2)
        self.generator_tab_controller.load_from_file(filename)

    def add_signalfile(self, filename: str, group_id=0):
        if not os.path.exists(filename):
            QMessageBox.critical(self, self.tr("File not Found"),
                                 self.tr("The file {0} could not be found. Was it moved or renamed?").format(
                                     filename))
            return

        already_qad_demodulated = False
        if filename.endswith(".wav"):
            cb = QCheckBox("Signal in file is already quadrature demodulated")
            msg = self.tr("You selected a .wav file as signal.\n"
                          "Universal Radio Hacker (URH) will interpret it as real part of the signal.\n"
                          "Protocol results may be bad due to missing imaginary part.\n\n"
                          "Load a complex file if you experience problems.\n"
                          "You have been warned.")
            msg_box = QMessageBox(QMessageBox.Information, "WAV file selected", msg)
            msg_box.addButton(QMessageBox.Ok)
            msg_box.addButton(QMessageBox.Abort)
            msg_box.setCheckBox(cb)

            reply = msg_box.exec()
            if reply != QMessageBox.Ok:
                return

            already_qad_demodulated = cb.isChecked()

        sig_name = os.path.splitext(os.path.basename(filename))[0]

        # Use default sample rate for signal
        # Sample rate will be overriden in case of a project later
        signal = Signal(filename, sig_name, wav_is_qad_demod=already_qad_demodulated,
                        sample_rate=self.project_manager.device_conf["sample_rate"])

        if self.project_manager.project_file is None:
            self.adjust_for_current_file(signal.filename)

        self.file_proxy_model.open_files.add(filename)
        self.add_signal(signal, group_id)

    def add_signal(self, signal, group_id=0):
        self.setCursor(Qt.WaitCursor)
        pa = ProtocolAnalyzer(signal)
        sig_frame = self.signal_tab_controller.add_signal_frame(pa)
        pa = self.compare_frame_controller.add_protocol(pa, group_id)

        signal.blockSignals(True)
        has_entry = self.project_manager.read_project_file_for_signal(signal)
        if not has_entry:
            signal.auto_detect()
        signal.blockSignals(False)

        self.signal_protocol_dict[sig_frame] = pa

        sig_frame.refresh(draw_full_signal=True)  # Hier wird das Protokoll ausgelesen
        if self.project_manager.read_participants_for_signal(signal, pa.messages):
            sig_frame.ui.gvSignal.redraw_view()

        sig_frame.ui.gvSignal.auto_fit_view()
        self.set_frame_numbers()

        self.compare_frame_controller.filter_search_results()
        self.refresh_main_menu()
        self.unsetCursor()

    def close_protocol(self, protocol):
        self.compare_frame_controller.remove_protocol(protocol)
        # Needs to be removed in generator also, otherwise program crashes,
        # if item from tree in generator is selected and corresponding signal is closed
        self.generator_tab_controller.tree_model.remove_protocol(protocol)
        protocol.eliminate()

    def close_signal_frame(self, signal_frame: SignalFrameController):
        try:
            self.project_manager.write_signal_information_to_project_file(signal_frame.signal)
            try:
                proto = self.signal_protocol_dict[signal_frame]
            except KeyError:
                proto = None

            if proto is not None:
                self.close_protocol(proto)
                del self.signal_protocol_dict[signal_frame]

            if self.signal_tab_controller.ui.scrlAreaSignals.minimumHeight() > signal_frame.height():
                self.signal_tab_controller.ui.scrlAreaSignals.setMinimumHeight(
                    self.signal_tab_controller.ui.scrlAreaSignals.minimumHeight() - signal_frame.height())

            if signal_frame.signal is not None:
                # Non-Empty Frame (when a signal and not a protocol is opened)
                self.file_proxy_model.open_files.discard(signal_frame.signal.filename)

            signal_frame.eliminate()

            self.compare_frame_controller.ui.treeViewProtocols.expandAll()
            self.set_frame_numbers()
            self.refresh_main_menu()
        except Exception as e:
            Errors.generic_error(self.tr("Failed to close"), str(e), traceback.format_exc())
            self.unsetCursor()

    def add_files(self, filepaths, group_id=0):
        num_files = len(filepaths)
        if num_files == 0:
            return

        for i, file in enumerate(filepaths):
            if not os.path.exists(file):
                continue

            if os.path.isdir(file):
                for f in self.signal_tab_controller.signal_frames:
                    self.close_signal_frame(f)

                FileOperator.RECENT_PATH = file
                self.project_manager.set_project_folder(file)
                return

            _, file_extension = os.path.splitext(file)
            FileOperator.RECENT_PATH = os.path.split(file)[0]

            if file_extension == ".complex":
                self.add_signalfile(file, group_id)
            elif file_extension == ".coco":
                self.add_signalfile(file, group_id)
            elif file_extension == ".proto":
                self.add_protocol_file(file)
            elif file_extension == ".wav":
                self.add_signalfile(file, group_id)
            elif file_extension == ".fuzz":
                self.add_fuzz_profile(file)
            elif file_extension == ".txt":
                self.add_plain_bits_from_txt(file)
            else:
                self.add_signalfile(file, group_id)

    def set_frame_numbers(self):
        self.signal_tab_controller.set_frame_numbers()

    def closeEvent(self, event: QCloseEvent):
        self.project_manager.saveProject()
        super().closeEvent(event)

    def close_all(self):

        self.filemodel.setRootPath(QDir.homePath())
        self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(QDir.homePath())))
        self.project_manager.saveProject()

        self.signal_tab_controller.close_all()
        self.compare_frame_controller.reset()
        self.generator_tab_controller.table_model.protocol.clear()
        self.generator_tab_controller.refresh_tree()
        self.generator_tab_controller.refresh_table()
        self.generator_tab_controller.refresh_label_list()

        self.project_manager.project_path = ""
        self.project_manager.project_file = None
        self.signal_tab_controller.signal_undo_stack.clear()
        self.compare_frame_controller.protocol_undo_stack.clear()
        self.generator_tab_controller.generator_undo_stack.clear()

    def show_options_dialog_specific_tab(self, tab_index: int):
        op = OptionsController(self.plugin_manager.installed_plugins, parent=self)
        op.values_changed.connect(self.on_options_changed)
        op.ui.tabWidget.setCurrentIndex(tab_index)
        op.show()

    def refresh_main_menu(self):
        enable = len(self.signal_protocol_dict) > 0
        self.ui.actionSaveAllSignals.setEnabled(enable)
        self.ui.actionClose_all.setEnabled(enable)

    def apply_default_view(self, view_index: int):
        self.compare_frame_controller.ui.cbProtoView.setCurrentIndex(view_index)
        self.generator_tab_controller.ui.cbViewType.setCurrentIndex(view_index)
        for sig_frame in self.signal_tab_controller.signal_frames:
            sig_frame.ui.cbProtoView.setCurrentIndex(view_index)

    def show_project_settings(self):
        pdc = ProjectDialogController(new_project=False, project_manager=self.project_manager, parent=self)
        pdc.finished.connect(self.on_project_dialog_finished)
        pdc.show()

    def collapse_project_tab_bar(self):
        self.ui.tabParticipants.hide()
        self.ui.tabDescription.hide()
        self.ui.tabWidget_Project.setMaximumHeight(self.ui.tabWidget_Project.tabBar().height())

    def expand_project_tab_bar(self):
        self.ui.tabDescription.show()
        self.ui.tabParticipants.show()
        self.ui.tabWidget_Project.setMaximumHeight(9000)

    @pyqtSlot()
    def on_project_tab_bar_double_clicked(self):
        if self.ui.tabParticipants.isVisible():
            self.collapse_project_tab_bar()
        else:
            self.expand_project_tab_bar()

    @pyqtSlot()
    def on_project_updated(self):
        self.participant_legend_model.participants = self.project_manager.participants
        self.participant_legend_model.update()
        self.compare_frame_controller.refresh()
        self.ui.textEditProjectDescription.setText(self.project_manager.description)

    @pyqtSlot()
    def on_fullscreen_action_triggered(self):
        if self.ui.actionFullscreen_mode.isChecked():
            self.showFullScreen()
        else:
            self.showMaximized()

    @pyqtSlot(str)
    def adjust_for_current_file(self, file_path):
        if file_path is None:
            return

        if file_path in FileOperator.archives.keys():
            file_path = copy.copy(FileOperator.archives[file_path])

        settings = constants.SETTINGS
        recent_file_paths = settings.value("recentFiles", [])
        recent_file_paths = [] if recent_file_paths is None else recent_file_paths  # check None for OSX
        recent_file_paths = [p for p in recent_file_paths if p != file_path and p is not None and os.path.exists(p)]
        recent_file_paths.insert(0, file_path)
        recent_file_paths = recent_file_paths[:constants.MAX_RECENT_FILE_NR]

        self.init_recent_file_action_list(recent_file_paths)

        settings.setValue("recentFiles", recent_file_paths)

    def init_recent_file_action_list(self, recent_file_paths: list):
        for i in range(len(self.recentFileActionList)):
            self.recentFileActionList[i].setVisible(False)

        if recent_file_paths is None:
            return

        for i, file_path in enumerate(recent_file_paths):
            if os.path.isfile(file_path):
                display_text = os.path.basename(file_path)
                self.recentFileActionList[i].setIcon(QIcon())
            elif os.path.isdir(file_path):
                head, tail = os.path.split(file_path)
                display_text = tail
                head, tail = os.path.split(head)
                if tail:
                    display_text = tail + "/" + display_text

                self.recentFileActionList[i].setIcon(QIcon.fromTheme("folder"))
            else:
                continue

            self.recentFileActionList[i].setText(display_text)
            self.recentFileActionList[i].setData(file_path)
            self.recentFileActionList[i].setVisible(True)

    @pyqtSlot()
    def on_show_field_types_config_action_triggered(self):
        self.show_options_dialog_specific_tab(tab_index=2)

    @pyqtSlot()
    def on_open_recent_action_triggered(self):
        action = self.sender()
        try:
            if os.path.isdir(action.data()):
                self.project_manager.set_project_folder(action.data())
            elif os.path.isfile(action.data()):
                self.setCursor(Qt.WaitCursor)
                self.add_files(FileOperator.uncompress_archives([action.data()], QDir.tempPath()))
                self.unsetCursor()
        except Exception as e:
            Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
            self.unsetCursor()

    @pyqtSlot()
    def on_show_about_clicked(self):
        descr = "<b><h2>Universal Radio Hacker</h2></b>Version: {0}<br />" \
                "GitHub: <a href='https://github.com/jopohl/urh'>https://github.com/jopohl/urh</a><br /><br />" \
                "Creators:<i><ul><li>" \
                "Johannes Pohl &lt;<a href='mailto:[email protected]'>[email protected]</a>&gt;</li>" \
                "<li>Andreas Noack &lt;<a href='mailto:[email protected]'>[email protected]</a>&gt;</li>" \
                "</ul></i>".format(version.VERSION)

        QMessageBox.about(self, self.tr("About"), self.tr(descr))

    @pyqtSlot(int, int, int, int)
    def show_protocol_selection_in_interpretation(self, start_message, start, end_message, end):
        cfc = self.compare_frame_controller
        msg_total = 0
        last_sig_frame = None
        for protocol in cfc.protocol_list:
            if not protocol.show:
                continue
            n = protocol.num_messages
            view_type = cfc.ui.cbProtoView.currentIndex()
            messages = [i - msg_total for i in range(msg_total, msg_total + n) if start_message <= i <= end_message]
            if len(messages) > 0:
                try:
                    signal_frame = next((sf for sf, pf in self.signal_protocol_dict.items() if pf == protocol))
                except StopIteration:
                    QMessageBox.critical(self, self.tr("Error"),
                                         self.tr("Could not find corresponding signal frame."))
                    return
                signal_frame.set_roi_from_protocol_analysis(min(messages), start, max(messages), end + 1, view_type)
                last_sig_frame = signal_frame
            msg_total += n
        focus_frame = last_sig_frame
        if last_sig_frame is not None:
            self.signal_tab_controller.ui.scrollArea.ensureWidgetVisible(last_sig_frame, 0, 0)

        QApplication.instance().processEvents()
        self.ui.tabWidget.setCurrentIndex(0)
        if focus_frame is not None:
            focus_frame.ui.txtEdProto.setFocus()

    @pyqtSlot(str)
    def on_file_tree_filter_text_changed(self, text: str):
        if len(text) > 0:
            self.filemodel.setNameFilters(["*" + text + "*"])
        else:
            self.filemodel.setNameFilters(["*"])

    @pyqtSlot()
    def on_show_decoding_dialog_triggered(self):
        signals = [sf.signal for sf in self.signal_tab_controller.signal_frames]
        decoding_controller = DecoderWidgetController(
            self.compare_frame_controller.decodings, signals,
            self.project_manager, parent=self)
        decoding_controller.finished.connect(self.update_decodings)
        decoding_controller.show()
        decoding_controller.decoder_update()

    @pyqtSlot()
    def update_decodings(self):
        self.compare_frame_controller.load_decodings()
        self.compare_frame_controller.fill_decoding_combobox()
        self.compare_frame_controller.refresh_existing_encodings()

        self.generator_tab_controller.refresh_existing_encodings(self.compare_frame_controller.decodings)

    @pyqtSlot(int)
    def on_selected_tab_changed(self, index: int):
        if index == 0:
            self.undo_group.setActiveStack(self.signal_tab_controller.signal_undo_stack)
        elif index == 1:
            self.undo_group.setActiveStack(self.compare_frame_controller.protocol_undo_stack)
            self.compare_frame_controller.ui.tblViewProtocol.resize_columns()
            self.compare_frame_controller.ui.tblViewProtocol.resize_vertical_header()
            h = max(self.compare_frame_controller.ui.btnSaveProto.height(),
                    self.generator_tab_controller.ui.btnSave.height())
            self.compare_frame_controller.ui.btnSaveProto.setMinimumHeight(h)

            th = self.compare_frame_controller.ui.tabWidget.tabBar().height()
            for i in range(self.compare_frame_controller.ui.tabWidget.count()):
                self.compare_frame_controller.ui.tabWidget.widget(i).layout().setContentsMargins(0, 7 + h - th, 0, 0)

        elif index == 2:
            self.undo_group.setActiveStack(self.generator_tab_controller.generator_undo_stack)
            h = max(self.compare_frame_controller.ui.btnSaveProto.height(),
                    self.generator_tab_controller.ui.btnSave.height())
            self.generator_tab_controller.ui.btnSave.setMinimumHeight(h)
            th = self.generator_tab_controller.ui.tabWidget.tabBar().height()
            for i in range(self.generator_tab_controller.ui.tabWidget.count()):
                self.generator_tab_controller.ui.tabWidget.widget(i).layout().setContentsMargins(0, 7 + h - th, 0, 0)

    @pyqtSlot()
    def on_show_record_dialog_action_triggered(self):
        pm = self.project_manager
        try:
            r = ReceiveDialogController(pm, parent=self)
        except OSError as e:
            logger.error(repr(e))
            return

        if r.has_empty_device_list:
            Errors.no_device()
            r.close()
            return

        r.recording_parameters.connect(pm.set_recording_parameters)
        r.files_recorded.connect(self.on_signals_recorded)
        r.show()

    @pyqtSlot()
    def show_proto_sniff_dialog(self):
        pm = self.project_manager
        signal = next((proto.signal for proto in self.compare_frame_controller.protocol_list), None)

        bit_len = signal.bit_len          if signal else 100
        mod_type = signal.modulation_type if signal else 1
        tolerance = signal.tolerance      if signal else 5
        noise = signal.noise_threshold    if signal else 0.001
        center = signal.qad_center        if signal else 0.02

        psd = ProtocolSniffDialogController(pm, noise, center, bit_len, tolerance, mod_type,
                                            self.compare_frame_controller.decodings,
                                            encoding_index=self.compare_frame_controller.ui.cbDecoding.currentIndex(),
                                            parent=self)

        if psd.has_empty_device_list:
            Errors.no_device()
            psd.close()
        else:
            psd.recording_parameters.connect(pm.set_recording_parameters)
            psd.protocol_accepted.connect(self.compare_frame_controller.add_sniffed_protocol_messages)
            psd.show()

    @pyqtSlot()
    def on_show_spectrum_dialog_action_triggered(self):
        pm = self.project_manager
        r = SpectrumDialogController(pm, parent=self)
        if r.has_empty_device_list:
            Errors.no_device()
            r.close()
            return

        r.recording_parameters.connect(pm.set_recording_parameters)
        r.show()

    @pyqtSlot(list)
    def on_signals_recorded(self, file_names: list):
        QApplication.instance().setOverrideCursor(Qt.WaitCursor)
        for filename in file_names:
            self.add_signalfile(filename)
        QApplication.instance().restoreOverrideCursor()

    @pyqtSlot()
    def show_options_dialog_action_triggered(self):
        self.show_options_dialog_specific_tab(tab_index=0)

    @pyqtSlot()
    def on_new_project_action_triggered(self):
        pdc = ProjectDialogController(parent=self)
        pdc.finished.connect(self.on_project_dialog_finished)
        pdc.show()

    @pyqtSlot()
    def on_project_settings_action_triggered(self):
        self.show_project_settings()

    @pyqtSlot()
    def on_edit_menu_about_to_show(self):
        self.ui.actionShowFileTree.setChecked(self.ui.splitter.sizes()[0] > 0)

    @pyqtSlot()
    def on_action_show_filetree_triggered(self):
        if self.ui.splitter.sizes()[0] > 0:
            self.ui.splitter.setSizes([0, 1])
        else:
            self.ui.splitter.setSizes([1, 1])

    @pyqtSlot()
    def on_project_dialog_finished(self):
        if self.sender().committed:
            if self.sender().new_project:
                for f in self.signal_tab_controller.signal_frames:
                    self.close_signal_frame(f)

            self.project_manager.from_dialog(self.sender())

    @pyqtSlot()
    def on_open_file_action_triggered(self):
        self.show_open_dialog(directory=False)

    @pyqtSlot()
    def on_open_directory_action_triggered(self):
        self.show_open_dialog(directory=True)

    def show_open_dialog(self, directory=False):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        if directory:
            self.dialog.setFileMode(QFileDialog.Directory)
        else:
            self.dialog.setFileMode(QFileDialog.ExistingFiles)
            self.dialog.setNameFilter(
                "All files (*);;Complex (*.complex);;Complex16 unsigned (*.complex16u);;Complex16 signed (*.complex16s);;Wave (*.wav);;Protocols (*.proto);;"
                "Fuzzprofiles (*.fuzz);;Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)")

        self.dialog.setOptions(QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)

        if self.dialog.exec_():
            try:
                file_names = self.dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                QApplication.instance().restoreOverrideCursor()

    @pyqtSlot()
    def on_close_all_action_triggered(self):
        self.close_all()

    @pyqtSlot(list)
    def on_files_dropped(self, files):
        """
        :type files: list of QtCore.QUrl
        """
        self.__add_urls_to_group(files, group_id=0)

    @pyqtSlot(list, int)
    def on_files_dropped_on_group(self, files, group_id: int):
        """
        :param group_id:
        :type files: list of QtCore.QUrl
        """
        self.__add_urls_to_group(files, group_id=group_id)

    def __add_urls_to_group(self, file_urls, group_id=0):
        local_files = [file_url.toLocalFile() for file_url in file_urls if file_url.isLocalFile()]
        if len(local_files) > 0:
            self.setCursor(Qt.WaitCursor)
            self.add_files(FileOperator.uncompress_archives(local_files, QDir.tempPath()), group_id=group_id)
            self.unsetCursor()

    @pyqtSlot(list)
    def on_cfc_close_wanted(self, protocols: list):
        frame_protos = {sframe: protocol for sframe, protocol in self.signal_protocol_dict.items() if protocol in protocols}

        for frame in frame_protos:
            self.close_signal_frame(frame)

        for proto in (proto for proto in protocols if proto not in frame_protos.values()):
            # close protocols without associated signal frame
            self.close_protocol(proto)

    @pyqtSlot(dict)
    def on_options_changed(self, changed_options: dict):
        refresh_protocol_needed = "show_pause_as_time" in changed_options

        if refresh_protocol_needed:
            for sf in self.signal_tab_controller.signal_frames:
                sf.refresh_protocol()

        self.compare_frame_controller.refresh_field_types_for_labels()
        self.compare_frame_controller.set_shown_protocols()
        self.generator_tab_controller.set_network_sdr_send_button_visibility()
        self.generator_tab_controller.init_rfcat_plugin()

        if "default_view" in changed_options:
            self.apply_default_view(int(changed_options["default_view"]))

    @pyqtSlot()
    def on_text_edit_project_description_text_changed(self):
        self.project_manager.description = self.ui.textEditProjectDescription.toPlainText()

    @pyqtSlot()
    def on_btn_file_tree_go_up_clicked(self):
        cur_dir = self.filemodel.rootDirectory()
        if cur_dir.cdUp():
            path = cur_dir.path()
            self.filemodel.setRootPath(path)
            self.ui.fileTree.setRootIndex(self.file_proxy_model.mapFromSource(self.filemodel.index(path)))