Beispiel #1
0
 def trans(self):
     self.ui.info.setText("正在转换中...")
     in_file = QFileInfo(self.in_file_path)
     out_file = QFileInfo(self.out_file_path)
     encode = self.ui.encode.text()
     if in_file.isFile() and out_file.isFile():
         if self.tr.read_from_file(self.in_file_path, self.out_file_path, encode=encode):
             self.ui.info.setText("转换完成")
         else:
             self.ui.info.setText("文件路径错误或者编码错误")
     else:
         self.ui.info.setText("输入文件路径有误")
Beispiel #2
0
    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(Qt.CopyAction)
            event.accept()
            icon = QIcon("loaded.png")
            for url in event.mimeData().urls():
                if url.isLocalFile():
                    fi = QFileInfo(url.toLocalFile())
                    if fi.isDir():
                        it = QDirIterator(
                            fi.fileName(),
                            QDir.Files,
                            QDirIterator.Subdirectories,
                        )
                        while it.hasNext():
                            item = QListWidgetItem()
                            item.setData(PathRole, it.next())
                            self.addItem(item)
                    elif fi.isFile():
                        item = QListWidgetItem()
                        item.setData(PathRole, url.toLocalFile())
                        self.addItem(item)

        else:
            event.ignore()
Beispiel #3
0
	def Input(filenames):
		"""
Take list of masks or filenames, return list of absolute filepaths, or False if error.
"""
		METHOD_NAME = f"Blister.Input"
		if type(filenames) != type(list()):
			print(f"{METHOD_NAME}: Invalid input type {type(filenames)}. List of strings only.", end='\n')
			return False
		file_list = []
		fileinfo_list = []
		fileinfo_unreadable = []
		for filename in filenames:
			if type(filename) != type(str()):
				print(f"{METHOD_NAME}: Invalid input type {type(filename)} in list. Strings only.", end='\n')
				return False
			file_list += glob.glob(QFileInfo(filename).absoluteFilePath())
		file_list = list(set(file_list))
		file_list.sort()
		for _file in file_list:
			fileinfo = QFileInfo(_file)
			if fileinfo.isFile():
				if fileinfo.isReadable():
					fileinfo_list += [fileinfo.absoluteFilePath()]
				else:
					fileinfo_unreadable += [fileinfo.absoluteFilePath()]
		if fileinfo_unreadable:
			print(f"{METHOD_NAME}: List of unreadable files (will not be processed):", end='\n')
			for fileinfo in fileinfo_unreadable: print(f"\t{fileinfo}", end='\n')
		if not fileinfo_list:
			print(f"{METHOD_NAME}: No input files exist or reachable.", end='\n')
			return False
		print(f"{METHOD_NAME}: List of input files:", end='\n')
		for fileinfo in fileinfo_list: print(f"\t{fileinfo}", end='\n')
		return fileinfo_list
Beispiel #4
0
 def on_btnInfo_isFile_clicked(self):
     self.__showBtnInfo(self.sender())
     fileInfo = QFileInfo(self.ui.editFile.text())
     if fileInfo.isFile():
         self.ui.textEdit.appendPlainText("True \n")
     else:
         self.ui.textEdit.appendPlainText("False \n")
    def readDir(self, dir, readSubs, tiefe, feedback):
        #fileList = [ QFileInfo ]
        #Schleife für alle Einträge des Verzeichnises
        listOfFiles = os.listdir(dir)
        total = 100
        if len(listOfFiles) > 0:
            total = 100.0 / len(listOfFiles)

            #for n,file in enumerate( os.listdir( dir ) ):
            for n, file in enumerate(listOfFiles):

                filePath = (os.path.join(dir, file))
                info = QFileInfo(filePath)
                #print( dir, info.isFile(), info.isDir( ))
                if info.exists() and info.isFile():
                    self.fileList.append(info)
                    #print (info.fileName(), info.size(), info.birthTime(), info.lastModified())
                elif info.exists() and info.isDir() and readSubs == True:
                    # rekursive if Sub Dir
                    self.readDir(filePath, True, tiefe + 1, feedback)
                else:
                    pass
                    #next
                if tiefe == 1:
                    # Update the progress bar in level 1
                    feedback.setProgress(int(n + 1 * total))

        else:
            feedback.setProgress(int(100))
            feedback.pushInfo("No files in directory! " + dir)

            return  #fileList
