Ejemplo n.º 1
0
    def importFbx(self):
        #Opens File Dialog
        self.consoleOut("Opening File Prompt...")
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        fbx_fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Select FBX File.",
            "",
            "Filmbox FBX (*fbx);;All Files (*)",
            options=options)

        if fbx_fileName:
            #Debug Line
            print(fbx_fileName)
            #Try importing FBX
            try:
                print("Importing FBX...")
                self.consoleOut("Importing FBX...")
                fbx = hou.hipFile.importFBX(fbx_fileName)
                print("Imported Complete.")
                self.consoleOut("Importing Complete.")
            except:
                print("ERROR_IMPORTING_FBX 001")
                self.consoleOut("ERROR_IMPORTING_FBX_001")
Ejemplo n.º 2
0
    def loadFromFile(self):
        if self.sharedMemory.isAttached():
            self.detach()

        self.ui.label.setText(self.tr("Select an image file"))

        fileName, _ = QFileDialog.getOpenFileName(
            None, "", "", self.tr("Images (*.png *.xpm *.jpg)"))

        image = QImage()
        if not image.load(fileName):
            self.ui.label.setText(
                self.tr(
                    "Selected file is not an image, please select another."))
            return
        self.ui.label.setPixmap(QPixmap.fromImage(image))

        buffer = QBuffer()
        buffer.open(QBuffer.ReadWrite)
        out = QDataStream(buffer)
        out << image
        size = buffer.size()

        if not self.sharedMemory.create(size):
            self.ui.label.setText(
                self.tr("Unable to create shared memory segment."))
            return

        self.sharedMemory.lock()
        size = min(self.sharedMemory.size(), size)
        self.sharedMemory.data()[:size] = buffer.data()[:size]
        self.sharedMemory.unlock()
Ejemplo n.º 3
0
 def loadState(self, filename=None):
     """Load program state from a previous save file"""
     if filename is None:
         tr = self.tr
         filename, _ = QFileDialog.getOpenFileName(
             self,
             tr("Open file"),
             ".",
             filter=tr("PyXPad save file (*.pyx)"))
     if (filename is None) or (filename == ""):
         return  # Cancelled
     if not os.path.exists(filename):
         self.write("Could not find " + filename)
         return
     try:
         with open(filename, "rb") as f:
             self.sources.loadState(f)
             self.data = pickle.load(f)
     except EOFError:
         self.data = OrderedDict()
     except:
         e = sys.exc_info()
         self.write("Could not load state from file '" + filename + "'")
         self.write("\t ->" + str(e[1]))
         raise
     else:
         # If no exception raised, then update tables, lists
         self.data = OrderedDict(self.data)
         self.updateDataTable()
         self.write("** Loaded state from file '" + filename + "'")
 def onImport(self):
     openPath, selectedFilter = QFileDialog.getOpenFileName(
         filter="Subgraph data (*.compound)")
     if openPath != "":
         with open(openPath, 'r') as f:
             data = json.load(f)
             self.assignData(data)
Ejemplo n.º 5
0
 def loadState(self, filename=None):
     """
     Loads program state from the given filename.
     If no filename is specified, then a dialog is created
     to ask the user for a file name.
     """
     if filename is None:
         tr = self.tr
         filename, _ = QFileDialog.getOpenFileName(self, tr('Open file'), '.',
                                                   filter=tr("PyXPad save file (*.pyx)"))
     if (filename is None) or (filename == ""):
         return  # Cancelled
     if not os.path.exists(filename):
         self.write("Could not find " + filename)
         return
     try:
         with open(filename, 'rb') as f:
             self.sources.loadState(f)
             self.data = pickle.load(f)
     except EOFError:
         self.data = OrderedDict()
     except:
         e = sys.exc_info()
         self.write("Could not load state from file '"+filename+"'")
         self.write("\t ->" + str(e[1]))
         raise
     else:
         # If no exception raised, then update tables, lists
         self.data = OrderedDict(self.data)
         self.updateDataTable()
         self.write("** Loaded state from file '"+filename+"'")
Ejemplo n.º 6
0
    def browse_local(self, job):
        #for some reason, this doesn't use the native file browser if i just do QFileDialog
        filename, _ = QFileDialog.getOpenFileName(
            directory=os.path.abspath(job.scratch_dir))

        if filename:
            run(self.session, "open \"%s\"" % filename)
Ejemplo n.º 7
0
def ask_filename():
    # type: () -> Text
    """Ask user for filename.  """
    dummy = application()
    filename, _ = QFileDialog.getOpenFileName(
        None, caption='选择要读取的文件…', filter='*.xlsx')
    return filename
