Example #1
0
    def open_case(self):
        """
        Gives the user a file dialog to find their existing project and opens that.
        :return: None
        """
        open_dialog = QFileDialog()

        user_location = open_dialog.getOpenFileName()[
            0]  # Index 0 because user can't pick more than one file.
        if user_location == '':
            return  # User most likely pressed cancel.

        case = Case.open_from_disk(user_location)

        if case is None:  # Something bad must have happened. Tell the user that the file is corrupt. Or invalid.
            alert = QMessageBox()
            alert.setText("Corrupt case file or invalid file type.")
            alert.setIcon(QMessageBox.Critical)

            alert.exec_()

            return
        else:
            # Successfully open a case!
            case_controller = CaseController(case)

            self.open_window(case_controller)
 def image_import(self):
     """
     Take the path(s) of one or more images and import them to the application.
     :return: Nothing
     """
     file_dialog = QFileDialog()  # Create QFileDialog
     # Open the file dialog as Open File Names dialog (for image choice)
     f_path = file_dialog.getOpenFileNames(parent=None,
                                           caption="Open Image(s)",
                                           directory=QDir.homePath(),
                                           filter=self.IMG_FILTER,
                                           options=self.DIALOG_FLAG)[0]
     if f_path:  # If user chose at least one image
         img_id_counter = 0  # Set a counter for id
         for file in f_path:  # For all paths in f_paths
             image_tmp = Image()  # Create an Image object
             success = image_tmp.img_open(file)  # Set image parameters
             if success:  # If image exists
                 image_tmp.img_set_image_id(img_id_counter)  # Set image counter
                 img_id_counter += 1  # increase the counter by 1
                 # image_tmp.img_print_info()  # print image info for debugging
                 self.image_list.append(image_tmp)  # Append image to list
                 item_name = "../" + image_tmp.info.dir_name + "/" + image_tmp.info.name  # Set name for view
                 item_widget = QListWidgetItem(item_name)  # Append item to window image list
                 item_widget.setFlags(item_widget.flags() | QtCore.Qt.ItemIsUserCheckable)  # Set it checkable
                 item_widget.setCheckState(QtCore.Qt.Checked)  # Set it checked
                 self.ui_main_win.listImage.addItem(item_widget)  # Add item to list
                 self.ui_main_win.menuCamera_Settings.setEnabled(self.UP)  # Enable Camera menu
                 self.ui_main_win.actionCrabSFM.setEnabled(self.UP)  # Enable SFM action
Example #3
0
    def getFile(self):

        dialg = QFileDialog()
        dialg.setFileMode(QFileDialog.AnyFile)
        dialg.setNameFilter("CSV Files (*.csv)")
        if dialg.exec_():
            fileName = dialg.selectedFiles()
            f = open(fileName[0], 'r')
            ml = machineLearning(f)

            with open(fileName[0], 'r') as f:
                data = f.read()
                self.textEditor.setPlainText(data)
                self.table.setRowCount(len(ml))
                self.table.setColumnCount(1)
                x = -1

                while x <= len(ml) - 2:
                    x += 1
                    self.table.setItem(x, 0, QTableWidgetItem(ml[x]))
            header = self.table.horizontalHeader()
            header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)

            f.close()
        else:
            pass