Beispiel #6
0
    async def dropEventLocalFile(self, ipfsop, url):
        """
        Handle a drop event with a file:// URL
        """

        maxFileSize = megabytes(64)
        try:
            path = url.toLocalFile()
            fileInfo = QFileInfo(path)

            if fileInfo.isFile():
                file = QFile(path)

                if file.open(QIODevice.ReadOnly):
                    size = file.size()

                    if size and size < maxFileSize:
                        logUser.info('Importing file: {0}'.format(path))
                        entry = await ipfsop.addPath(path)
                        if entry:
                            self.tracker.clipboardProcess(entry['Hash'])

                    file.close()
            if fileInfo.isDir():
                # Don't check for directory size
                async def entryAdded(entry):
                    logUser.info('{path}: imported'.format(
                        path=entry.get('Name')))

                entry = await ipfsop.addPath(path, callback=entryAdded)
                if entry:
                    self.tracker.clipboardProcess(entry['Hash'])
        except Exception:
            pass
Beispiel #7
0
 def run(self):
     print('start Guard')
     time.sleep(self.wait_time)
     file_transcript = QFileInfo(self.transcript)
     if file_transcript.isFile():
         print('have transcript')
         self.check_transcript(self.check_interval)
         self.ensure_finish(self.dir)
     else:
         print('Warning: Error, transcript dose not exist')
    def ClickedEvent(self, event):
        validSuffix = ['jpg', 'png']
        index = self.selectedIndexes()[0]
        finfo = QFileInfo(self._model.filePath(index))

        if finfo.suffix().lower() not in validSuffix:
            return

        if finfo.isFile() and finfo.isReadable():
            self.fileSelected.emit(finfo.absoluteFilePath())
Beispiel #9
0
def restore(settings):
    finfo = QFileInfo(settings.fileName())

    if finfo.exists() and finfo.isFile():
        for w in qApp.allWidgets():
            mo = w.metaObject()
            if w.objectName() in ['username_text_box', 'password_text_box', 'forget_password']:
                for i in range(mo.propertyCount()):
                    name = mo.property(i).name()
                    val = settings.value("{}/{}".format(w.objectName(), name), w.property(name))
                    w.setProperty(name, val)
Beispiel #10
0
    def read_BAT(self):
        current_charge = None
        full_capacity = None

        file_BAT0_current = "/sys/class/power_supply/BAT0/charge_now"
        file_info = QFileInfo(file_BAT0_current)
        if file_info.isFile() and file_info.isReadable():
            with open(file_BAT0_current) as bat_file:
                current_charge = bat_file.readline()

        file_BAT0_capacity = "/sys/class/power_supply/BAT0/charge_full"
        file_info_current = QFileInfo(file_BAT0_capacity)
        if file_info_current.isFile() and file_info_current.isReadable():
            with open(file_BAT0_capacity) as bat_file:
                full_capacity = bat_file.readline()

        if current_charge is not None and full_capacity is not None:
            print("FULL: ", current_charge)
            print("FULL: ", full_capacity)

            bat_percentage = int(current_charge) // int(full_capacity)
            print("Percentage: ", (bat_percentage)*100)