Ejemplo n.º 8
0
 def onImport(self):
     openPath, selectedFilter = QFileDialog.getOpenFileName(filter="Python node data (*.pynode)")
     if openPath != "":
         with open(openPath, 'r') as f:
             dataString = f.read()
             self.tryApplyNodeData(dataString)
         EditorHistory().saveState("Import python node data", modify=True)
Ejemplo n.º 9
0
    def addNetCDF(self):
        """
        Add a NetCDF file as a data source
        """
        try:
            from pyxpad.datafile import NetCDFDataSource
        except ImportError:
            self.main.write("Sorry, no NetCDF support")
            return
        try:
            # Get the file name
            tr = self.main.tr
            fname, _ = QFileDialog.getOpenFileName(
                self.main,
                tr("Open file"),
                ".",
                filter=tr("NetCDF files (*.nc *.cdl)"))
            if (fname is None) or (fname == ""):
                return  # Cancelled

            s = NetCDFDataSource(fname)

            self.addSource(s)
            self.updateDisplay()
        except:
            self.main.write("Error creating NetCDFDataSource")
            self.main.write(str(sys.exc_info()))
Ejemplo n.º 10
0
 def load(self):
     name_filter = "Graph files (*.json)"
     savepath = QFileDialog.getOpenFileName(filter=name_filter)
     if type(savepath) in [tuple, list]:
         fpath = savepath[0]
     else:
         fpath = savepath
     if not fpath == '':
         with open(fpath, 'r') as f:
             data = json.load(f)
             self.loadFromData(data, fpath)
Ejemplo n.º 11
0
 def on_open(self):
     file_path, other = QFileDialog.getOpenFileName(self, "Open File", self.current_dir)
     #print([a for a in dir(QFileDialog) if not a.startswith("_")])
     print("File name: {}, Other: {}".format(file_path, other))
     if file_path:
         dirname = os.path.basename(os.path.dirname(file_path))
         filename = os.path.basename(file_path)
         self.setWindowTitle("{} - {}".format(filename, dirname))
         with open(file_path) as f:
             text = f.read()
             #formatted = markup_python(text)
             #formatted = "<font color=red size=24>{}</font>".format(text)
             self.text_edit.setText(text)
Ejemplo n.º 12
0
def select_file_dialog(title, start_directory=None, pattern=None):
    """
    Shows select file dialog
    :param title: str
    :param start_directory: str
    :param pattern: str
    :return: str
    """

    if not pattern:
        pattern = 'All Files (*.*)'

    return QFileDialog.getOpenFileName(None, title, start_directory, pattern)[0]
Ejemplo n.º 13
0
    def openSlot(self):
        """ Callback from Open button """

        # TODO: Check for edits and prompt to save dirty
        if self.data.filename:
            dirname = os.path.dirname(self.data.filename)
        else:
            dirname = os.getcwd()
        filename = QFileDialog.getOpenFileName(self, "Open particle file", dirname, "(*.bgeo *.geo *.bhclassic *.ptc *.pdb)")
        if filename:
            if isinstance(filename, tuple):
                filename = filename[0]
            self.open(str(filename))
Ejemplo n.º 14
0
    def openSlot(self):
        """ Callback from Open button """

        # TODO: Check for edits and prompt to save dirty
        if self.data.filename:
            dirname = os.path.dirname(self.data.filename)
        else:
            dirname = os.getcwd()
        filename = QFileDialog.getOpenFileName(
            self, "Open particle file", dirname,
            "(*.bgeo *.geo *.bhclassic *.ptc *.pdb)")
        if filename:
            if isinstance(filename, tuple):
                filename = filename[0]
            self.open(str(filename))
Ejemplo n.º 15
0
 def onImport(self):
     openPath, selectedFilter = QFileDialog.getOpenFileName(filter="Subgraph data (*.json)")
     if openPath != "":
         with open(openPath, 'r') as f:
             data = json.load(f)
             data["isRoot"] = False
             data["parentGraphName"] = self._rawNode.rawGraph.parentGraph.name
             missedPackages = set()
             if validateGraphDataPackages(data, missedPackages):
                 data["nodes"] = self.canvasRef().makeSerializedNodesUnique(data["nodes"])
                 self._rawNode.rawGraph.populateFromJson(data)
                 self.canvasRef().createWrappersForGraph(self._rawNode.rawGraph)
                 EditorHistory().saveState("Import compound")
             else:
                 logger.error("Missing dependencies! {0}".format(",".join(missedPackages)))
Ejemplo n.º 16
0
 def _launch_browser(self, *args):
     from Qt.QtWidgets import QFileDialog
     import os
     if self.start_folder is None or not os.path.exists(self.start_folder):
         start_folder = os.getcwd()
     else:
         start_folder = self.start_folder
     file = QFileDialog.getOpenFileName(self.widget, self.browser_title,
                                        start_folder, "All files (*)", "",
                                        QFileDialog.HideNameFilterDetails)
     #file is a tuple of (filename, selected filter)
     #unless no file was selected (e.g. dialog was closed by clicking 'cancel')
     if len(file) == 2:
         self.line_edit.setText(file[0])
         self.line_edit.returnPressed.emit()