Example #4
0
        def change_homescreen():
            dialog = QFileDialog(self, _("Choose Homescreen"))
            filename, __ = dialog.getOpenFileName()
            if not filename:
                return  # user cancelled

            if filename.endswith('.toif'):
                img = open(filename, 'rb').read()
                if img[:8] != b'TOIf\x90\x00\x90\x00':
                    handler.show_error('File is not a TOIF file with size of \
                                       144x144')
                    return
            else:
                from PIL import Image  # FIXME
                im = Image.open(filename)
                if im.size != (128, 64):
                    handler.show_error('Image must be 128 x 64 pixels')
                    return
                im = im.convert('1')
                pix = im.load()
                img = bytearray(1024)
                for j in range(64):
                    for i in range(128):
                        if pix[i, j]:
                            o = (i + j * 128)
                            img[o // 8] |= (1 << (7 - o % 8))
                img = bytes(img)
            invoke_client('change_homescreen', img)
Example #5
0
 def openFile(self):
     # Initialize window to show opened image
     self.newW = ShowOpenedImage()
     fileDialog = QFileDialog()
     fName = fileDialog.getOpenFileName(self, 'Open Image', '/', 'Image Files (*.png *.jpg *.bmp)');
     print('Opened file %s' %fName[0])
     self.newW.showImage(fName[0])
 def set_path_action_handler(self):
     file_dialog = QFileDialog()
     path = file_dialog.getExistingDirectory(
         self, "Select directory", "/home/",
         QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
     self.logger.info("Path set to %s", path)
     self.set_path(path)
     self.app.save_setting("path", path)
Example #7
0
 def get_open_filename(self, parent, filter_, file_mode=None):
     dialog = QFileDialog(parent, directory=self._get_default_directory(), filter=filter_)
     if file_mode:
         dialog.setFileMode(file_mode)
     if dialog.exec_():
         return dialog.selectedFiles()[0]
     else:
         return None
Example #8
0
 def get_save_filename(self, parent, filter_, default_name=None):
     dialog = QFileDialog(parent, directory=self._get_default_directory(), filter=filter_)
     if default_name:
         dialog.selectFile(default_name)
     dialog.setModal(True)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if dialog.exec_() != QFileDialog.Accepted or not dialog.selectedFiles():
         return None
     return dialog.selectedFiles()[0]
Example #9
0
 def _open_file(self, filter):
     caption = 'open File'
     filters = 'File (%s)' % (filter)
     dlg = QFileDialog(self, caption, self.lastOpenDirPath, filters)
     dlg.setDefaultSuffix(filter)
     dlg.setFileMode(QFileDialog.AnyFile)
     dlg.setOption(QFileDialog.DontUseNativeDialog, False)
     if dlg.exec_():
         return dlg.selectedFiles()[0]
     return ''
 def browse_sample_xray(self):
     """Browse for a sample xray file to use during x-ray creation"""
     file_dialog = QFileDialog(self)
     sample_file = file_dialog.getOpenFileName(
         caption='Choose sample x-ray to use:',
         filter='X-Ray or JSON (*.asc *.json)')[0]
     self.book.sample_xray = sample_file
     self._sample_xray_edit.setText(sample_file)
     if sample_file:
         self.update_aliases_from_file()
Example #11
0
 def _chooseFile(self):
     if self._file_dialog is None:
         dialog = self._file_dialog = QFileDialog(self, self._dialog_label, ".", self._file_types)
         if self._default_suffix:
             dialog.setDefaultSuffix(self._default_suffix)
         dialog.setFileMode(self._file_mode)
         dialog.setModal(True)
         if self._dir is not None:
             dialog.setDirectory(self._dir)
         dialog.filesSelected['QStringList'].connect(self.setFilename)
     return self._file_dialog.exec_()
Example #12
0
    def handleAddSrcFiles(self):
        fileDlg = QFileDialog(self, 'Select Files',
                              self.config[PATHS]['download_path'],
                              self.filetypes)
        fileDlg.setFileMode(QFileDialog.ExistingFiles)

        if fileDlg.exec_():
            for filename in fileDlg.selectedFiles():
                if filename not in self.filenames:
                    self.filenames.append(filename)
                    self.srcFilesList.addItem(filename)
Example #13
0
    def handleSelectSrcFiles(self):
        fileDlg = QFileDialog(self, 'Select Files',
                              self.config[PATHS]['download_path'],
                              self.filetypes)
        fileDlg.setFileMode(QFileDialog.ExistingFiles)

        if fileDlg.exec_():
            self.filenames = fileDlg.selectedFiles()

        self.srcFilesList.clear()
        self.srcFilesList.addItems(self.filenames)
Example #14
0
 def saveSelectionAs(self, filename=None, force=False):
     if not self.model:
         return
     if filename is None:
         if not self._save_sel_as_dialog:
             filters = ";;".join([
                 "%s (%s)" % (name, " ".join(patterns))
                 for name, patterns, func in self._save_file_types
             ])
             dialog = self._save_sel_as_dialog = QFileDialog(
                 self, "Save sky model", ".", filters)
             dialog.setDefaultSuffix(ModelHTML.DefaultExtension)
             dialog.setFileMode(QFileDialog.AnyFile)
             dialog.setAcceptMode(QFileDialog.AcceptSave)
             dialog.setOption(QFileDialog.DontConfirmOverwrite, False)
             dialog.setModal(True)
             dialog.filesSelected['QStringList'].connect(
                 self.saveSelectionAs)
         return self._save_sel_as_dialog.exec_() == QDialog.Accepted
     # save selection
     if isinstance(filename, QStringList):
         filename = filename[0]
     filename = str(filename)
     selmodel = self.model.copy()
     sources = [src for src in self.model.sources if src.selected]
     if not sources:
         self.signalShowErrorMessage.emit(
             """You have not selected any sources to save.""")
         return
     # try to determine the file type
     filetype, import_func, export_func, doc = Tigger.Models.Formats.resolveFormat(
         filename, None)
     if export_func is None:
         self.signalShowErrorMessage.emit(
             """Error saving model file %s: unsupported output format""" %
             filename)
         return
     busy = BusyIndicator()
     try:
         export_func(self.model, filename, sources=sources)
     except:
         busy.reset_cursor()
         self.signalShowErrorMessage.emit(
             """Error saving selection to model file %s: %s""" %
             (filename, str(sys.exc_info()[1])))
         return False
     else:
         self.signalShowMessage.emit(
             """Wrote %d selected source%s to file %s""" %
             (len(selmodel.sources),
              "" if len(selmodel.sources) == 1 else "s", filename), 3000)
     finally:
         busy.reset_cursor()
     pass
Example #15
0
 def selectJsonFile(self):
     jsonFile, _ = QFileDialog().getOpenFileName(self, "Select File", "",
                                                 "Json File(*.json)")
     curDir = os.getcwd()
     if jsonFile != '':
         try:
             newPath = shutil.copy(jsonFile, curDir)
         except SameFileError:
             _, file = os.path.split(jsonFile)
             newPath = os.path.join(curDir, file)
         self.LEPathJson.setText(newPath)
def save_file_dialog(parent, filters):
    dlg = QFileDialog()
    options = dlg.Options()
    options |= dlg.DontUseNativeDialog
    filename, _ = dlg.getSaveFileName(parent,
                                      None,
                                      "Save model",
                                      filter=filters,
                                      options=options)
    if filename == "":
        return None
    return filename
Example #17
0
 def _openFileCallback(self):
     if not self._open_file_dialog:
         filters = ";;".join([
             "%s (%s)" % (name, " ".join(patterns))
             for name, patterns, func in self._load_file_types
         ])
         dialog = self._open_file_dialog = QFileDialog(
             self, "Open sky model", ".", filters)
         dialog.setFileMode(QFileDialog.ExistingFile)
         dialog.setModal(True)
         dialog.filesSelected['QStringList'].connect(self.openFile)
     self._open_file_dialog.exec_()
     return
Example #18
0
 def select_batch_files(self):
     """
     Selection of .xml pyIMD project files for batch calculation.
     """
     filter_ext = "XML (*.xml);;, All files (*.*) "
     file_name = QFileDialog()
     file_name.setFileMode(QFileDialog.ExistingFiles)
     ret = file_name.getOpenFileNames(
         self, "Select the pyIMD project files for batch processing",
         self.last_selected_path, filter_ext)
     files = ret[0]
     for i in range(0, len(files)):
         self.batchFileListWidget.addItem(str(files[i]))
Example #19
0
 def select_exe(self):
     '''
     Create a dialog to select the Prince executable
     '''
     dialog = QFileDialog()
     dialog.setFileMode(QFileDialog.ExistingFile)
     filename = dialog.getOpenFileName(self, _('Select Prince executable'),
                                       '', '')
     if filename:
         try:
             self.exe.setText(filename)
         except (TypeError):
             self.exe.setText(filename[0])
 def video2images_set_export_folder(self):
     """
     Set export folder for the video frames.
     :return: Nothing
     """
     file_dialog = QFileDialog()
     f_path = file_dialog.getExistingDirectory(parent=None,
                                               caption="Open Directory",
                                               directory=QDir.homePath(),
                                               options=self.DIALOG_FLAG | QFileDialog.ShowDirsOnly)
     # print(f_path)
     if f_path:
         self.ui_video2images.line_edit_export_images_at.setText(f_path)
         self.ui_video2images.button_compute.setEnabled(self.UP)
Example #21
0
 def getFile(self):
     isImg = None
     lstImg = ['.jpg', '.png', '.jpeg', '.gif', '.tiff', '.bmp']
     filepath, _ = QFileDialog().getOpenFileName(
         self, "Select File", "",
         "Images or pdf(*.png *.jpg *.jpeg *.pdf *.gif *.tiff *.bmp")
     if filepath != '':
         _, formatX = os.path.splitext(filepath)
         formatX = formatX.lower()
         if formatX in lstImg:
             isImg = True
         else:
             isImg = False
     return (isImg, filepath)
Example #22
0
    def _save_pdf(self):  # pragma: no cover
        filename = QFileDialog().getSaveFileName(
            self, self.tr("Export document to PDF"), "",
            self.tr("PDF files (*.pdf)"), options=QFileDialog.ShowDirsOnly)[0]
        if filename:
            if not QFileInfo(filename).suffix():
                filename += ".pdf"

            printer = QPrinter()
            printer.setPageSize(QPrinter.A4)
            printer.setColorMode(QPrinter.Color)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(filename)
            self._doc.text.print_(printer)
Example #23
0
 def save_img_path(self):
     """
     Open the dialog and take the path.
     :return: True/False, path_string/empty_string
     """
     file_dialog = QFileDialog()
     f_path = file_dialog.getSaveFileName(parent=None,
                                          caption="Save Image as",
                                          directory=QDir.homePath(),
                                          filter=self.IMG_FILTER,
                                          initialFilter="",
                                          options=self.DIALOG_FLAG)[0]
     if f_path:
         return True, f_path
     return False, ""
Example #24
0
    def getFile(self):
        pic, _ = QFileDialog().getOpenFileName(self)
        if pic != '':
            format = pic[-3:]
            if format == "pdf":
                #add tags and move the copy to the folder
                self.LWidgetPaths.addItem(pic)
                self.lstPath.append(pic)
                print(pic + ' e PDF')

            elif format in ('jpg', 'png', 'jpeg', 'PNG', 'JPG', 'JPEG'):
                pictOut = self.ResizeToA4(pic=pic)
                picFileName = self.Renaming()
                pictOut.save(picFileName)
                self.LWidgetPaths.addItem(picFileName)
                self.lstPath.append(picFileName)
Example #25
0
    def get_filename_for_save(self):  # pragma: no cover
        filedialog = QFileDialog(self)
        filedialog.setOption(QFileDialog.DontUseNativeDialog)
        filedialog.setAcceptMode(QFileDialog.AcceptSave)

        filedialog.setDirectory(
            self._parent.cfg.get("TextEditor/LastPath", ".", system=True))

        if filedialog.exec_():
            self._file_path = filedialog.selectedFiles()[0]
            self._parent.cfg["SYSTEM",
                             "TextEditor/LastPath"] = (os.path.dirname(
                                 self._file_path))
            return True

        return False
Example #26
0
def export_media_subs_list():

    import_dir = mw.pm.profile.get("importDirectory", "")
    myfilter = "Text (*.txt);;All Files (*.*)"
    save_file_dialog = QFileDialog()
    save_file_path = save_file_dialog.getSaveFileName(mw,
                                                      "Select Filename to Save",
                                                      import_dir + os.sep + "DB with-Sub Media Path List",
                                                      myfilter)[0]
    if save_file_path:
        data_str = ""
        conn = sqlite3.connect(get_path("user_files", "doc.db"))
        for row in conn.execute("select media_path_no_ext||media_ext from subs order by media_path_no_ext"):
            data_str += row[0] + '\n'
        conn.close()
        with open(save_file_path, "w", encoding="utf-8") as f:
            f.write(data_str)
    show_text("Export Completed!")
Example #27
0
 def save_tikz(sel, *args):
     dialog = QFileDialog()
     dialog.setDefaultSuffix(".tex")
     result = dialog.getSaveFileName(self,
                                     QCoreApplication.translate(
                                         "side_widget",
                                         "Save TikZ Output"),
                                     filter="LaTex (*.tex)")
     if result[0]:
         try:
             self.__io_controller.generate_tikz(result[0])
         except Exception:
             logger.exception("Exception while saving tikz")
             box = QMessageBox()
             box.critical(
                 self,
                 QCoreApplication.translate("side_widget", "Error"),
                 QCoreApplication.translate(
                     "side_widget", "Error while writing "
                     "tikz file. "
                     "See log for details."))
Example #28
0
 def saveFileAs(self, filename=None):
     """Saves file using the specified 'filename'. If filename is None, opens dialog to get a filename.
     Returns True if saving succeeded, False on error (or if cancelled by user).
     """
     if filename is None:
         if not self._save_as_dialog:
             filters = ";;".join([
                 "%s (%s)" % (name, " ".join(patterns))
                 for name, patterns, func in self._save_file_types
             ])
             dialog = self._save_as_dialog = QFileDialog(
                 self, "Save sky model", ".", filters)
             dialog.setDefaultSuffix(ModelHTML.DefaultExtension)
             dialog.setFileMode(QFileDialog.AnyFile)
             dialog.setAcceptMode(QFileDialog.AcceptSave)
             dialog.setOption(QFileDialog.DontConfirmOverwrite, True)
             dialog.setModal(True)
             dialog.filesSelected['QStringList'].connect(self.saveFileAs)
         return self._save_as_dialog.exec_() == QDialog.Accepted
     # filename supplied, so save
     return self.saveFile(filename, confirm=False)
def load_file_dialog(parent, filters, multiple_files=False):
    dlg = QFileDialog()
    options = dlg.Options()
    options |= QFileDialog.DontUseNativeDialog
    if multiple_files:
        file_name, _ = dlg.getOpenFileNames(parent,
                                            "Load a model",
                                            "",
                                            filters,
                                            "File WRML (*.wrl)",
                                            options=options)
    else:
        file_name, _ = dlg.getOpenFileName(parent,
                                           "Load a model",
                                           "",
                                           filters,
                                           "File WRML (*.wrl)",
                                           options=options)
    if file_name == "":
        return None
    return file_name
Example #30
0
    def __save_as(self):
        dialog = QFileDialog()
        dialog.setDefaultSuffix(".json")

        result = dialog.getSaveFileName(
            self,
            QCoreApplication.translate("main_window",
                                       "Save Signal-flow Graph"),
            filter="JSON (*.json)")

        if result[0]:
            try:
                self.__io_controller.save_graph(result[0])
                self.__file_path = result[0]
                self.__set_title()
            except Exception:
                logger.exception("Exception while saving to path: %s",
                                 self.__file_path)
                self.__show_error(
                    QCoreApplication.translate("main_window",
                                               "Error while saving file."
                                               " See log for details"))