Beispiel #11
0
    def open(self, t_filename=None):
        settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "pySPM",
                             "pySPM")
        if t_filename is None:
            home = QDir.cleanPath(os.getenv("HOMEPATH"))
            path = settings.value("lastPath", home)
            self.filename = QFileDialog.getOpenFileName(
                None, "Choose measurement file", path, "*.ita")
        else:
            self.filename = t_filename

        check_file = QFileInfo(self.filename)
        self.setWindowTitle(check_file.fileName())
        if not check_file.exists() or not check_file.isFile():
            return

        settings.setValue("lastPath", check_file.path())
        self.ita = pySPM.ITA(self.filename)
        self.t, self.S = self.ita.getSpectrum(time=True)
        self.sf, self.k0 = self.ita.get_mass_cal()
        self.mass = pySPM.utils.time2mass(self.t, self.sf, self.k0)
        self.spec = self.ax.plot(self.mass, self.S)[0]
        SatLevel = self.ita.size['pixels']['x'] * self.ita.size['pixels'][
            'y'] * self.ita.Nscan
        self.sat_level = self.ax.axhline(SatLevel, color='r')
        if 'pySPM' in self.ita.root.goto("MassScale"):
            self.MassCal = []
            N = self.ita.root.goto("MassScale/pySPM/N").get_ulong()
            for i in range(N):
                elt = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                         "/elt").value.decode('utf8')
                mass = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                          "/mass").get_double()
                time = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                          "/time").get_double()
                self.MassCal.append(dict(elt=elt, mass=mass, time=time))
        else:
            self.MassCal = []
            for x in self.ita.root.goto("MassScale/calib"):
                if x.name == 'assign':
                    self.MassCal.append({'elt': x.get_string()})
                if x.name == 'mcp':
                    mcp = struct.unpack("<10d", x.value)
                    self.MassCal[-1]['time'] = mcp[0]
                    self.MassCal[-1]['mass'] = mcp[1]
        self.DoMassCal()
Beispiel #12
0
    def deleteFile(self):
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        if path:
            fileInfo = QFileInfo(path)
            if fileInfo.isFile():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected file?"):
                    return
                file = QFile(path)
                file.remove()

            elif fileInfo.isDir():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected directory?"):
                    return
                directory = QDir(path)
                directory.removeRecursively()
Beispiel #13
0
    def on_double_clicked(self, index):
        """
        event handler:
        双击工作空间中文件的handler

        Parameters
        ----------
        index : 双击的item在tree_widget中的索引

        """

        # 取得双击的文件路径
        file_info = QFileInfo(self.tree_view.model().fileInfo(index))
        # 告诉线程文件路径,并启动线程
        if file_info.isFile():
            self.file_path = file_info.absoluteFilePath()
            self.worker_calc_overall.file_path = self.file_path
            self.thread_calc_overall.start()
Beispiel #14
0
    def init_config(self):
        """
            Restore if possible all the widgets to their state saved into a given configuration
        """
        # If a configuration has already been saved in a file, get its path
        if self.settings.contains("latest_config"):
            self.config_file_path = self.settings.value("latest_config")

        # Create a Qt info file required to save the state of each widget
        info_file = QFileInfo(self.config_file_path)
        # Initialize the Qt settings file
        self.latest_config = QSettings(self.config_file_path,
                                       QSettings.IniFormat)
        # Introspect all the children widgets and call their restore_config() function
        if info_file.exists() and info_file.isFile():
            widget_names = self.latest_config.childGroups()
            for widget_name in widget_names:
                widget = self.findChild(
                    self.str_to_class(widget_name + "/type"), widget_name)
                widget.restore_config(self.latest_config)
Beispiel #15
0
    def save(self, *args):
        l = len(args)
        if l == 0:
            args = ('')
        if l == 1:
            arg = args[0]
            file = QFileInfo(arg)
            if not file.isFile():
                fileName = self.fileName()
                error = args[0]
            else:
                fileName = arg
                error = ''
            return self.save(fileName, error)
        if l == 2:
            ##
            # Saves the map to the file at \a fileName. Returns whether or not the
            # file was saved successfully. If not, <i>error</i> will be set to the
            # error message if it is not 0.
            #
            # If the save was successful, the file name of this document will be set
            # to \a fileName.
            #
            # The map format will be the same as this map was opened with.
            ##
            fileName, error = args
            mapFormat = self.mWriterFormat

            tmxMapFormat = TmxMapFormat()
            if (not mapFormat):
                mapFormat = tmxMapFormat
            if (not mapFormat.write(self.map(), fileName)):
                if (error):
                    error = mapFormat.errorString()
                return False

            self.undoStack().setClean()
            self.setFileName(fileName)
            self.mLastSaved = QFileInfo(fileName).lastModified()
            self.saved.emit()
            return True