Ejemplo n.º 17
0
def get_file(directory, parent=None):
    """
    Show a open file dialog
    :param directory: str, root directory
    :param parent: QWidget
    :return: str, selected folder or None if no folder is selected
    """

    file_dialog = QFileDialog(parent)
    if directory:
        file_dialog.setDirectory(directory)
    directory = file_dialog.getOpenFileName()
    directory = python.force_list(directory)
    if directory:
        return directory
Ejemplo n.º 18
0
def browse_file(self):
    filter_list = 'File({})'.format(' '.join(
        ['*' + e for e in self.filters])) if self.filters else 'Any File(*)'
    if self.multiple:
        r_files, _ = QFileDialog.getOpenFileNames(self, 'Browse Files',
                                                  self.path, filter_list)
        if r_files:
            self.filesChanged.emit(r_files)
            self.path = r_files[0]
    else:
        r_file, _ = QFileDialog.getOpenFileName(self, 'Browse File', self.path,
                                                filter_list)
        if r_file:
            self.fileChanged.emit(r_file)
            self.path = r_file
Ejemplo n.º 19
0
 def doImport(pyFlowInstance):
     name_filter = "Graph files (*.json)"
     openFilename, filterString = QFileDialog.getOpenFileName(
         filter=PythonScriptExporter.name_filter)
     if openFilename != "":
         with open(openFilename, 'r') as f:
             script = f.read()
             mem = Py3CodeCompiler().compile(code=script, scope=globals())
             fileVersion = Version.fromString(mem["EXPORTER_VERSION"])
             if fileVersion >= PythonScriptExporter.version(
             ) and PythonScriptExporter.displayName(
             ) == mem["EXPORTER_NAME"]:
                 pyFlowInstance.newFile()
                 ROOT_GRAPH = pyFlowInstance.graphManager.get(
                 ).findRootGraph()
                 mem["createScene"](ROOT_GRAPH)
                 pyFlowInstance.afterLoad()
Ejemplo n.º 20
0
    def select_geqdsk_file(self):
        """Choose a "geqdsk" equilibrium file to open"""

        filename, _ = QFileDialog.getOpenFileName(self, "Open geqdsk file",
                                                  ".")

        if (filename is None) or (filename == ""):
            return  # Cancelled
        if not os.path.exists(filename):
            self.write("Could not find " + filename)
            self.geqdsk_file_line_edit.setStyleSheet(
                f"QLineEdit {{ background-color: {COLOURS['red']} }}")
            return

        self.geqdsk_file_line_edit.setText(filename)
        self.geqdsk_file_line_edit.setStyleSheet("")

        self.read_geqdsk()
Ejemplo n.º 21
0
    def loadAttributeFile(self):
        fileName, filt = QFileDialog.getOpenFileName(
            caption="Open Attribute File", filter="Attribute File (*.dat)")

        if fileName == "":
            return

        fileObj = open(fileName)
        lines = fileObj.readlines()[3:]
        fileObj.close()
        mapVals = {}

        for line in lines:
            parts = line.split('\t')[1:]
            mapVals[int(parts[0][1:])] = float(parts[1])

        maxValue = max(mapVals.values())
        minValue = min(mapVals.values())
        midValue = (maxValue + minValue) / 2

        # Color from min (blue) to mid (white) to max (red)

        for key in mapVals.keys():
            value = mapVals[key]
            per = (value - minValue) / (midValue - minValue) - 1
            color = abs(per) * 255
            colorSet = [255, 255 - color, 255 - color, 255
                        ] if per > 0 else [255 - color, 255 - color, 255, 255]
            colorSet = array(colorSet)

            self.atomStruct.residues[key - 1].ribbon_color = colorSet
            self.atomStruct.residues[key - 1].atoms.colors = colorSet

        js = "attributeName = '" + fileName.split(
            "/")[-1] + "';updateDisplay()"
        self.html_view.runJavaScript(js)
        self.attributeFile = True

        if self.atomStruct.surfaces() != []:
            run(self.session,
                "color #" + self.atomStruct.surfaces()[0].id_string +
                " fromatoms",
                log=False)
Ejemplo n.º 22
0
    def select_options_file(self):
        """Choose a Hypnotoad options file to load"""

        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "Open options file",
                                                  ".",
                                                  filter=YAML_FILTER)

        if (filename is None) or (filename == ""):
            return  # Cancelled
        if not os.path.exists(filename):
            self.write("Could not find " + filename)
            return

        self.options_file_line_edit.setText(filename)
        self.filename = filename
        self.read_options()
        self.nonorthogonal_box.setChecked(
            not self.options.get("orthogonal", True))
Ejemplo n.º 23
0
    def onFileOpen(self):
        if self.isModified():
            button = QMessageBox.question(
                self,
                self.windowTitle(),
                self.
                tr("You have unsaved changes. Do you want to open a new document anyway?"
                   ),
            )
            if button != QMessageBox.Yes:
                return

        path, _ = QFileDialog.getOpenFileName(self,
                                              self.tr("Open MarkDown File"),
                                              "",
                                              self.tr("MarkDown File (*.md)"))
        if not path:
            return

        self.openFile(path)
Ejemplo n.º 24
0
def get_open_filename(title='Open File',
                      file_dir=None,
                      ext_filter='*',
                      parent=None):
    """
    Opens an open file dialog
    :param title: str
    :param file_dir: str
    :param ext_filter: str
    :param parent: QWidget
    :return: str, selected file path
    """

    file_dir = file_dir or CURRENT_DIR
    file_dialog = QFileDialog.getOpenFileName(parent, title, file_dir,
                                              ext_filter)
    file_path = file_dialog[0] or None
    if file_path:
        set_current_directory(file_path)

    return file_dialog
Ejemplo n.º 25
0
    def addNetCDF(self):
        """
        Add a NetCDF file as a data source
        """
        try:
            from pyxpad.datafile import NetCDFDataSource
        except ImportError:
            self.main.write("Sorry, no NetCDF support")
            return
        try:
            # Get the file name
            tr = self.main.tr
            fname, _ = QFileDialog.getOpenFileName(self.main, tr('Open file'), '.',
                                                   filter=tr("NetCDF files (*.nc *.cdl)"))
            if (fname is None) or (fname == ""):
                return  # Cancelled

            s = NetCDFDataSource(fname)

            self.addSource(s)
            self.updateDisplay()
        except:
            self.main.write("Error creating NetCDFDataSource")
            self.main.write(str(sys.exc_info()))
Ejemplo n.º 26
0
def ask_filename():
    """Ask user for filename.  """

    filename, _ = QFileDialog.getOpenFileName(
        None, caption='选择要读取的文件…', filter='*.xlsx')
    return filename
Ejemplo n.º 27
0
 def setFilename(self):
     filename = QFileDialog.getOpenFileName(self, 'Select File', '',
                                            self.fileFilter)
     if filename:
         self.inputBox.setText(filename)
Ejemplo n.º 28
0
    def openFile(self):
        fileName, filt = QFileDialog.getOpenFileName(
            caption="Open PDB Trajectory File", filter="PDB File (*.pdb)")

        if fileName == "":
            return

        if self.atomStruct != None:
            self.deleteModel()

        # This create a simple Oxygen atom
        # Need to get this to display
        self.atomStruct = AtomicStructure(self.session)

        myFile = open(fileName)

        coords = []
        prevRes = None
        res = None
        modelNum = -1

        for line in myFile:
            if line.startswith("MODEL"):
                modelNum = modelNum + 1
                coords = []
                prevRes = None
                res = None
            elif line.startswith("ENDMDL"):
                self.atomLocation.append(array(coords))
            elif line.startswith("ATOM"):
                x = float(line[30:38].strip())
                y = float(line[38:46].strip())
                z = float(line[46:54].strip())

                name = line[12:16].strip()
                resName = line[17:20].strip()
                chain = line[21]
                resSeq = line[22:26].strip()
                element = line[76:78].strip()

                if element == "H":
                    continue

                coords.append([x, y, z])

                if modelNum != 0:
                    continue

                if resName + resSeq != prevRes:
                    prevRes = resName + resSeq
                    res = self.atomStruct.new_residue(resName, chain,
                                                      int(resSeq))

                atom = self.atomStruct.new_atom(name, element)
                atom.coord = array([x, y, z], dtype=float64)
                res.add_atom(atom)

        myFile.close()
        self.atomStruct.connect_structure()

        self.session.models.add([self.atomStruct])

        for i in range(len(self.atomLocation)):
            self.surfacePositions.append(None)

        self.atomStruct.atoms.coords = self.atomLocation[0]
        fileName = fileName.split("/")[-1]

        js = "modelName = '" + fileName + "'; frameCount = " + str(
            len(self.atomLocation)) + "; reset();"
        self.html_view.runJavaScript(js)
        run(self.session, "lighting full", log=False)
Ejemplo n.º 29
0
 def onImport(self):
     openPath, selectedFilter = QFileDialog.getOpenFileName(filter="Python node data (*.py)")
     if openPath != "":
         with open(openPath, 'r') as f:
             dataString = f.read()
             self.tryApplyNodeData(dataString)