Beispiel #16
0
    def save(self, *args):
        l = len(args)
        if l==0:
            args = ('')
        if l==1:
            arg = args[0]
            file = QFileInfo(arg)
            if not file.isFile():
                fileName = self.fileName()
                error = args[0]
            else:
                fileName = arg
                error = ''
            return self.save(fileName, error)
        if l==2:
            ##
            # Saves the map to the file at \a fileName. Returns whether or not the
            # file was saved successfully. If not, <i>error</i> will be set to the
            # error message if it is not 0.
            #
            # If the save was successful, the file name of this document will be set
            # to \a fileName.
            #
            # The map format will be the same as this map was opened with.
            ##
            fileName, error = args
            mapFormat = self.mWriterFormat
            
            tmxMapFormat = TmxMapFormat()
            if (not mapFormat):
                mapFormat = tmxMapFormat
            if (not mapFormat.write(self.map(), fileName)):
                if (error):
                   error = mapFormat.errorString()
                return False

            self.undoStack().setClean()
            self.setFileName(fileName)
            self.mLastSaved = QFileInfo(fileName).lastModified()
            self.saved.emit()
            return True
Beispiel #17
0
	def Output(filename, output_dir, mod, suffix, rewrite=True, index=-1):
		"""
Take input filename, output dir path, and make a new filename using mod and suffix.
Rewrite a file by default. Can be used with Blister.Threading().
"""
		METHOD_NAME = f"Blister.Output"
		thread_id = Blister.ThreadID(index)
		if mod != "": mod = "_" + mod
		if (suffix != ""): suffix = "." + suffix
		fileinfo_old = QFileInfo(filename)
		fileinfo = QFileInfo(QDir(output_dir), fileinfo_old.baseName() + mod + suffix)
		if (fileinfo.exists() and (not fileinfo.isFile())):
			print(f"{thread_id}{METHOD_NAME}: This path is a dir:\n{thread_id}\t{fileinfo.absoluteFilePath()}", end='\n')
			return False
		if ((fileinfo.exists() and (not fileinfo.isWritable())) or ((not fileinfo.exists()) and (not QFileInfo(fileinfo.absolutePath()).permission(QFile.WriteUser)))):
			print(f"{thread_id}{METHOD_NAME}: Writing this file is not permitted:\n{thread_id}\t{fileinfo.absoluteFilePath()}", end='\n')
			return False
		if (fileinfo.exists() and (rewrite == False)):
			fileinfo = QFileInfo(QDir(output_dir), fileinfo_old.baseName()+ "_" + str(int(time.time()) % 100000) + suffix)
			print(f"{thread_id}{METHOD_NAME}: File to write already exists [rewriting is forbidden]. It will be renamed:\n{thread_id}\t{fileinfo_old.absoluteFilePath()} --> {fileinfo.absoluteFilePath()}", end='\n')
		return fileinfo.absoluteFilePath()
Beispiel #18
0
def getMetadataForFileList(filenames):
    '''Takes a list of filenames, returns a list of metadata associated with
    all files in that list that are readable tracks'''

    metadata = []
    for filename in filenames:
        info = QFileInfo(filename)
        if info.isDir() and info.isExecutable():
            print(filename)
            dir = QDir(filename)
            print(dir.entryList(QDir.AllEntries | QDir.NoDotAndDotDot))
            metadata.extend(
                getMetadataForFileList([
                    i.filePath()
                    for i in dir.entryInfoList(QDir.AllEntries
                                               | QDir.NoDotAndDotDot)
                ]))
        elif info.isFile() and info.isReadable():
            print(filename)
            metadata.extend(processFile(filename))
    return metadata
Beispiel #19
0
 def open(self, t_filename=None):
     settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "pySPM", "pySPM")
     if t_filename is None:
         home = QDir.cleanPath(os.getenv("HOMEPATH"))
         path = settings.value("lastPath", home)
         self.filename = QFileDialog.getOpenFileName(None, "Choose measurement file", path, "*.ita")
     else:
         self.filename = t_filename
     
     check_file = QFileInfo(self.filename)
     self.setWindowTitle(check_file.fileName())
     if not check_file.exists() or  not check_file.isFile():
         return
     
     settings.setValue("lastPath", check_file.path())
     self.ita = pySPM.ITA(self.filename)
     self.t, self.S = self.ita.getSpectrum(time=True)
     self.sf, self.k0 = self.ita.get_mass_cal()
     self.mass = pySPM.utils.time2mass(self.t, self.sf, self.k0)
     self.spec = self.ax.plot(self.mass, self.S)[0]
     SatLevel = self.ita.size['pixels']['x']*self.ita.size['pixels']['y']*self.ita.Nscan
     self.sat_level = self.ax.axhline(SatLevel, color='r')
     if 'pySPM' in self.ita.root.goto("MassScale"):
         self.MassCal = []
         N = self.ita.root.goto("MassScale/pySPM/N").get_ulong()
         for i in range(N):
             elt = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/elt").value.decode('utf8')
             mass = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/mass").get_double()
             time = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/time").get_double()
             self.MassCal.append(dict(elt=elt, mass=mass, time=time))
     else:
         self.MassCal = []
         for x in self.ita.root.goto("MassScale/calib"):
             if x.name == 'assign':
                 self.MassCal.append({'elt':x.get_string()})
             if x.name == 'mcp':
                 mcp = struct.unpack("<10d", x.value)
                 self.MassCal[-1]['time'] = mcp[0]
                 self.MassCal[-1]['mass']  =  mcp[1]
     self.DoMassCal()                    
Beispiel #20
0
    def __init__(self, path, parent = None):
        super().__init__(parent)
        
        self.mPath = path
        self.mUi = Ui_NewTilesetDialog()
        self.mNameWasEdited = False

        self.mUi.setupUi(self)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        # Restore previously used settings
        s = preferences.Preferences.instance().settings()
        tilesetType = s.value(TYPE_KEY, 0)
        colorEnabled = bool(s.value(COLOR_ENABLED_KEY))
        colorName = s.value(COLOR_KEY, '')
        if colorName == '':
            color = Qt.magenta
        else:
            color = QColor(colorName)
        spacing = s.value(SPACING_KEY, 0)
        margin = s.value(MARGIN_KEY, 0)
        self.mUi.tilesetType.setCurrentIndex(tilesetType)
        self.mUi.useTransparentColor.setChecked(colorEnabled)
        self.mUi.colorButton.setColor(color)
        self.mUi.spacing.setValue(spacing)
        self.mUi.margin.setValue(margin)
        self.mUi.browseButton.clicked.connect(self.browse)
        self.mUi.name.textEdited.connect(self.nameEdited)
        self.mUi.name.textChanged.connect(self.updateOkButton)
        self.mUi.image.textChanged.connect(self.updateOkButton)
        self.mUi.tilesetType.currentIndexChanged.connect(self.tilesetTypeChanged)
        # Set the image and name fields if the given path is a file
        fileInfo = QFileInfo(path)
        if (fileInfo.isFile()):
            self.mUi.image.setText(path)
            self.mUi.name.setText(fileInfo.completeBaseName())

        self.mUi.imageGroupBox.setVisible(tilesetType == 0)
        self.updateOkButton()
Beispiel #21
0
    async def importDroppedFileFromUrl(self,
                                       ipfsop,
                                       url,
                                       maxFileSize=2 * 1024 * 1024):
        try:
            path = url.toLocalFile()
            fileInfo = QFileInfo(path)

            if fileInfo.isFile():
                file = QFile(path)

                if file.open(QIODevice.ReadOnly):
                    size = file.size()

                    if size and size < maxFileSize:
                        entry = await ipfsop.addPath(path)
                        file.close()

                        if entry:
                            return entry

                    file.close()
        except Exception:
            pass