Пример #1
0
 def __load(self):
     """
     Private slot to load the available scripts into the manager.
     """
     scriptsDir = QDir(self.scriptsDirectory())
     if not scriptsDir.exists():
         scriptsDir.mkpath(self.scriptsDirectory())
     
     if not scriptsDir.exists("requires"):
         scriptsDir.mkdir("requires")
     
     self.__disabledScripts = \
         Preferences.getHelp("GreaseMonkeyDisabledScripts")
     
     from .GreaseMonkeyScript import GreaseMonkeyScript
     for fileName in scriptsDir.entryList(["*.js"], QDir.Files):
         absolutePath = scriptsDir.absoluteFilePath(fileName)
         script = GreaseMonkeyScript(self, absolutePath)
         
         if script.fullName() in self.__disabledScripts:
             script.setEnabled(False)
         
         if script.startAt() == GreaseMonkeyScript.DocumentStart:
             self.__startScripts.append(script)
         else:
             self.__endScripts.append(script)
Пример #2
0
    def populateTemplates(self):
        self.tree.clear()
        self.tree.setIndentation(0)

        # Add templates
        item = self.addTopLevelItem(self.tr("Fiction"))
        templates = [i for i in self.templates() if i[2] == "Fiction"]
        for t in templates:
            sub = QTreeWidgetItem(item, [t[0]])

        # Add templates: non-fiction
        item = self.addTopLevelItem(self.tr("Non-fiction"))
        templates = [i for i in self.templates() if i[2] == "Non-fiction"]
        for t in templates:
            sub = QTreeWidgetItem(item, [t[0]])


        # Add Demo project
        item = self.addTopLevelItem(self.tr("Demo projects"))
        dir = QDir(appPath("sample-projects"))
        for f in dir.entryList(["*.msk"], filters=QDir.Files):
            sub = QTreeWidgetItem(item, [f[:-4]])
            sub.setData(0, Qt.UserRole, f)

        self.tree.expandAll()
Пример #3
0
 def __installEric6Doc(self, engine):
     """
     Private method to install/update the eric6 help documentation.
     
     @param engine reference to the help engine (QHelpEngineCore)
     @return flag indicating success (boolean)
     """
     versionKey = "eric6_ide"
     info = engine.customValue(versionKey, "")
     lst = info.split('|')
     
     dt = QDateTime()
     if len(lst) and lst[0]:
         dt = QDateTime.fromString(lst[0], Qt.ISODate)
     
     qchFile = ""
     if len(lst) == 2:
         qchFile = lst[1]
     
     docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help")
     
     files = docsPath.entryList(["*.qch"])
     if not files:
         engine.setCustomValue(
             versionKey, QDateTime().toString(Qt.ISODate) + '|')
         return False
     
     for f in files:
         if f == "source.qch":
             fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
             if dt.isValid() and \
                fi.lastModified().toString(Qt.ISODate) == \
                 dt.toString(Qt.ISODate) and \
                qchFile == fi.absoluteFilePath():
                 return False
             
             namespace = QHelpEngineCore.namespaceName(
                 fi.absoluteFilePath())
             if not namespace:
                 continue
             
             if namespace in engine.registeredDocumentations():
                 engine.unregisterDocumentation(namespace)
             
             if not engine.registerDocumentation(fi.absoluteFilePath()):
                 self.errorMessage.emit(
                     self.tr(
                         """<p>The file <b>{0}</b> could not be"""
                         """ registered. <br/>Reason: {1}</p>""")
                     .format(fi.absoluteFilePath, engine.error())
                 )
                 return False
             
             engine.setCustomValue(
                 versionKey,
                 fi.lastModified().toString(Qt.ISODate) + '|' +
                 fi.absoluteFilePath())
             return True
     
     return False
Пример #4
0
    def setDirPath(self, path):
        dir = QDir(path)

        self.beginResetModel()
        self.fileList = dir.entryList()
        self.fileCount = 0
        self.endResetModel()
Пример #5
0
 def run(self):
     #   Lists ISO files in local directory
     root=QDir(self.destination)
     root.setFilter(QDir.AllDirs|QDir.NoDot|QDir.NoDotDot)
     dirs=root.entryList()
     for dir in dirs:
         sub=QDir(self.destination+'/'+dir)
         sub.setNameFilters(["*.iso"])
         sub.setFilter(QDir.Files)
         local=sub.entryList()
         if len(local)!=0:
             for iso in local:
                 isoSize=QFileInfo(sub.absolutePath()+'/' +iso).size()
                 self.localList.append([dir,iso,isoSize])
     #   List the remote directory
     commande = ['rsync', '-avHP', '--list-only',str(self.path)]
     try:
         if self.password != "":
             envir = os.environ.copy()
             envir['RSYNC_PASSWORD']=str(self.password)
             process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE, env=envir)
         else:
             process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE)
     except OSError as e:
         self.lvM.emit(self.tr("Command rsync not found: ")+str(e))
         self.endSignal.emit(1)
         return
     except ValueError as e:
         self.lvM.emit(self.tr("Error in rsync parameters: ")+str(e))
         self.endSignal.emit(2)
         return
     except Exception as e:
         # Unknown error in rsync
         self.lvM.emit(self.tr("Error in rsync: ")+str(e))
         self.endSignal.emit(3)
         return
     process.poll()
     while True :
         item=process.stdout.readline().rstrip().decode('unicode_escape')
         self.lvM.emit(item)
         if str(item.lower()).endswith('.iso') :
             words=item.split()
             self.list.append(words[-1])
         process.poll()
         if process.returncode != None:
             break
     self.endSignal.emit(0)
Пример #6
0
def related_file(FBTS, filename, encoding=None):
    qd = QDir( FBTS.folderpath() )
    qd.setFilter(QDir.Files | QDir.Readable)
    qd.setSorting(QDir.Type | QDir.Reversed)
    qd.setNameFilters( [filename] ) # literal name or 'foo*.*'
    names = qd.entryList()
    if names : # list is not empty, open the first
        a_file = QFile( qd.absoluteFilePath(names[0]) )
        return _qfile_to_stream(a_file, QIODevice.ReadOnly, encoding)
    return None
Пример #7
0
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False):
    dir = QDir()
    dir.setPath(from_dir)

    from_dir += QDir.separator()
    to_dir += QDir.separator()

    if not os.path.exists(to_dir):
        os.makedirs(to_dir)

    for file_ in dir.entryList(QDir.Files):
        from_ = from_dir + file_
        to_ = to_dir + file_
        if str(to_).endswith(".src"):
            to_ = str(to_).replace(".src", "")

        if os.path.exists(to_):
            if replace_on_conflict:
                if not QFile.remove(to_):
                    return False
            else:
                continue

        if not QFile.copy(from_, to_):
            return False

    for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot):
        from_ = from_dir + dir_
        to_ = to_dir + dir_

        if not os.path.exists(to_):
            os.makedirs(to_)

        if not copy_dir_recursive(from_, to_, replace_on_conflict):
            return False

    return True
Пример #8
0
 def __init__(self, parent, dirName):
     """
     Constructor
     
     @param parent parent widget (QWidget)
     @param dirName name of directory to show (string)
     """
     super(IconsPreviewDialog, self).__init__(parent)
     self.setupUi(self)
     
     dir = QDir(dirName)
     for icon in dir.entryList(["*.png"]):
         QListWidgetItem(
             QIcon(os.path.join(dirName, icon)),
             icon, self.iconView)
Пример #9
0
 def loadDirectory(self, dirName):
     """
     Public method to load the search engine definitions from files.
     
     @param dirName name of the directory to load the files from (string)
     @return flag indicating success (boolean)
     """
     if not QFile.exists(dirName):
         return False
     
     success = False
     
     dir = QDir(dirName)
     for name in dir.entryList(["*.xml"]):
         fileName = dir.filePath(name)
         if self.__addEngineByFile(fileName):
             success = True
     
     return success
Пример #10
0
 def __loadFlashCookiesFromPath(self, path):
     """
     Private slot to load the Flash cookies from a path.
     
     @param path Flash cookies path
     @type str
     """
     if path.endswith("#AppContainer"):
         # specific to IE and Windows
         return
     
     path = path.replace("\\", "/")
     solDir = QDir(path)
     entryList = solDir.entryList()
     for entry in entryList:
         if entry == "." or entry == "..":
             continue
         entryInfo = QFileInfo(path + "/" + entry)
         if entryInfo.isDir():
             self.__loadFlashCookiesFromPath(entryInfo.filePath())
         else:
             self.__insertFlashCookie(entryInfo.filePath())
Пример #11
0
def search_dir(base_path, theme_name):
    """ Search for theme name """

    # Search each entry in this directory
    base_dir = QDir(base_path)
    for e in base_dir.entryList():
        # Path to current item
        path = base_dir.path() + "/" + e
        base_filename = e.split('.')[0]

        # If file matches theme name, return
        if base_filename == theme_name:
            return path

        # If this is a directory, search within it
        dir = QDir(path)
        if dir.exists():
            # If found below, return it
            res = search_dir(path, theme_name)
            if res:
                return res

    # If no match found in dir, return None
    return None
Пример #12
0
def listfiles(path):
    # print (QDir.currentPath()+path)
    dir = QDir(path)
    dir.setFilter(QDir.Files | QDir.NoDotAndDotDot)
    print (dir.entryList())
    return dir.entryList()
Пример #13
0
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split("|")

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath) + QDir.separator() + "qch")
        elif version == 5:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath))
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + "|")
            return False

        for f in files:
            if f.startswith(name):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(fi.absoluteFilePath())
                if not namespace:
                    continue

                if (
                    dt.isValid()
                    and namespace in engine.registeredDocumentations()
                    and fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate)
                    and qchFile == fi.absoluteFilePath()
                ):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>"""
                        ).format(fi.absoluteFilePath, engine.error())
                    )
                    return False

                engine.setCustomValue(versionKey, fi.lastModified().toString(Qt.ISODate) + "|" + fi.absoluteFilePath())
                return True

        return False
Пример #14
0
class APISChronology(QDialog, FORM_CLASS):
    def __init__(self, country, parent=None):
        """Constructor."""
        super(APISChronology, self).__init__(parent)
        self.candidateCountry = country
        self.setupUi(self)

        # Initial window size/pos last saved. Use default values for first time
        if GetWindowSize("chronology"):
            self.resize(GetWindowSize("chronology"))
        if GetWindowPos("chronology"):
            self.move(GetWindowPos("chronology"))

        self.settings = QSettings(QSettings().value("APIS/config_ini"),
                                  QSettings.IniFormat)

        self.currentChronology = None
        self.chronologiesDir = None
        self.isSetup = False
        self.uiChronologyCombo.currentIndexChanged.connect(
            self.updateChronology)
        self.accepted.connect(self.onAccepted)
        self.rejected.connect(self.onRejected)

        self.loadAvailableChronologies()

    def loadAvailableChronologies(self):
        self.chronologiesDir = QDir(self.settings.value("APIS/chronology_dir"))
        if self.chronologiesDir.exists():
            chronologiesJsonFiles = self.chronologiesDir.entryList(['*.json'],
                                                                   QDir.Files)
            if len(chronologiesJsonFiles) > 0:
                for chronology in chronologiesJsonFiles:
                    if QFile(
                            os.path.join(self.chronologiesDir.absolutePath(),
                                         chronology)
                    ).exists(
                    ):  # and is chronology json file (find some token to verify)
                        self.uiChronologyCombo.addItem(
                            QFileInfo(chronology).completeBaseName())

                indexCandidate = self.uiChronologyCombo.findText(
                    self.candidateCountry)
                indexDefault = self.uiChronologyCombo.findText(
                    self.settings.value("APIS/default_chronology", "AUT"))
                # QMessageBox.information(self, "Info", "{}, {}, {}".format(self.candidateCountry, indexCandidate, indexDefault))
                if indexCandidate >= 0:
                    self.uiChronologyCombo.setCurrentIndex(indexCandidate)
                elif indexDefault >= 0:
                    self.uiChronologyCombo.setCurrentIndex(indexDefault)
                else:
                    self.uiChronologyCombo.setCurrentIndex(0)
                self.isSetup = True
            else:
                QMessageBox.warning(
                    self, "Keine Chronologien vorhanden",
                    "Im angegebenen Verzeichnis ({0}) sind keine Chronologien vorhanden!"
                    .format(self.chronologiesDir.absolutePath()))
        else:
            QMessageBox.warning(
                self, "Ordner existiert nicht",
                "Das angegebenen Verzeichnis ({0}) existiert nicht!".format(
                    self.chronologiesDir.absolutePath()))

    def nested_dict_iter(self, nested):
        for key, value in nested.items():
            if isinstance(value, Mapping):
                yield from self.nested_dict_iter(value)
            else:
                yield key, value

    def updateChronology(self):
        # QMessageBox.information(self, "Info", "{0}".format(self.sender()))
        chronology = self.sender().currentText()
        fileName = os.path.join(self.chronologiesDir.absolutePath(),
                                "{}.json".format(chronology))
        with open(fileName) as jsonFile:
            data = json.load(jsonFile)
            del data
            # blub = JsonJ(data)
            # QMessageBox.information(self, "Info", json.dumps(blub))
            # if "name" in data and data["name"] == chronology and "children" in data:
            #     for item in data["children"]:
            #         continue
            # else:
            #     QMessageBox.warning(self, "Chronologie JSON Datei fehlerhaft", "Die Chronologie JSON Datei ({0}) ist fehlerhaft!".format(fileName))

    def onAccepted(self):
        SetWindowSizeAndPos("chronology", self.size(), self.pos())

    def onRejected(self):
        SetWindowSizeAndPos("chronology", self.size(), self.pos())
Пример #15
0
    def _perform_migrations(self):
        qry = self.getQuery()
        d = self.getDatabase()

        # check if we can query a version of
        # the schema_changes table, if not possible
        # we likely need to create a completly new db
        if qry.exec(
                "SELECT version FROM schema_changes ORDER BY version DESC LIMIT 1"
        ) and qry.next():
            db_version = int(qry.value(0))
            print(f"Found Database Version to be {db_version}")
        else:
            db_version = -1
            print(
                "Could not determine database version, will create new schema from scratch..."
            )

        # check to see if we can find any migration files
        # we will prefer the ones in sql/*.sql on disk over the ones
        # bundled with qrc for easier development, but the release version
        # will likely use the ones bundled with the applications ressources
        files = glob.glob("sql/*.sql")
        if len(files) == 0:
            # could not find any files on disk in sql subdir
            if QDir(":/sql").exists():
                dir_ = QDir(":/sql")
                dir_.setNameFilters(["*.sql"])
                # in QDir.entryList files will be stripped of path
                # and we also need to append :
                files = [
                    ":/sql/" + x for x in dir_.entryList(filters=QDir.Files)
                ]

        # if the number of files is still zero we could not find any migrations
        # this would be a bug and we can terminate
        if len(files) == 0:
            print(
                "Could not find any Schema Files in sql/*.sql - Please reinstall application."
            )
            print("Exiting now ...")
            sys.exit(1)
        else:
            # next we sort the files in the correct order
            files = sorted(files,
                           key=lambda x: float(re.findall(r"(\d+)", x)[0]))
            # next up, we check the highest migration file version number
            # this should be the last list entry
            # if thats higher than db version we migrate
            # otherwise we return early doing nothing
            highvers = self._get_migrationfile_version(
                os.path.basename(files[-1]))
            if highvers <= db_version:
                print(
                    f"Found highest Version of migration files is {highvers}")
                print("Nothing needs to be migrated.")
                return

            print("Performing outstanding Database migrations...")
            qry.exec(
                "SELECT version, apply_date FROM schema_changes ORDER BY version ASC"
            )
            all_migrations = dict()
            while qry.next():
                all_migrations[qry.value(0)] = qry.value(1)

            d.transaction()
            for file in files:
                scriptname: str = os.path.basename(file)
                file_version = self._get_migrationfile_version(scriptname)

                # if the database version is already higher then the version in the filename
                # we may skip this sql file
                if db_version >= file_version:
                    print(
                        f"Skipping {scriptname}, because migration {file_version} was already applied on {all_migrations.get(file_version, 'NULL')}"
                    )
                else:
                    # otherwise we will execute the sql code and apply the migration
                    try:
                        if file.startswith(":"):
                            fd = QFile(file)
                            fd.open(QFile.ReadOnly | QFile.Text)
                            sql = QTextStream(fd).readAll()
                        else:
                            with open(file, 'rt', encoding='utf-8') as fd:
                                sql = fd.read()
                    except OSError:
                        print(f"Could not open file for reading: {file}")
                        sys.exit(1)
                    finally:
                        if file.startswith(":"):
                            fd.close()

                    # We will have to use sqlparser to split our migration files
                    # into atomic statements since the sqlite qt driver does not
                    # work with multiple stmts in one exec call and offers itself
                    # no alternative like the sqlite3.executescript() that comes
                    # with python3... :(
                    for stmt in sqlparse.split(sql):
                        if not qry.exec(stmt):
                            print(f"Applying {scriptname} to schema failed")
                            print(
                                f"The error appeared with the following statement:"
                            )
                            print(stmt)
                            print(qry.lastError().text())
                            d.rollback()
                            sys.exit(1)

                    if not qry.exec(f"""
                            INSERT INTO schema_changes 
                                (version, scriptname, apply_date)
                            VALUES
                                ({file_version}, '{scriptname}', DATETIME('now'))
                            """):
                        print(qry.lastError().text())
                        d.rollback()
                        sys.exit(1)
                    else:
                        print(f"Successfully applied {scriptname} to schema")

            # if we come this far we've applied all outstanding migrations
            # and can commit all changes to disk
            d.commit()
            print(f"All outstanding db migrations were applied")
            print(f"Database schema is now at version: {file_version}")
Пример #16
0
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split('|')

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(
                QLibraryInfo.location(QLibraryInfo.DocumentationPath) +
                QDir.separator() + "qch")
        elif version == 5:
            docsPath = QLibraryInfo.location(QLibraryInfo.DocumentationPath)
            if (not os.path.isdir(docsPath)
                    or len(QDir(docsPath).entryList(["*.qch"])) == 0):
                # Qt installer is a bit buggy; it's missing a symbolic link
                docsPathList = QDir.fromNativeSeparators(docsPath).split("/")
                docsPath = os.sep.join(
                    docsPathList[:-3] +
                    ["Docs", "Qt-{0}.{1}".format(*qVersionTuple())])
            docsPath = QDir(docsPath)
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey,
                                  QDateTime().toString(Qt.ISODate) + '|')
            return False

        for f in files:
            if f.startswith(name + "."):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(
                    fi.absoluteFilePath())
                if not namespace:
                    continue

                if (dt.isValid()
                        and namespace in engine.registeredDocumentations()
                        and (fi.lastModified().toString(Qt.ISODate)
                             == dt.toString(Qt.ISODate))
                        and qchFile == fi.absoluteFilePath()):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be"""
                            """ registered. <br/>Reason: {1}</p>""").format(
                                fi.absoluteFilePath, engine.error()))
                    return False

                engine.setCustomValue(
                    versionKey,
                    fi.lastModified().toString(Qt.ISODate) + '|' +
                    fi.absoluteFilePath())
                return True

        return False
class UpdateRegistryWorker(QObject):
    '''Background worker for updating Image Registry'''

    finished = pyqtSignal(object)
    error = pyqtSignal(Exception, str)

    def __init__(self):
        QObject.__init__(self)
        self.killed = False
        self.settings = QSettings(QSettings().value("APIS/config_ini"), QSettings.IniFormat)

        # self.registryFile = pluginDir + "\\" + "apis_image_registry.json" #self.settings.value("APIS/image_registry_file", None)

        self.imageDirName = self.settings.value("APIS/image_dir")
        self.orthoDirName = self.settings.value("APIS/ortho_image_dir")
        self.imageDir = QDir(self.imageDirName)
        self.orthoDir = QDir(self.orthoDirName)

        self.imageFormats = self.settings.value("APIS/image_formats", ['jpg'])
        self.hiResFormats = self.settings.value("APIS/hires_formats", ['jpg', 'tif', 'sid', 'nef', 'raf', 'cr2', 'dng'])
        self.orthoFormats = self.settings.value("APIS/ortho_formats", ['jpg', 'tif', 'sid'])

        self.imageFormatsStr = "|".join(self.imageFormats)
        self.hiResFormatsStr = "|".join(self.hiResFormats)
        self.orthoFormatsStr = "|".join(self.orthoFormats)

    def run(self):
        try:
            self.updateImageRegistries()
            self.updateOrthoRegistries()

            if self.killed is False:
                ret = True
                ret = {
                    "imageRegistryNE": self.imageRegistryNE,
                    "hiResRegistryNE": self.hiResRegistryNE,
                    "i2cRegistryNE": self.i2cRegistryNE,
                    "orthoRegistryNE": self.orthoRegistryNE,
                    "mosaicRegistryNE": self.mosaicRegistryNE,
                    "imageRegistry": self.imageRegistry,
                    "hiResRegistry": self.hiResRegistry,
                    "i2cRegistry": self.i2cRegistry,
                    "orthoRegistry": self.orthoRegistry,
                    "mosaicRegistry": self.mosaicRegistry
                }
            else:
                ret = False
        except Exception as e:
            # forward the exception upstream
            self.error.emit(e, traceback.format_exc())
        self.finished.emit(ret)

    def kill(self):
        self.killed = True

    def updateImageRegistries(self):
        self.imageRegistry = []
        self.hiResRegistry = []
        self.i2cRegistry = []

        imageEntryList = self.imageDir.entryList(['??????????'], QDir.Dirs)
        for i in imageEntryList:
            if self.killed is True:
                # kill request received, exit loop early
                break
            iDir = QDir(self.imageDir.path() + '\\' + i)
            # FIXME implement solution for not just jpg but values from ini
            iEntryList = iDir.entryList([i + '_???.jpg'], QDir.Files)
            self.imageRegistry = self.imageRegistry + iEntryList

            hiResDirsEntryList = iDir.entryList(["highres*", "mrsid", "raw"], QDir.Dirs)
            hiResFilters = [i + '_???.' + ext for ext in self.hiResFormats]
            for hr in hiResDirsEntryList:
                if self.killed is True:
                    # kill request received, exit loop early
                    break
                hrDir = QDir(iDir.path() + '\\' + hr)
                hrEntryList = hrDir.entryList(hiResFilters, QDir.Files)
                self.hiResRegistry = self.hiResRegistry + hrEntryList

            i2cDirEntryList = iDir.entryList(["ins2cam"], QDir.Dirs)
            i2cFilters = [i + '_???.' + ext for ext in ['jpg', 'tif', 'tiff']]
            for i2c in i2cDirEntryList:
                if self.killed is True:
                    # kill request received, exit loop early
                    break
                i2cDir = QDir(iDir.path() + '\\' + i2c)
                i2cEntryList = i2cDir.entryList(i2cFilters, QDir.Files)
                self.i2cRegistry = self.i2cRegistry + i2cEntryList

        if self.killed is False:
            self.imageRegistryNE = [img[:14].replace('_', '.') for img in self.imageRegistry]
            self.hiResRegistryNE = [img[:14].replace('_', '.') for img in self.hiResRegistry]
            self.i2cRegistryNE = [img[:14].replace('_', '.') for img in self.i2cRegistry]

    def updateOrthoRegistries(self):
        self.orthoRegistryNE = []
        self.orthoRegistry = []
        self.mosaicRegistryNE = []
        self.mosaicRegistry = []
        orthoEntryList = self.orthoDir.entryList(['??????????'], QDir.Dirs)
        for o in orthoEntryList:
            if self.killed is True:
                # kill request received, exit loop early
                break
            orthoFilters = [o + '_???_op*.' + ext for ext in self.orthoFormats]
            mosaicFilters = [o + '_???_???_op*.' + ext for ext in self.orthoFormats]
            oDir = QDir(self.orthoDir.path() + '\\' + o)
            oEntryList = oDir.entryList(orthoFilters, QDir.Files)
            mEntryList = oDir.entryList(mosaicFilters, QDir.Files)
            #chekc oEntryList if _INT_op
            oEntryList = [img for img in oEntryList if img[11:14].isdigit()]
            #check mEntryList if _INT_INT_op
            mEntryList = [img for img in mEntryList if img[11:14].isdigit() and img[15:18].isdigit()]
            self.orthoRegistry = self.orthoRegistry + oEntryList
            self.mosaicRegistry = self.mosaicRegistry + mEntryList
        if self.killed is False:
            self.orthoRegistryNE = [img[:14].replace('_', '.') for img in self.orthoRegistry]
            self.mosaicRegistryNE = [f"{img[:10]}.{img[11:14]}-{img[15:18]}" for img in self.mosaicRegistry]
Пример #18
0
class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        browseButton = self.createButton("&Browse...", self.browse)
        findButton = self.createButton("&Find", self.find)

        self.fileComboBox = self.createComboBox("*")
        self.textComboBox = self.createComboBox()
        self.directoryComboBox = self.createComboBox(QDir.currentPath())

        fileLabel = QLabel("Named:")
        textLabel = QLabel("Containing text:")
        directoryLabel = QLabel("In directory:")
        self.filesFoundLabel = QLabel()

        self.createFilesTable()

        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch()
        buttonsLayout.addWidget(findButton)

        mainLayout = QGridLayout()
        mainLayout.addWidget(fileLabel, 0, 0)
        mainLayout.addWidget(self.fileComboBox, 0, 1, 1, 2)
        mainLayout.addWidget(textLabel, 1, 0)
        mainLayout.addWidget(self.textComboBox, 1, 1, 1, 2)
        mainLayout.addWidget(directoryLabel, 2, 0)
        mainLayout.addWidget(self.directoryComboBox, 2, 1)
        mainLayout.addWidget(browseButton, 2, 2)
        mainLayout.addWidget(self.filesTable, 3, 0, 1, 3)
        mainLayout.addWidget(self.filesFoundLabel, 4, 0)
        mainLayout.addLayout(buttonsLayout, 5, 0, 1, 3)
        self.setLayout(mainLayout)

        self.setWindowTitle("Find Files")
        self.resize(700, 300)

    def browse(self):
        directory = QFileDialog.getExistingDirectory(self, "Find Files",
                QDir.currentPath())

        if directory:
            if self.directoryComboBox.findText(directory) == -1:
                self.directoryComboBox.addItem(directory)

            self.directoryComboBox.setCurrentIndex(self.directoryComboBox.findText(directory))

    @staticmethod
    def updateComboBox(comboBox):
        if comboBox.findText(comboBox.currentText()) == -1:
            comboBox.addItem(comboBox.currentText())

    def find(self):
        self.filesTable.setRowCount(0)

        fileName = self.fileComboBox.currentText()
        text = self.textComboBox.currentText()
        path = self.directoryComboBox.currentText()

        self.updateComboBox(self.fileComboBox)
        self.updateComboBox(self.textComboBox)
        self.updateComboBox(self.directoryComboBox)

        self.currentDir = QDir(path)
        if not fileName:
            fileName = "*"
        files = self.currentDir.entryList([fileName],
                QDir.Files | QDir.NoSymLinks)

        if text:
            files = self.findFiles(files, text)
        self.showFiles(files)

    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles

    def showFiles(self, files):
        for fn in files:
            file = QFile(self.currentDir.absoluteFilePath(fn))
            size = QFileInfo(file).size()

            fileNameItem = QTableWidgetItem(fn)
            fileNameItem.setFlags(fileNameItem.flags() ^ Qt.ItemIsEditable)
            sizeItem = QTableWidgetItem("%d KB" % (int((size + 1023) / 1024)))
            sizeItem.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            sizeItem.setFlags(sizeItem.flags() ^ Qt.ItemIsEditable)

            row = self.filesTable.rowCount()
            self.filesTable.insertRow(row)
            self.filesTable.setItem(row, 0, fileNameItem)
            self.filesTable.setItem(row, 1, sizeItem)

        self.filesFoundLabel.setText("%d file(s) found (Double click on a file to open it)" % len(files))

    def createButton(self, text, member):
        button = QPushButton(text)
        button.clicked.connect(member)
        return button

    def createComboBox(self, text=""):
        comboBox = QComboBox()
        comboBox.setEditable(True)
        comboBox.addItem(text)
        comboBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        return comboBox

    def createFilesTable(self):
        self.filesTable = QTableWidget(0, 2)
        self.filesTable.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.filesTable.setHorizontalHeaderLabels(("File Name", "Size"))
        self.filesTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.filesTable.verticalHeader().hide()
        self.filesTable.setShowGrid(False)

        self.filesTable.cellActivated.connect(self.openFileOfItem)

    def openFileOfItem(self, row, column):
        item = self.filesTable.item(row, 0)

        QDesktopServices.openUrl(QUrl(self.currentDir.absoluteFilePath(item.text())))
Пример #19
0
class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        browseButton = self.createButton("&Browse...", self.browse)
        self.findButton = self.createButton("&Find", self.find)

        self.fileComboBox = self.createComboBox("*")
        self.textComboBox = self.createComboBox()
        self.directoryComboBox = self.createComboBox(QDir.currentPath())

        fileLabel = QLabel("Named:")
        textLabel = QLabel("Containing text:")
        directoryLabel = QLabel("In directory:")
        self.filesFoundLabel = QLabel()

        self.createFilesTable()

        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch()
        buttonsLayout.addWidget(self.findButton)

        mainLayout = QGridLayout()
        mainLayout.addWidget(fileLabel, 0, 0)
        mainLayout.addWidget(self.fileComboBox, 0, 1, 1, 2)
        mainLayout.addWidget(textLabel, 1, 0)
        mainLayout.addWidget(self.textComboBox, 1, 1, 1, 2)
        mainLayout.addWidget(directoryLabel, 2, 0)
        mainLayout.addWidget(self.directoryComboBox, 2, 1)
        mainLayout.addWidget(browseButton, 2, 2)
        mainLayout.addWidget(self.filesTable, 3, 0, 1, 3)
        mainLayout.addWidget(self.filesFoundLabel, 4, 0)
        mainLayout.addLayout(buttonsLayout, 5, 0, 1, 3)
        self.setLayout(mainLayout)

        self.setWindowTitle("Find Files")
        self.resize(700, 300)

    def browse(self):
        directory = QFileDialog.getExistingDirectory(self, "Find Files",
                QDir.currentPath())

        if directory:
            if self.directoryComboBox.findText(directory) == -1:
                self.directoryComboBox.addItem(directory)

            self.directoryComboBox.setCurrentIndex(self.directoryComboBox.findText(directory))

    @staticmethod
    def updateComboBox(comboBox):
        if comboBox.findText(comboBox.currentText()) == -1:
            comboBox.addItem(comboBox.currentText())

    def find(self):
        self.filesTable.setRowCount(0)

        fileName = self.fileComboBox.currentText()
        text = self.textComboBox.currentText()
        path = self.directoryComboBox.currentText()

        self.updateComboBox(self.fileComboBox)
        self.updateComboBox(self.textComboBox)
        self.updateComboBox(self.directoryComboBox)

        self.currentDir = QDir(path)
        if not fileName:
            fileName = "*"
        files = self.currentDir.entryList([fileName],
                QDir.Files | QDir.NoSymLinks)

        if text:
            files = self.findFiles(files, text)
        self.showFiles(files)

    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles

    def showFiles(self, files):
        for fn in files:
            file = QFile(self.currentDir.absoluteFilePath(fn))
            size = QFileInfo(file).size()

            fileNameItem = QTableWidgetItem(fn)
            fileNameItem.setFlags(fileNameItem.flags() ^ Qt.ItemIsEditable)
            sizeItem = QTableWidgetItem("%d KB" % (int((size + 1023) / 1024)))
            sizeItem.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            sizeItem.setFlags(sizeItem.flags() ^ Qt.ItemIsEditable)

            row = self.filesTable.rowCount()
            self.filesTable.insertRow(row)
            self.filesTable.setItem(row, 0, fileNameItem)
            self.filesTable.setItem(row, 1, sizeItem)

        self.filesFoundLabel.setText("%d file(s) found (Double click on a file to open it)" % len(files))

    def createButton(self, text, member):
        button = QPushButton(text)
        button.clicked.connect(member)
        return button

    def createComboBox(self, text=""):
        comboBox = QComboBox()
        comboBox.setEditable(True)
        comboBox.addItem(text)
        comboBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        return comboBox

    def createFilesTable(self):
        self.filesTable = QTableWidget(0, 2)
        self.filesTable.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.filesTable.setHorizontalHeaderLabels(("File Name", "Size"))
        self.filesTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.filesTable.verticalHeader().hide()
        self.filesTable.setShowGrid(False)

        self.filesTable.cellActivated.connect(self.openFileOfItem)

    def openFileOfItem(self, row, column):
        item = self.filesTable.item(row, 0)

        QDesktopServices.openUrl(QUrl(self.currentDir.absoluteFilePath(item.text())))
Пример #20
0
    def findQmFiles(self):
        trans_dir = QDir('translations')
        fileNames = trans_dir.entryList(['*.qm'], QDir.Files, QDir.Name)

        return [trans_dir.filePath(fn) for fn in fileNames]
Пример #21
0
 def _vcsCheckout(self, export=False):
     """
     Protected slot used to create a local project from the repository.
     
     @param export flag indicating whether an export or a checkout
             should be performed
     """
     if not self.project or not self.project.checkDirty():
         return
     
     vcsSystemsDict = e5App().getObject(
         "PluginManager").getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(vcsSystemsDict.keys())
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         QCoreApplication.translate("VcsProjectHelper", "New Project"),
         QCoreApplication.translate(
             "VcsProjectHelper",
             "Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     
     selectedVcsSystem = None
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             selectedVcsSystem = vcsSystem
             break
     
     if not self.project.closeProject():
         return
     
     vcs = self.project.initVCS(selectedVcsSystem)
     if vcs is not None:
         vcsdlg = vcs.vcsNewProjectOptionsDialog()
         if vcsdlg.exec_() == QDialog.Accepted:
             projectdir, vcsDataDict = vcsdlg.getData()
             # edit VCS command options
             if vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     QCoreApplication.translate(
                         "VcsProjectHelper", "New Project"),
                     QCoreApplication.translate(
                         "VcsProjectHelper",
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     vcs.vcsSetOptions(codlg.getOptions())
             
             # create the project directory if it doesn't exist already
             if not os.path.isdir(projectdir):
                 try:
                     os.makedirs(projectdir)
                 except EnvironmentError:
                     E5MessageBox.critical(
                         self.parent(),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "Create project directory"),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "<p>The project directory <b>{0}</b> could not"
                             " be created.</p>").format(projectdir))
                     self.project.resetVCS()
                     return
             
             # create the project from the VCS
             vcs.vcsSetDataFromDict(vcsDataDict)
             if export:
                 ok = vcs.vcsExport(vcsDataDict, projectdir)
             else:
                 ok = vcs.vcsCheckout(vcsDataDict, projectdir, False)
             if ok:
                 projectdir = os.path.normpath(projectdir)
                 filters = ["*.e4p"]
                 d = QDir(projectdir)
                 plist = d.entryInfoList(filters)
                 if len(plist):
                     if len(plist) == 1:
                         self.project.openProject(
                             plist[0].absoluteFilePath())
                     else:
                         pfilenamelist = d.entryList(filters)
                         pfilename, ok = QInputDialog.getItem(
                             None,
                             QCoreApplication.translate(
                                 "VcsProjectHelper",
                                 "New project from repository"),
                             QCoreApplication.translate(
                                 "VcsProjectHelper",
                                 "Select a project file to open."),
                             pfilenamelist, 0, False)
                         if ok:
                             self.project.openProject(
                                 QFileInfo(d, pfilename).absoluteFilePath())
                     if export:
                         self.project.pdata["VCS"] = 'None'
                         self.project.vcs = self.project.initVCS()
                         self.project.setDirty(True)
                         self.project.saveProject()
                 else:
                     res = E5MessageBox.yesNo(
                         self.parent(),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "New project from repository"),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "The project retrieved from the repository"
                             " does not contain an eric project file"
                             " (*.e4p). Create it?"),
                         yesDefault=True)
                     if res:
                         self.project.ppath = projectdir
                         self.project.opened = True
                         
                         from Project.PropertiesDialog import (
                             PropertiesDialog
                         )
                         dlg = PropertiesDialog(self.project, False)
                         if dlg.exec_() == QDialog.Accepted:
                             dlg.storeData()
                             self.project.initFileTypes()
                             self.project.pdata["VCS"] = selectedVcsSystem
                             self.project.setDirty(True)
                             if self.project.pdata["MAINSCRIPT"]:
                                 ms = os.path.join(
                                     self.project.ppath,
                                     self.project.pdata["MAINSCRIPT"])
                                 if os.path.exists(ms):
                                     self.project.appendFile(ms)
                             else:
                                 ms = ""
                             self.project.newProjectAddFiles(ms)
                             self.project.createProjectManagementDir()
                             self.project.saveProject()
                             self.project.openProject(self.project.pfile)
                             if not export:
                                 res = E5MessageBox.yesNo(
                                     self.parent(),
                                     QCoreApplication.translate(
                                         "VcsProjectHelper",
                                         "New project from repository"),
                                     QCoreApplication.translate(
                                         "VcsProjectHelper",
                                         "Shall the project file be added"
                                         " to the repository?"),
                                     yesDefault=True)
                                 if res:
                                     self.project.vcs.vcsAdd(
                                         self.project.pfile)
             else:
                 E5MessageBox.critical(
                     self.parent(),
                     QCoreApplication.translate(
                         "VcsProjectHelper", "New project from repository"),
                     QCoreApplication.translate(
                         "VcsProjectHelper",
                         """The project could not be retrieved from"""
                         """ the repository."""))
                 self.project.resetVCS()
Пример #22
0
    def __init__(self, install_directory):
        QWizardPage.__init__(self)
        self.install_directory = install_directory
        self.setTitle(
            QCoreApplication.translate("SiteWizard", "Site Information"))
        self.setSubTitle(
            QCoreApplication.translate(
                "SiteWizard",
                "Specify basic information about the site for which you "
                "want to generate site files."))
        self.setPixmap(QWizard.LogoPixmap, QPixmap(":/images/icon64.png"))

        self.siteNameLabel = QLabel(
            QCoreApplication.translate("SiteWizard", "&Site title:"))
        self.siteNameLineEdit = QLineEdit()
        self.siteNameLabel.setBuddy(self.siteNameLineEdit)
        self.siteNameLineEdit.setPlaceholderText(
            QCoreApplication.translate("SiteWizard", "Site title"))

        self.descriptionLabel = QLabel(
            QCoreApplication.translate("SiteWizard", "&Description:"))
        self.descriptionLineEdit = QLineEdit()
        self.descriptionLabel.setBuddy(self.descriptionLineEdit)
        self.descriptionLineEdit.setPlaceholderText(
            QCoreApplication.translate("SiteWizard", "Site description"))

        self.copyrightLabel = QLabel(
            QCoreApplication.translate("SiteWizard", "&Copyright"))
        self.copyrightLineEdit = QLineEdit()
        self.copyrightLabel.setBuddy(self.copyrightLineEdit)
        self.copyrightLineEdit.setPlaceholderText(
            QCoreApplication.translate(
                "SiteWizard", "&copy 2022 YourCompany. All Rights Reserved."))

        self.themeLabel = QLabel(
            QCoreApplication.translate("SiteWizard", "&Theme"))
        self.theme = QComboBox()
        self.themeLabel.setBuddy(self.theme)

        themesDir = QDir(os.path.join(install_directory, "themes"))
        for theme in themesDir.entryList(QDir.NoDotAndDotDot | QDir.Dirs):
            self.theme.addItem(theme)

        self.registerField("siteName*", self.siteNameLineEdit)
        self.registerField("description", self.descriptionLineEdit)
        self.registerField("copyright", self.copyrightLineEdit)
        self.registerField("theme", self.theme, "currentText")

        self.warning = QLabel("")
        self.warning.setStyleSheet("QLabel  color : orange ")

        layout = QGridLayout()
        layout.addWidget(self.siteNameLabel, 0, 0)
        layout.addWidget(self.siteNameLineEdit, 0, 1)
        layout.addWidget(self.descriptionLabel, 1, 0)
        layout.addWidget(self.descriptionLineEdit, 1, 1)
        layout.addWidget(self.copyrightLabel, 2, 0)
        layout.addWidget(self.copyrightLineEdit, 2, 1)
        layout.addWidget(self.themeLabel, 3, 0)
        layout.addWidget(self.theme, 3, 1)
        layout.addWidget(self.warning, 4, 0, 1, 2)
        self.setLayout(layout)
        self.siteNameLineEdit.textChanged.connect(self.siteNameChanged)
        self.setAutoFillBackground(True)
Пример #23
0
    def beginFinalInit(self):
        """
        @see: startup
        Notice the __init__ method . we just setup the basic widget.
        And after the language , style ,plugins etc had loaded .
        we call this method . 
        
        Never call it unless you know what's it
        """
        #when at linux platform . the icon is not visible at menu .
        for key in self.__actions.keys():
            self.__actions.get(key).setIconVisibleInMenu(True)
            
        #--------------->>Seeking init <<-----------------#
        # __init__ menu
        self.getMenu("settings").addAction(self.getAction("perferences"))
        
        
        #i18n , must restart program to make it in use
        action_languages = QAction(QIcon(getPath('iconDir','languages.png')),QApplication.translate("default", "Languages"),self)
        action_languages.setIconVisibleInMenu(True)
        menu_languages = QMenu(self)
        
        trans_dir = QDir(getPrccisePath("transDir","","coredir"))
        fileNames = trans_dir.entryList(['i18n*.qm'], QDir.Files,QDir.Name)
        qmFiles = [trans_dir.filePath(fn) for fn in fileNames]
    
        for qmf in qmFiles: 
            translator = QTranslator() 
            translator.load(qmf)
            action = menu_languages.addAction(translator.translate("default", "English"))
            action.triggered.connect(lambda re,locale=translator.translate("default", "locale"):self.__evt_changeLanguage(locale))
        
        action_languages.setMenu(menu_languages)
        self.getMenu("settings").addAction(action_languages)
        
        #style menu use signalmapper
        action_style = QAction(QIcon(getPath('iconDir','style.png')),QApplication.translate("default", "Style"),self)
        action_style.setIconVisibleInMenu(True)
        menu_style = QMenu(self)
        for style_item in QStyleFactory.keys():
            action = menu_style.addAction(style_item)
            action.triggered.connect(lambda re,style_item=style_item:changeStyle(style_item))
        action_style.setMenu(menu_style)
        self.getMenu("settings").addAction(action_style)
        
        menu_plugin = self.getMenu("plugins")
        
        menu_plugin.addAction(self.getAction("plguinInfos"))
        
        menu_plugin.addSeparator()
        menu_plugin.addAction(self.getAction("plguinRequest"))
        
        #--------------->>Seeking init <<-----------------#
        # __init__ toolbar
        toolBar = self.addToolBar(QApplication.translate("default","common"))
        
        toolBar.addAction(self.getAction("perferences"))
        toolBar.addAction(self.getAction("close"))
        toolBar.addAction(self.getAction("gotohome"))
        toolBar.addAction(self.getAction("help"))
        
        #--------------->>Seeking init <<-----------------#
        # __init__ status bar
        self.statusBar().showMessage("Seeking ...")
        
        
        #--------------->>Seeking init <<-----------------#
        #Effects of a loading progress .
        #Results appear in the tab of the interior, the window has no effect on the global
        self.overlay = Overlay(self.centralWidget())
        self.overlay.hide()

        #--------------->>Seeking init <<-----------------#
        #other
        self.emit(SIGNAL('updateWindows()'))
Пример #24
0
 def setUp(self):
     options = ParserHelper()
     self.form = breezeconfig.MainWindow(options)
     dir = QDir(self.form.schemeDir)
     self.files = dir.entryList(dir, dir.Files)
     self.confFile = Path(Path.home() / ".config/kdeglobals")
Пример #25
0
def sampleQrCodes():
    dir = QDir(':/share/qr-codes')
    if dir.exists():
        for entry in dir.entryList():
            yield entry, QFile(':/share/qr-codes/{}'.format(entry))
Пример #26
0
class LayoutBox(QVBoxLayout):
    def __init__(self):
        super().__init__()
        self.profileGroup = QGroupBox("Profile")
        self.profileLabel = QLabel("none")
        self.profileSelect = QPushButton("Open...")
        self.profileSelect.clicked.connect(self.openProfileClick)
        self.profileSave = QPushButton("Save")
        self.profileSave.clicked.connect(self.saveProfileClick)
        self.profileSave.setEnabled(False)
        self.profileBox = QHBoxLayout()
        self.profileBox.addWidget(self.profileLabel)
        self.profileBox.addStretch()
        self.profileBox.addWidget(self.profileSelect)
        self.profileBox.addWidget(self.profileSave)
        self.profileGroup.setLayout(self.profileBox)

        self.filesBox = FilesBox()
        self.filesBox.buttonBox.setEnable(False)  #
        self.filesBox.availableTweaks.setEnabled(False)  #
        self.filesBox.selectedTweaks.setEnabled(False)  #

        self.filesBox.availableTweaks.itemClicked.connect(self.availClick)
        self.filesBox.selectedTweaks.itemClicked.connect(self.selectClick)

        self.descriptionGroup = QGroupBox("Tweak description")
        self.descriptionGroup.setMinimumHeight(50)
        self.description = QLabel("")
        self.description.setTextInteractionFlags(Qt.TextInteractionFlags(5))

        self.descriptionBox = QHBoxLayout()
        self.descriptionBox.addWidget(self.description)
        self.descriptionGroup.setLayout(self.descriptionBox)

        self.addWidget(self.profileGroup)
        self.addItem(self.filesBox)
        self.addWidget(self.descriptionGroup)
        self.profileDir = QDir()
        self.profilePathDialog = QFileDialog()
        self.profilePath = ""
        self.appDir = QDir().current()

    def openProfileClick(self):
        #Button Open... click
        self.profilePath = self.profilePathDialog.getExistingDirectory(
            self.profileSelect, "Select Firefox profile")
        # self.profilePath = "~/Library/Application Support/Firefox/Profiles/rpk2uobe.default"
        logging.debug("Selected directory: \"%s\"", self.profilePath)
        if self.profilePath != "":
            self.selectedProfile = QDir(self.profilePath)
            self.firefoxDir = QDir(self.profilePath)
            logging.debug("Selected profile qdir: %s",
                          self.selectedProfile.path())
            self.firefoxDir.cdUp()
            self.profilesFile = QFile(self.firefoxDir.path() + "/profiles.ini")
            logging.debug("Profiles file: %s", self.profilesFile.fileName())
            logging.debug("Profiles file exists: %s",
                          self.profilesFile.exists())
            logging.debug("Firefox folder: %s", self.firefoxDir.dirName())
            # Basic check if parent directory is named 'firefox' and contains a file named 'profiles.ini'
            #if self.firefoxDir.dirName() == "firefox" and self.profilesFile.exists():
            if True:
                self.profilePath = self.profilePath
                self.profileLabel.setText(self.profilePath)

                self.filesBox.buttonBox.setEnable(True)
                self.filesBox.availableTweaks.setEnabled(True)
                self.filesBox.selectedTweaks.setEnabled(True)
                self.profileSave.setEnabled(True)

                self.profileDir.setPath(self.profilePath)
                logging.debug("Profile dirs: %s", self.profileDir.entryList())
                self.userChrome = QFile(
                    self.profilePath + "/chrome/userChrome.css")
                self.userFFSettings = QFile(
                    self.profilePath + "/chrome/userFirefox.json")
                logging.debug("userChrome exists: %s",
                              self.userChrome.exists())
                if self.userChrome.exists(
                ) and not self.userFFSettings.exists():
                    self.backupChrome = QMessageBox()
                    self.backupChrome.setIcon(QMessageBox.Question)
                    self.backupChrome.setText(
                        "userChrome.css file already exists in this profile. This may be overwritten. Do you want to make a backup?"
                    )
                    self.backupChrome.setStandardButtons(
                        QMessageBox.StandardButtons(81920))  #yes, no
                    self.backupChrome.exec()
                    logging.debug("Dialog result: %s",
                                  self.backupChrome.result())
                    if self.backupChrome.result() == 16384:  #yes
                        logging.debug("Backing up userChrome")
                        self.backupDone = QMessageBox()
                        self.backupFile = QFile(
                            self.profilePath + "/chrome/userChrome.css~")
                        logging.debug("Backup file: %s",
                                      self.backupFile.fileName())
                        logging.debug("Backup exists: %s",
                                      self.backupFile.exists())
                        if self.backupFile.exists():
                            logging.debug("Backup already exists")
                            self.backupDone.setIcon(QMessageBox.Warning)
                            self.backupDone.setText(
                                "Backup already exists. The file was NOT overwritten and new backup not made."
                            )
                        else:
                            if self.userChrome.copy(self.profilePath +
                                                    "/chrome/userChrome.css~"):
                                self.backupDone.setIcon(
                                    QMessageBox.Information)
                                self.backupDone.setText(
                                    "Backed up to 'userChrome.css~'")
                            else:
                                self.backupDone.setIcon(QMessageBox.Critical)
                                self.backupDone.setText("Backing up failed.")
                        self.backupDone.exec()
                    elif self.backupChrome.result() == 65536:  #no
                        logging.debug("Not backing up userChome")
                # Load existing settings
                try:
                    with open(self.profilePath + "/chrome/userFirefox.json"
                              ) as uFP:
                        savedTweaks = json.load(uFP)
                    logging.debug("Loaded json settings: %s", savedTweaks)
                    for loadedTweak in savedTweaks:
                        logging.debug(
                            "Loaded tweak. check: %i, category: %s, name: %s",
                            loadedTweak["Enabled"], loadedTweak["Category"],
                            loadedTweak["Name"])
                        tweakCat = loadedTweak["Category"]
                        tweakName = loadedTweak["Name"]
                        self.filesBox.tweaksAdded[
                            tweakCat + tweakName] = QTreeWidgetItem(
                                self.filesBox.selectedTweaks)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setCheckState(
                                                      0,
                                                      loadedTweak["Enabled"])
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      1, tweakCat)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      2, tweakName)
                except FileNotFoundError:
                    pass
                self.filesBox.resizeColumns()
            else:
                self.noProfile = QMessageBox()
                self.noProfile.setIcon(QMessageBox.Warning)
                self.noProfile.setText(
                    "The selected directory does not appear to be a valid Firefox profile. Profiles are usually located at '~/.mozilla/firefox/xxxx' and is most likely a hidden directory."
                )
                self.noProfile.exec()

    def availClick(self):
        if self.filesBox.availableTweaks.currentItem().parent() is not None:
            tweakName = self.filesBox.availableTweaks.currentItem().text(0)
            tweakCat = self.filesBox.availableTweaks.currentItem().parent(
            ).text(0)
            self.showDesc(tweakCat, tweakName)

    def selectClick(self):
        try:
            tweakName = self.filesBox.selectedTweaks.currentItem().text(2)
            tweakCat = self.filesBox.selectedTweaks.currentItem().text(1)
            self.showDesc(tweakCat, tweakName)
        except:
            pass

    def showDesc(self, category, name):
        logging.debug("Showing description for %s/%s: ", category, name)
        currentDir = QDir().current().path()
        tweakPath = currentDir + "/" + category + "/" + name
        logging.debug("Loading %s", tweakPath)
        tweakDesc = ""
        descLines = 0
        with open(tweakPath) as tweakContent:
            for line in tweakContent:
                if (re.search("^(\/\* ?)|( \* ?)|( \*\/)", line) is not None):
                    if len(line) > 3:
                        trimmedLine = line[3:]
                        tweakDesc += trimmedLine
                        descLines += 1
                else:
                    break
        logging.debug("Description: %s", tweakDesc)
        self.description.setText(tweakDesc)
        logging.debug("Desc lines: %i", descLines)

    def saveProfileClick(self):
        logging.debug("Saving profile")
        self.saveQuestion = QMessageBox()
        self.saveQuestion.setIcon(QMessageBox.Question)
        self.saveQuestion.setStandardButtons(
            QMessageBox.StandardButtons(81920))  #yes, no
        self.saveQuestion.setText(
            "Do you want to apply selected tweaks and overwrite userChrome?")
        self.saveQuestion.exec()
        self.saveCSS = ""
        if self.saveQuestion.result() == 16384:  #yes
            logging.debug("Saving userChrome")
            selTweaksNumber = self.filesBox.selectedTweaks.topLevelItemCount()
            savingTweaks = []
            for i in range(selTweaksNumber):
                currentSavingTweak = self.filesBox.selectedTweaks.topLevelItem(
                    i)
                currentSavingData = {}
                currentSavingData["Enabled"] = currentSavingTweak.checkState(0)
                currentSavingData["Category"] = currentSavingTweak.text(1)
                currentSavingData["Name"] = currentSavingTweak.text(2)
                logging.debug("Tweak cat %s, name %s, selected %s",
                              currentSavingData["Category"],
                              currentSavingData["Name"],
                              currentSavingData["Enabled"])
                savingTweaks.append(currentSavingData)
                if currentSavingData["Enabled"] == 2:
                    with open(self.appDir.path() + "/" +
                              currentSavingData["Category"] + "/" +
                              currentSavingData["Name"]) as twkFile:
                        self.saveCSS += twkFile.read() + "\n"
            logging.debug("Selected tweaks: %s", savingTweaks)
            with open(self.profilePath + "/chrome/userFirefox.json",
                      "w") as fp:
                json.dump(savingTweaks, fp)
            logging.debug("userChrome.css: %s", self.saveCSS)
            with open(self.profilePath + "/chrome/userChrome.css", "w") as fp:
                fp.write(self.saveCSS)
        elif self.saveQuestion.result() == 65536:  #no
            logging.debug("Not saving userChrome.")
Пример #27
0
    def findQmFiles(self):
        trans_dir = QDir(':/translations')
        fileNames = trans_dir.entryList(['*.qm'], QDir.Files, QDir.Name)

        return [trans_dir.filePath(fn) for fn in fileNames]
def availableStl():
    qDir = QDir(STL_DIR, '*.stl')
    return qDir.entryList(QDir.Files)
Пример #29
0
    def beginFinalInit(self):
        """
        @see: startup
        Notice the __init__ method . we just setup the basic widget.
        And after the language , style ,plugins etc had loaded .
        we call this method . 
        
        Never call it unless you know what's it
        """
        #when at linux platform . the icon is not visible at menu .
        for key in self.__actions.keys():
            self.__actions.get(key).setIconVisibleInMenu(True)

        #--------------->>Seeking init <<-----------------#
        # __init__ menu
        self.getMenu("settings").addAction(self.getAction("perferences"))

        #i18n , must restart program to make it in use
        action_languages = QAction(
            QIcon(getPath('iconDir', 'languages.png')),
            QApplication.translate("default", "Languages"), self)
        action_languages.setIconVisibleInMenu(True)
        menu_languages = QMenu(self)

        trans_dir = QDir(getPrccisePath("transDir", "", "coredir"))
        fileNames = trans_dir.entryList(['i18n*.qm'], QDir.Files, QDir.Name)
        qmFiles = [trans_dir.filePath(fn) for fn in fileNames]

        for qmf in qmFiles:
            translator = QTranslator()
            translator.load(qmf)
            action = menu_languages.addAction(
                translator.translate("default", "English"))
            action.triggered.connect(lambda re, locale=translator.translate(
                "default", "locale"): self.__evt_changeLanguage(locale))

        action_languages.setMenu(menu_languages)
        self.getMenu("settings").addAction(action_languages)

        #style menu use signalmapper
        action_style = QAction(QIcon(getPath('iconDir', 'style.png')),
                               QApplication.translate("default", "Style"),
                               self)
        action_style.setIconVisibleInMenu(True)
        menu_style = QMenu(self)
        for style_item in QStyleFactory.keys():
            action = menu_style.addAction(style_item)
            action.triggered.connect(
                lambda re, style_item=style_item: changeStyle(style_item))
        action_style.setMenu(menu_style)
        self.getMenu("settings").addAction(action_style)

        menu_plugin = self.getMenu("plugins")

        menu_plugin.addAction(self.getAction("plguinInfos"))

        menu_plugin.addSeparator()
        menu_plugin.addAction(self.getAction("plguinRequest"))

        #--------------->>Seeking init <<-----------------#
        # __init__ toolbar
        toolBar = self.addToolBar(QApplication.translate("default", "common"))

        toolBar.addAction(self.getAction("perferences"))
        toolBar.addAction(self.getAction("close"))
        toolBar.addAction(self.getAction("gotohome"))
        toolBar.addAction(self.getAction("help"))

        #--------------->>Seeking init <<-----------------#
        # __init__ status bar
        self.statusBar().showMessage("Seeking ...")

        #--------------->>Seeking init <<-----------------#
        #Effects of a loading progress .
        #Results appear in the tab of the interior, the window has no effect on the global
        self.overlay = Overlay(self.centralWidget())
        self.overlay.hide()

        #--------------->>Seeking init <<-----------------#
        #other
        self.emit(SIGNAL('updateWindows()'))
Пример #30
0
 def _vcsCheckout(self, export=False):
     """
     Protected slot used to create a local project from the repository.
     
     @param export flag indicating whether an export or a checkout
             should be performed
     """
     if not self.project.checkDirty():
         return
     
     vcsSystemsDict = e5App().getObject("PluginManager")\
         .getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(vcsSystemsDict.keys())
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         self.tr("New Project"),
         self.tr("Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             break
     
     if not self.project.closeProject():
         return
     
     self.project.pdata["VCS"] = [vcsSystem]
     self.project.vcs = self.project.initVCS(vcsSystem)
     if self.project.vcs is not None:
         vcsdlg = self.project.vcs.vcsNewProjectOptionsDialog()
         if vcsdlg.exec_() == QDialog.Accepted:
             projectdir, vcsDataDict = vcsdlg.getData()
             self.project.pdata["VCS"] = [vcsSystem]
             self.project.vcs = self.project.initVCS(vcsSystem)
             # edit VCS command options
             if self.project.vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     self.tr("New Project"),
                     self.tr(
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(self.project.vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     self.project.vcs.vcsSetOptions(codlg.getOptions())
             
             # create the project directory if it doesn't exist already
             if not os.path.isdir(projectdir):
                 try:
                     os.makedirs(projectdir)
                 except EnvironmentError:
                     E5MessageBox.critical(
                         self.parent(),
                         self.tr("Create project directory"),
                         self.tr(
                             "<p>The project directory <b>{0}</b> could not"
                             " be created.</p>").format(projectdir))
                     self.project.pdata["VCS"] = ['None']
                     self.project.vcs = self.project.initVCS()
                     return
             
             # create the project from the VCS
             self.project.vcs.vcsSetDataFromDict(vcsDataDict)
             if export:
                 ok = self.project.vcs.vcsExport(vcsDataDict, projectdir)
             else:
                 ok = self.project.vcs.vcsCheckout(vcsDataDict, projectdir,
                                                   False)
             if ok:
                 projectdir = os.path.normpath(projectdir)
                 filters = ["*.e4p"]
                 d = QDir(projectdir)
                 plist = d.entryInfoList(filters)
                 if len(plist):
                     if len(plist) == 1:
                         self.project.openProject(
                             plist[0].absoluteFilePath())
                         self.project.newProject.emit()
                     else:
                         pfilenamelist = d.entryList(filters)
                         pfilename, ok = QInputDialog.getItem(
                             None,
                             self.tr("New project from repository"),
                             self.tr("Select a project file to open."),
                             pfilenamelist, 0, False)
                         if ok:
                             self.project.openProject(
                                 QFileInfo(d, pfilename).absoluteFilePath())
                             self.project.newProject.emit()
                     if export:
                         self.project.pdata["VCS"] = ['None']
                         self.project.vcs = self.project.initVCS()
                         self.project.setDirty(True)
                         self.project.saveProject()
                 else:
                     res = E5MessageBox.yesNo(
                         self.parent(),
                         self.tr("New project from repository"),
                         self.tr(
                             "The project retrieved from the repository"
                             " does not contain an eric project file"
                             " (*.e4p). Create it?"),
                         yesDefault=True)
                     if res:
                         self.project.ppath = projectdir
                         self.project.opened = True
                         
                         from Project.PropertiesDialog import \
                             PropertiesDialog
                         dlg = PropertiesDialog(self.project, False)
                         if dlg.exec_() == QDialog.Accepted:
                             dlg.storeData()
                             self.project.initFileTypes()
                             self.project.setDirty(True)
                             try:
                                 ms = os.path.join(
                                     self.project.ppath,
                                     self.project.pdata["MAINSCRIPT"][0])
                                 if os.path.exists(ms):
                                     self.project.appendFile(ms)
                             except IndexError:
                                 ms = ""
                             self.project.newProjectAddFiles(ms)
                             self.project.createProjectManagementDir()
                             self.project.saveProject()
                             self.project.openProject(self.project.pfile)
                             if not export:
                                 res = E5MessageBox.yesNo(
                                     self.parent(),
                                     self.tr(
                                         "New project from repository"),
                                     self.tr(
                                         "Shall the project file be added"
                                         " to the repository?"),
                                     yesDefault=True)
                                 if res:
                                     self.project.vcs.vcsAdd(
                                         self.project.pfile)
             else:
                 E5MessageBox.critical(
                     self.parent(),
                     self.tr("New project from repository"),
                     self.tr(
                         """The project could not be retrieved from"""
                         """ the repository."""))
                 self.project.pdata["VCS"] = ['None']
                 self.project.vcs = self.project.initVCS()
         else:
             self.project.pdata["VCS"] = ['None']
             self.project.vcs = self.project.initVCS()
Пример #31
0
ERROR_REPORT_STABLE_VERSION = None

try:
    from language import openshot_lang
    language_path = ":/locale/"
except ImportError:
    language_path = os.path.join(PATH, 'language')
    print("Compiled translation resources missing!")
    print("Loading translations from: {}".format(language_path))

# Compile language list from :/locale resource
try:
    from PyQt5.QtCore import QDir
    langdir = QDir(language_path)
    trpaths = langdir.entryList(
        ['OpenShot_*.qm'],
        QDir.NoDotAndDotDot | QDir.Files,
        sort=QDir.Name)
    for trpath in trpaths:
        # Extract everything between "Openshot_" and ".qm"
        lang=trpath[trpath.find('_')+1:-3]
        SUPPORTED_LANGUAGES.append(lang)
except ImportError:
    # Fail gracefully if we're running without PyQt5 (e.g. CI tasks)
    pass

SETUP = {
    "name": NAME,
    "version": VERSION,
    "author": JT["name"] + " and others",
    "author_email": JT["email"],
    "maintainer": JT["name"],
Пример #32
0
class gmIdGUIWindow(QtWidgets.QMainWindow):
    # intialize, define all the signals and constants
    def __init__(self):
        # change pyqtgraph setting
        pg.setConfigOption('background', 'w')
        # Create UI Interface
        super(gmIdGUIWindow, self).__init__()
        self.ui = Ui_GmIdMainWindow()
        self.ui.setupUi(self)
        # Initialize the Data
        self.configDataLib()
        # Connect buttons and checkBoxes
        self.configBondKeys()
        # Set the plot
        self.configPlot()

    def configBondKeys(self):
        ''' connect GUI elements to corresponding functions'''
        #checkBox.stateChanged.connect()
        self.ui.checkBoxCornerTT.stateChanged.connect(self.PlotCornerTT)
        self.ui.checkBoxCornerFF.stateChanged.connect(self.PlotCornerFF)
        self.ui.checkBoxCornerSS.stateChanged.connect(self.PlotCornerSS)
        self.ui.checkBoxCornerFS.stateChanged.connect(self.PlotCornerFS)
        self.ui.checkBoxCornerSF.stateChanged.connect(self.PlotCornerSF)
        self.ui.checkBoxRef.stateChanged.connect(self.PlotRef)
        #pushButton.clicked.connect()
        self.ui.pushButtonMosDirSel.clicked.connect(self.DirSel)
        self.ui.pushButtonMosMatSet.clicked.connect(self.MosMatSet)
        self.ui.pushButtonGateLSet.clicked.connect(self.GateLSet)
        self.ui.pushButtonGateLRef.clicked.connect(self.GateLRef)
        self.ui.pushButtonPlot.clicked.connect(self.PlotUpdate)
        self.ui.pushButtonSynGmId.clicked.connect(self.SynGmId)
        self.ui.pushButtonSynVstar.clicked.connect(self.SynVstar)
        self.ui.pushButtonFuEst.clicked.connect(self.FuEst)
        self.ui.pushButtonExtCheck.clicked.connect(self.ExtCheck)
        self.ui.pushButtonCal.clicked.connect(self.CalMos)
        #comboBox.currentIndexChanged.connect()
        self.ui.comboBoxDesignCorner.currentIndexChanged.connect(
            self.changeCorner)

    def configPlot(self):
        # vstar as x axis
        self.ui.topPlotVstar.plotItem.showGrid(True, True, 0.7)
        self.ui.topPlotVstar.plotItem.setTitle('Fig.1 Id vs Vstar')
        self.ui.topPlotVstar.plotItem.setLabel('bottom', 'Vstar', units='V')
        self.ui.topPlotVstar.plotItem.setLabel('left', 'Id', units='A')
        self.ui.topPlotVstar.plotItem.setLogMode(False, True)
        self.ui.midPlotVstar.plotItem.showGrid(True, True, 0.7)
        self.ui.midPlotVstar.plotItem.setLabel('bottom', 'Vstar', units='V')
        self.ui.midPlotVstar.plotItem.setTitle('Fig.2 Avo vs Vstar')
        self.ui.midPlotVstar.plotItem.setLabel('left', 'Avo')
        self.ui.botPlotVstar.plotItem.showGrid(True, True, 0.7)
        self.ui.botPlotVstar.plotItem.setLabel('bottom', 'Vstar', units='V')
        self.ui.botPlotVstar.plotItem.setTitle('Fig.3 Ft vs Vstar')
        self.ui.botPlotVstar.plotItem.setLabel('left', 'Ft', units='Hz')
        # id as x axis
        self.ui.topPlotId.plotItem.showGrid(True, True, 0.7)
        self.ui.topPlotId.plotItem.setTitle('Fig.1 Gm/Id vs Id')
        self.ui.topPlotId.plotItem.setLabel('bottom', 'Id', units='A')
        self.ui.topPlotId.plotItem.setLabel('left', 'Gm/Id', units='S/A')
        self.ui.midPlotId.plotItem.showGrid(True, True, 0.7)
        self.ui.midPlotId.plotItem.setLabel('bottom', 'Id', units='A')
        self.ui.midPlotId.plotItem.setTitle('Fig.2 Avo vs Id')
        self.ui.midPlotId.plotItem.setLabel('left', 'Avo')
        self.ui.botPlotId.plotItem.showGrid(True, True, 0.7)
        self.ui.botPlotId.plotItem.setLabel('bottom', 'Id', units='A')
        self.ui.botPlotId.plotItem.setTitle('Fig.3 Ft*Gm/Id vs Id')
        self.ui.botPlotId.plotItem.setLabel('left', 'Ft*Gm/Id', units='Hz/V')
        # gmId as x axis
        self.ui.topPlotGmId.plotItem.showGrid(True, True, 0.7)
        self.ui.topPlotGmId.plotItem.setTitle('Fig.1 Id vs GmId')
        self.ui.topPlotGmId.plotItem.setLabel('bottom', 'GmId', units='V')
        self.ui.topPlotGmId.plotItem.setLabel('left', 'Id', units='A')
        self.ui.midPlotGmId.plotItem.showGrid(True, True, 0.7)
        self.ui.midPlotGmId.plotItem.setLabel('bottom', 'GmId', units='V')
        self.ui.midPlotGmId.plotItem.setTitle('Fig.2 Avo vs GmId')
        self.ui.midPlotGmId.plotItem.setLabel('left', 'Avo')
        self.ui.botPlotGmId.plotItem.showGrid(True, True, 0.7)
        self.ui.botPlotGmId.plotItem.setLabel('bottom', 'GmId', units='V')
        self.ui.botPlotGmId.plotItem.setTitle('Fig.3 Ft vs GmId')
        self.ui.botPlotGmId.plotItem.setLabel('left', 'Ft', units='Hz')
        # L as x axis
        self.ui.topLPlotL.plotItem.showGrid(True, True, 0.7)
        self.ui.topLPlotL.plotItem.setTitle('Fig.1 Vth vs L')
        self.ui.topLPlotL.plotItem.setLabel('bottom', 'L', units='um')
        self.ui.topLPlotL.plotItem.setLabel('left', 'Vth', units='V')
        # Pen & Line
        self.redLinePen = pg.mkPen('r', width=1.5, style=QtCore.Qt.DashLine)
        self.yellowLinePen = pg.mkPen('y', width=1.5, style=QtCore.Qt.DashLine)
        self.blueLinePen = pg.mkPen('b', width=1.5, style=QtCore.Qt.DashLine)
        self.dashPen = pg.mkPen('r', width=1.5, style=QtCore.Qt.DashLine)
        self.topVLineVstar = pg.InfiniteLine(angle=90,
                                             pen=self.redLinePen,
                                             movable=False)
        self.midVLineVstar = pg.InfiniteLine(angle=90,
                                             pen=self.redLinePen,
                                             movable=False)
        self.botVLineVstar = pg.InfiniteLine(angle=90,
                                             pen=self.redLinePen,
                                             movable=False)
        self.topVLineId = pg.InfiniteLine(angle=90,
                                          pen=self.yellowLinePen,
                                          movable=False)
        self.midVLineId = pg.InfiniteLine(angle=90,
                                          pen=self.yellowLinePen,
                                          movable=False)
        self.botVLineId = pg.InfiniteLine(angle=90,
                                          pen=self.yellowLinePen,
                                          movable=False)
        self.topVLineGmId = pg.InfiniteLine(angle=90,
                                            pen=self.blueLinePen,
                                            movable=False)
        self.midVLineGmId = pg.InfiniteLine(angle=90,
                                            pen=self.blueLinePen,
                                            movable=False)
        self.botVLineGmId = pg.InfiniteLine(angle=90,
                                            pen=self.blueLinePen,
                                            movable=False)
        self.topHLineVstar = pg.InfiniteLine(angle=0,
                                             pen=self.redLinePen,
                                             movable=False)
        self.topHLineGmId = pg.InfiniteLine(angle=0,
                                            pen=self.blueLinePen,
                                            movable=False)
        self.ui.topPlotVstar.addItem(self.topVLineVstar, ignoreBounds=True)
        self.ui.midPlotVstar.addItem(self.midVLineVstar, ignoreBounds=True)
        self.ui.botPlotVstar.addItem(self.botVLineVstar, ignoreBounds=True)
        self.ui.topPlotVstar.addItem(self.topHLineVstar, ignoreBounds=True)
        self.ui.topPlotGmId.addItem(self.topVLineGmId, ignoreBounds=True)
        self.ui.midPlotGmId.addItem(self.midVLineGmId, ignoreBounds=True)
        self.ui.botPlotGmId.addItem(self.botVLineGmId, ignoreBounds=True)
        self.ui.topPlotGmId.addItem(self.topHLineGmId, ignoreBounds=True)
        #self.arrowFt = pg.ArrowItem(angle=90, tipAngle=30, baseAngle=20, headLen=20, tailLen=None, pen={'color': 'w', 'width': 3})
        #self.arrowAvo = pg.ArrowItem(angle=90, tipAngle=30, baseAngle=20, headLen=20, tailLen=None, pen={'color': 'w', 'width': 3})
        #self.arrowFt.setPos(0,0)
        #self.arrowAvo.setPos(0,0)
        #self.ui.botPlotVstar.addItem(self.arrowFt)
        #self.ui.midPlotVstar.addItem(self.arrowAvo)
        self.ui.topPlotVstar.scene().sigMouseMoved.connect(
            self.topMouseMovedVstar)
        self.ui.topPlotGmId.scene().sigMouseMoved.connect(
            self.topMouseMovedGmId)

    def configDataLib(self):
        # MOS Transistor
        self.L = 0.18
        self.Lref = 0.18
        # MOS Transistor
        self.W = 10.0
        self.GmId = 10.0
        self.Gm = 10.0
        self.Id = 1.0
        self.VDS = 0.9
        self.VSB = 0.1
        # Calculation MOS Transistor
        self.synW = 10.0
        self.synVGS = 0.9
        self.synGmId = 5.0
        self.synGm = 5.0
        self.synId = 1.0
        # Calculation MOS Transistor
        self.calW = 10.0
        self.calGmId = 5.0
        self.calId = 1.0
        self.calVGS = 0.9
        # Process
        self.tgtCorner = 0
        #avaiable corner: TT, FF, SS, FS, SF
        self.listCorner = ["tt", "ff", "ss", "fs", "sf"]
        self.avaCorner = [0, 0, 0, 0, 0]
        self.mosCorner = [None, None, None, None, None]
        self.mosDat = None
        # Data
        self.listL = []
        self.listId = []
        self.listGmId = []
        self.listVstar = []
        self.listFt = []
        self.listFOM = []
        self.listAvo = []
        self.listVth = []
        self.pltId = None
        self.pltGmId = None
        self.pltVstar = None
        self.pltFt = None
        self.pltFOM = None
        self.pltAvo = None
        self.pltIdG = None
        self.pltFtG = None
        self.pltAvoG = None
        self.EnFom = 0
        # Range of vstar, gmid
        self.minVstar = 0.08
        self.maxVstar = 1.0
        self.minGmId = 2.0
        self.maxGmId = 25.0
        # Curve for L
        self.curveIdFit = None
        self.curveFtFit = None
        self.curveAvoFit = None
        self.curveIdCorner = [None, None, None, None, None]
        self.curveFtCorner = [None, None, None, None, None]
        self.curveAvoCorner = [None, None, None, None, None]
        self.curveIdFitG = None
        self.curveFtFitG = None
        self.curveAvoFitG = None
        self.curveIdCornerG = [None, None, None, None, None]
        self.curveFtCornerG = [None, None, None, None, None]
        self.curveAvoCornerG = [None, None, None, None, None]
        self.curveGmFitI = None
        self.curveFomFitI = None
        self.curveAvoFitI = None
        self.curveGmCornerI = [None, None, None, None, None]
        self.curveFomCornerI = [None, None, None, None, None]
        self.curveAvoCornerI = [None, None, None, None, None]
        # Curve for Lref
        self.curveIdFitRef = None
        self.curveFtFitRef = None
        self.curveAvoFitRef = None
        self.curveIdCornerRef = [None, None, None, None, None]
        self.curveFtCornerRef = [None, None, None, None, None]
        self.curveAvoCornerRef = [None, None, None, None, None]
        self.curveIdFitGRef = None
        self.curveFtFitGRef = None
        self.curveAvoFitGRef = None
        self.curveIdCornerGRef = [None, None, None, None, None]
        self.curveFtCornerGRef = [None, None, None, None, None]
        self.curveAvoCornerGRef = [None, None, None, None, None]
        self.curveGmFitIRef = None
        self.curveFomFitIRef = None
        self.curveAvoFitIRef = None
        self.curveGmCornerIRef = [None, None, None, None, None]
        self.curveFomCornerIRef = [None, None, None, None, None]
        self.curveAvoCornerIRef = [None, None, None, None, None]
        # Curve as function of L
        self.curveVth = None
        self.curveVthCorner = [None, None, None, None, None]
        # Pen Style for Pyqtgraph
        self.plotColor = pg.hsvColor(time.time() / 5 % 1, alpha=.5)
        self.cornerPen = [None, None, None, None, None]
        self.cornerPen[0] = pg.mkPen(color=(119, 172, 48),
                                     width=1.5,
                                     style=QtCore.Qt.DotLine)
        self.cornerPen[1] = pg.mkPen(color=(0, 114, 189),
                                     width=1.5,
                                     style=QtCore.Qt.DotLine)
        self.cornerPen[2] = pg.mkPen(color=(126, 47, 142),
                                     width=1.5,
                                     style=QtCore.Qt.DotLine)
        self.cornerPen[3] = pg.mkPen(color=(217, 83, 25),
                                     width=1.5,
                                     style=QtCore.Qt.DotLine)
        self.cornerPen[4] = pg.mkPen(color=(237, 177, 32),
                                     width=1.5,
                                     style=QtCore.Qt.DotLine)
        self.linePen = [None, None, None, None, None]
        self.linePen[0] = pg.mkPen(color=(119, 172, 48), width=2)
        self.linePen[1] = pg.mkPen(color=(0, 114, 189), width=2)
        self.linePen[2] = pg.mkPen(color=(126, 47, 142), width=2)
        self.linePen[3] = pg.mkPen(color=(217, 83, 25), width=2)
        self.linePen[4] = pg.mkPen(color=(237, 177, 32), width=2)
        self.dotPen = pg.mkPen(self.plotColor,
                               width=2,
                               style=QtCore.Qt.DotLine)
        self.symbolStyle = 'o'
        # Flag for State
        self.arrowPos = 0
        self.curveReady = 0
        self.desLSet = 0
        self.refLSet = 0

    # checkBox Functions
    def PlotCornerTT(self, state):
        if self.avaCorner[0] == 1:
            if state == Qt.Checked:
                self.visibleCurve(0, True)
            else:
                self.visibleCurve(0, False)
        else:
            self.ui.labelLog.setText('No Data Available')

    def PlotCornerFF(self, state):
        if self.avaCorner[1] == 1:
            if state == Qt.Checked:
                self.visibleCurve(1, True)
            else:
                self.visibleCurve(1, False)
        else:
            self.ui.labelLog.setText('No Data Available')

    def PlotCornerSS(self, state):
        if self.avaCorner[2] == 1:
            if state == Qt.Checked:
                self.visibleCurve(2, True)
            else:
                self.visibleCurve(2, False)
        else:
            self.ui.labelLog.setText('No Data Available')

    def PlotCornerFS(self, state):
        if self.avaCorner[3] == 1:
            if state == Qt.Checked:
                self.visibleCurve(3, True)
            else:
                self.visibleCurve(3, False)
        else:
            self.ui.labelLog.setText('No Data Available')

    def PlotCornerSF(self, state):
        if self.avaCorner[4] == 1:
            if state == Qt.Checked:
                self.visibleCurve(4, True)
            else:
                self.visibleCurve(4, False)
        else:
            self.ui.labelLog.setText('No Data Available')

    def PlotRef(self, state):
        if self.refLSet == 1:
            if state == Qt.Checked:
                self.visibleRef(True)
            else:
                self.visibleRef(False)
        else:
            self.ui.labelLog.setText('No Ref Curve')

    # pushButton Functions
    def DirSel(self):
        '''Select the Directory for the Data'''
        self.matDirPath = QFileDialog.getExistingDirectory()
        self.matDir = QDir(self.matDirPath)
        self.matDir.setFilter(QtCore.QDir.Files)
        self.matFileList = self.matDir.entryList()
        self.ui.listWidgetMat.clear()
        for i in range(len(self.matFileList)):
            if self.matFileList[i][0] == '.':
                continue
            self.ui.listWidgetMat.addItem(self.matFileList[i])

    def MosMatSet(self):
        self.matItem = self.ui.listWidgetMat.currentItem()
        if self.matItem == None:
            self.ui.labelLog.setText('No MOS Data Set')
        else:
            self.matFilePath = self.matDirPath + '/' + self.matItem.text()
            self.matFileName = self.matItem.text().split('.')[0]
            self.matFileInfo = self.matFileName.split('_')
            self.ui.titleMosCharData.setText(self.matFileName)
            self.loadMat()

    def GateLSet(self):
        self.gateLItem = self.ui.listWidgetL.currentItem()
        if self.gateLItem == None:
            self.ui.labelLog.setText('No Gate Length Set')
        else:
            self.L = float(self.gateLItem.text())
            self.ui.labelGateL.setText(self.gateLItem.text())
            self.desLSet = 1

    def GateLRef(self):
        self.gateLRefItem = self.ui.listWidgetLRef.currentItem()
        if self.gateLRefItem == None:
            self.ui.labelLog.setText('No Ref Gate Length')
        else:
            self.Lref = float(self.gateLRefItem.text())
            self.ui.labelGateLRef.setText(self.gateLRefItem.text())
            self.refLSet = 1

    def PlotUpdate(self):
        if self.desLSet == 0:
            self.ui.labelLog.setText('No Des Gate Length')
        elif self.refLSet == 0:
            self.ui.labelLog.setText('No Ref Gate Length')
        else:
            self.cornerMat()

    def PlotOff(self):
        if self.avaCorner[0] == 1:
            self.ui.checkBoxCornerTT.setCheckState(2)
            self.ui.checkBoxCornerTT.setCheckState(0)
        if self.avaCorner[1] == 1:
            self.ui.checkBoxCornerFF.setCheckState(2)
            self.ui.checkBoxCornerFF.setCheckState(0)
        if self.avaCorner[2] == 1:
            self.ui.checkBoxCornerSS.setCheckState(2)
            self.ui.checkBoxCornerSS.setCheckState(0)
        if self.avaCorner[3] == 1:
            self.ui.checkBoxCornerFS.setCheckState(2)
            self.ui.checkBoxCornerFS.setCheckState(0)
        if self.avaCorner[4] == 1:
            self.ui.checkBoxCornerSF.setCheckState(2)
            self.ui.checkBoxCornerSF.setCheckState(0)
        if self.refLSet == 1:
            self.ui.checkBoxRef.setCheckState(2)
            self.ui.checkBoxRef.setCheckState(0)

    def SynGmId(self):
        self.synGmId = float(self.ui.lineEditSynGmId.text())
        self.SynMos()

    def SynVstar(self):
        self.synGmId = 2 / float(self.ui.lineEditSynVstar.text())
        self.SynMos()

    def CalMos(self):
        self.UpdateBias()
        self.calVGS = float(self.ui.lineEditCalVgs.text())
        self.calGmId = lp.lookupfz(self.mosDat,
                                   'nch',
                                   'GMOVERID',
                                   VDS=self.VDS,
                                   VSB=self.VSB,
                                   L=self.L,
                                   VGS=self.calVGS)
        self.calId = lp.lookupfz(self.mosDat,
                                 'nch',
                                 'ID',
                                 VDS=self.VDS,
                                 VSB=self.VSB,
                                 L=self.L,
                                 VGS=self.calVGS) * self.calW / self.W
        self.ui.labelCalGmId.setText('%2.2f' % self.calGmId)
        self.ui.labelCalId.setText('%2.2f' % self.calId)

    def FuEst(self):
        pass

    def ExtCheck(self):
        pass

    # Background functions
    def UpdateBias(self):
        self.VDS = float(self.ui.spinBoxBiasVds.value()) * 0.001
        self.VSB = -float(self.ui.spinBoxBiasVbs.value()) * 0.001

    def SynMos(self):
        '''Syn MOS from Gm'''
        self.UpdateBias()
        self.synGm = float(self.ui.lineEditSynGm.text())
        self.synId = self.synGm / self.synGmId
        self.synW = lp.lookupfz(self.mosDat,
                                'nch',
                                'ID',
                                VDS=self.VDS,
                                VSB=self.VSB,
                                L=self.L,
                                VGS=self.synVGS) * self.W / self.synId
        print('Width : %1.2f' % self.synW)

    def SearchVGS(self):
        vgsStart = 0
        vgsEnd = 1.8
        gmIdSeq = None
        vgsStep = [0.1, 0.01, 0.001]
        vgsLeft = 0
        for i in range(3):
            vgsSeq = np.arange(vgsStart, vgsEnd, vgsStep[i])
            gmIdSeq = lp.lookupfz(self.mosDat,
                                  'nch',
                                  'GMOVERID',
                                  VDS=self.VDS,
                                  VSB=self.VSB,
                                  L=self.L,
                                  VGS=vgsSeq)
            vgsLeft = np.searchsorted(gmIdSeq, self.synGmId, 'left')
            self.synVGS = vgsSeq[vgsLeft]
            vgsStart = vgsSeq[vgsLeft - 1]
            vgsEnd = vgsSeq[vgsLeft]

    def loadMat(self):
        print('Load Mat File')
        self.mosDat = h5py.File(self.matFilePath, 'r')
        print("Loading complete!")
        self.ui.listWidgetL.clear()
        self.listL = np.array(self.mosDat['L']).flatten()
        for i in range(len(self.listL)):
            self.ui.listWidgetL.addItem(str(self.listL[i]))
            self.ui.listWidgetLRef.addItem(str(self.listL[i]))
        lp.info(self.mosDat)
        self.W = self.mosDat['W'][0][0] * self.mosDat['NFING'][0][0]
        print('Mos Default Width : %2.2f' % self.W)

    def cornerMat(self):
        '''Search & Load all the corner Matlib Data'''
        # Set Corner
        self.tgtCorner = self.listCorner.index(self.matFileInfo[2])
        print('Corner Set to : %s' % self.listCorner[self.tgtCorner])
        # Search Corner
        for i in range(len(self.listCorner)):
            cornerFileName = self.matFileInfo[0] + '_' + self.matFileInfo[
                1] + '_' + self.listCorner[i] + '.mat'
            if cornerFileName in self.matFileList:
                print('%s corner Found' % self.listCorner[i])
                self.avaCorner[i] = 1
                cornerFilePath = self.matDirPath + '/' + cornerFileName
                self.mosCorner[i] = h5py.File(cornerFilePath, 'r')
            else:
                print('%s corner None' % self.listCorner[i])
                self.avaCorner[i] = 0
                self.mosCorner[i] = None
        # Update Plots
        ## Clear the plots and then add back the indicator
        self.ui.topPlotVstar.clear()
        self.ui.midPlotVstar.clear()
        self.ui.botPlotVstar.clear()
        self.ui.topPlotGmId.clear()
        self.ui.midPlotGmId.clear()
        self.ui.botPlotGmId.clear()
        self.ui.topPlotVstar.addItem(self.topHLineVstar, ignoreBounds=True)
        self.ui.topPlotVstar.addItem(self.topVLineVstar, ignoreBounds=True)
        self.ui.midPlotVstar.addItem(self.midVLineVstar, ignoreBounds=True)
        self.ui.botPlotVstar.addItem(self.botVLineVstar, ignoreBounds=True)
        self.ui.topPlotGmId.addItem(self.topHLineGmId, ignoreBounds=True)
        self.ui.topPlotGmId.addItem(self.topVLineGmId, ignoreBounds=True)
        self.ui.midPlotGmId.addItem(self.midVLineGmId, ignoreBounds=True)
        self.ui.botPlotGmId.addItem(self.botVLineGmId, ignoreBounds=True)
        ## Generate the Curve
        self.GenCurve()
        self.ui.comboBoxDesignCorner.setCurrentIndex(self.tgtCorner)
        self.changeCorner()
        # Update CheckBox Text
        if self.avaCorner[0] == 0:
            self.ui.checkBoxCornerTT.setText("--")
        else:
            self.ui.checkBoxCornerTT.setText("TT")
            self.ui.checkBoxCornerTT.setCheckState(2)
            self.ui.checkBoxCornerTT.setCheckState(0)
        if self.avaCorner[1] == 0:
            self.ui.checkBoxCornerFF.setText("--")
        else:
            self.ui.checkBoxCornerFF.setText("FF")
            self.ui.checkBoxCornerFF.setCheckState(2)
            self.ui.checkBoxCornerFF.setCheckState(0)
        if self.avaCorner[2] == 0:
            self.ui.checkBoxCornerSS.setText("--")
        else:
            self.ui.checkBoxCornerSS.setText("SS")
            self.ui.checkBoxCornerSS.setCheckState(2)
            self.ui.checkBoxCornerSS.setCheckState(0)
        if self.avaCorner[3] == 0:
            self.ui.checkBoxCornerFS.setText("--")
        else:
            self.ui.checkBoxCornerFS.setText("FS")
            self.ui.checkBoxCornerFS.setCheckState(2)
            self.ui.checkBoxCornerFS.setCheckState(0)
        if self.avaCorner[4] == 0:
            self.ui.checkBoxCornerSF.setText("--")
        else:
            self.ui.checkBoxCornerSF.setText("SF")
            self.ui.checkBoxCornerSF.setCheckState(2)
            self.ui.checkBoxCornerSF.setCheckState(0)

    def changeCorner(self):
        '''Change the Temp Corner'''
        newTgtCorner = self.ui.comboBoxDesignCorner.currentIndex()
        if self.avaCorner[newTgtCorner] == 1:
            self.curveIdCorner[self.tgtCorner].setPen(
                self.cornerPen[self.tgtCorner])
            self.curveFtCorner[self.tgtCorner].setPen(
                self.cornerPen[self.tgtCorner])
            if (self.refLSet == 1):
                self.curveIdCornerRef[self.tgtCorner].setVisible(False)
            self.tgtCorner = newTgtCorner
            self.ui.labelLog.setText("Corner Set")
            self.pen = self.linePen[self.tgtCorner]
            self.curveIdCorner[self.tgtCorner].setPen(
                self.linePen[self.tgtCorner])
            self.curveFtCorner[self.tgtCorner].setPen(
                self.linePen[self.tgtCorner])
            self.mosDat = self.mosCorner[self.tgtCorner]
            self.UpdatePlot()
            self.PlotOff()
            if (self.refLSet == 1):
                self.curveIdCornerRef[self.tgtCorner].setVisible(True)
        else:
            self.ui.labelLog.setText("Corner Not Found")

    def GenCurve(self):
        '''Generate all the curve'''
        for i in range(len(self.listCorner)):
            if self.avaCorner[i] == 1:
                self.vstarCurve(self.mosCorner[i], i)
                self.ui.topPlotVstar.addItem(self.curveIdCorner[i])
                self.ui.botPlotVstar.addItem(self.curveFtCorner[i])
                self.ui.midPlotVstar.addItem(self.curveAvoCorner[i])
                self.gmIdCurve(self.mosCorner[i], i)
                self.ui.topPlotGmId.addItem(self.curveIdCornerG[i])
                self.ui.botPlotGmId.addItem(self.curveFtCornerG[i])
                self.ui.midPlotGmId.addItem(self.curveAvoCornerG[i])
                self.vthCurve(self.mosCorner[i], i)
                self.ui.topLPlotL.addItem(self.curveVthCorner[i])
                if self.refLSet == 1:
                    self.ui.topPlotVstar.addItem(self.curveIdCornerRef[i])
            else:
                self.curveIdCorner[i] = None
                self.curveFtCorner[i] = None
                self.curveAvoCorner[i] = None
                self.curveIdCornerG[i] = None
                self.curveFtCornerG[i] = None
                self.curveAvoCornerG[i] = None
                self.curveVthCorner[i] = None
                # Ref
                self.curveIdCornerRef[i] = None
                self.curveFtCornerRef[i] = None
                self.curveAvoCornerRef[i] = None
                self.curveIdCornerGRef[i] = None
                self.curveFtCornerGRef[i] = None
                self.curveAvoCornerGRef[i] = None

    def UpdatePlot(self):
        '''Update the Plot for GmId'''
        # Update the MainCurve
        if self.curveIdFit != None:
            self.ui.topPlotVstar.removeItem(self.curveIdFit)
            self.ui.midPlotVstar.removeItem(self.curveAvoFit)
            self.ui.botPlotVstar.removeItem(self.curveFtFit)
            self.ui.topPlotGmId.removeItem(self.curveIdFitG)
            self.ui.midPlotGmId.removeItem(self.curveAvoFitG)
            self.ui.botPlotGmId.removeItem(self.curveFtFitG)
            self.ui.topLPlotL.removeItem(self.curveVth)
        VGS = np.arange(0, 1.8, 0.01)
        self.listId = lp.lookupfz(self.mosDat,
                                  'nch',
                                  'ID',
                                  VDS=0.9,
                                  VSB=0,
                                  L=self.L,
                                  VGS=VGS)
        self.listAvo = lp.lookupfz(self.mosDat,
                                   'nch',
                                   'SELF_GAIN',
                                   VDS=0.9,
                                   VSB=0,
                                   L=self.L,
                                   VGS=VGS)
        self.listGmId = lp.lookupfz(self.mosDat,
                                    'nch',
                                    'GMOVERID',
                                    VDS=0.9,
                                    VSB=0,
                                    L=self.L,
                                    VGS=VGS)
        self.listFt = lp.lookupfz(self.mosDat,
                                  'nch',
                                  'FUG',
                                  VDS=0.9,
                                  VSB=0,
                                  L=self.L,
                                  VGS=VGS)
        self.listVth = lp.lookupfz(self.mosDat,
                                   'nch',
                                   'VT',
                                   VDS=0.9,
                                   VSB=0,
                                   L=self.listL,
                                   VGS=0.9)
        # Fig Line
        self.listVstar = 2 * np.reciprocal(self.listGmId)
        self.csId = CubicSpline(self.listVstar, self.listId)
        self.csFt = CubicSpline(self.listVstar, self.listFt)
        self.csAvo = CubicSpline(self.listVstar, self.listAvo)
        self.listGmIdG = np.flip(self.listGmId, 0)
        self.listIdG = np.flip(self.listId, 0)
        self.listFtG = np.flip(self.listFt, 0)
        self.listAvoG = np.flip(self.listAvo, 0)
        self.csIdG = CubicSpline(self.listGmIdG, self.listIdG)
        self.csFtG = CubicSpline(self.listGmIdG, self.listFtG)
        self.csAvoG = CubicSpline(self.listGmIdG, self.listAvoG)
        # Vstar Figure
        #self.pltVstar = np.arange( self.listVstar.min(), self.listVstar.max(), 0.001)
        self.pltVstar = np.arange(self.minVstar, self.maxVstar, 0.0005)
        self.pltId = self.csId(self.pltVstar)
        self.pltFt = self.csFt(self.pltVstar)
        self.pltAvo = self.csAvo(self.pltVstar)
        self.curveIdFit = pg.PlotDataItem(self.pltVstar,
                                          self.pltId,
                                          pen=self.pen,
                                          clear=True)
        self.curveFtFit = pg.PlotDataItem(self.pltVstar,
                                          self.pltFt,
                                          pen=self.pen,
                                          clear=True)
        self.curveAvoFit = pg.PlotDataItem(self.pltVstar,
                                           self.pltAvo,
                                           pen=self.pen,
                                           clear=True)
        self.ui.topPlotVstar.addItem(self.curveIdFit)
        self.ui.midPlotVstar.addItem(self.curveAvoFit)
        self.ui.botPlotVstar.addItem(self.curveFtFit)
        # GmId Figure
        #self.pltGmId = np.arange( self.listGmId.min(), self.listGmId.max(), 0.001)
        self.pltGmId = np.arange(self.minGmId, self.maxGmId, 0.01)
        self.pltIdG = self.csIdG(self.pltGmId)
        self.pltFtG = self.csFtG(self.pltGmId)
        self.pltAvoG = self.csAvoG(self.pltGmId)
        self.curveIdFitG = pg.PlotDataItem(self.pltGmId,
                                           self.pltIdG,
                                           pen=self.pen,
                                           clear=True)
        self.curveFtFitG = pg.PlotDataItem(self.pltGmId,
                                           self.pltFtG,
                                           pen=self.pen,
                                           clear=True)
        self.curveAvoFitG = pg.PlotDataItem(self.pltGmId,
                                            self.pltAvoG,
                                            pen=self.pen,
                                            clear=True)
        self.ui.topPlotGmId.addItem(self.curveIdFitG)
        self.ui.midPlotGmId.addItem(self.curveAvoFitG)
        self.ui.botPlotGmId.addItem(self.curveFtFitG)
        # Id Figure
        self.pltIdI = np.log10(self.pltIdG)
        self.curveGmFitI = pg.PlotDataItem(self.pltIdI,
                                           self.pltGmId,
                                           pen=self.pen,
                                           clear=True)
        self.curveFomFitI = pg.PlotDataItem(self.pltIdI,
                                            self.pltFtG * self.pltGmId,
                                            pen=self.pen,
                                            clear=True)
        self.curveAvoFitI = pg.PlotDataItem(self.pltIdI,
                                            self.pltAvoG,
                                            pen=self.pen,
                                            clear=True)
        self.ui.topPlotId.addItem(self.curveGmFitI)
        self.ui.midPlotId.addItem(self.curveAvoFitI)
        self.ui.botPlotId.addItem(self.curveFomFitI)
        # Vth Figure
        self.curveVth = pg.PlotDataItem(self.listL,
                                        self.listVth,
                                        pen=self.pen,
                                        symbolBrush=(255, 0, 0),
                                        symbolPen='w',
                                        clear=True)
        self.ui.topLPlotL.addItem(self.curveVth)
        # Set Flag
        self.curveReady = 1

    def vthCurve(self, mosDat, cornerIndex):
        '''Generate the Vth as a function of L'''
        listVth = lp.lookupfz(mosDat,
                              'nch',
                              'VT',
                              VDS=0.9,
                              VSB=0,
                              L=self.listL,
                              VGS=0.9)
        self.curveVthCorner[cornerIndex] = pg.PlotDataItem(
            self.listL, listVth, pen=self.cornerPen[cornerIndex], clear=True)

    def gmIdCurve(self, mosDat, cornerIndex):
        VGS = np.arange(0, 1.8, 0.01)
        listId = lp.lookupfz(mosDat,
                             'nch',
                             'ID',
                             VDS=0.9,
                             VSB=0,
                             L=self.L,
                             VGS=VGS)
        listGmOverId = lp.lookupfz(mosDat,
                                   'nch',
                                   'GMOVERID',
                                   VDS=0.9,
                                   VSB=0,
                                   L=self.L,
                                   VGS=VGS)
        listFt = lp.lookupfz(mosDat,
                             'nch',
                             'FUG',
                             VDS=0.9,
                             VSB=0,
                             L=self.L,
                             VGS=VGS)
        listAvo = lp.lookupfz(mosDat,
                              'nch',
                              'SELF_GAIN',
                              VDS=0.9,
                              VSB=0,
                              L=self.L,
                              VGS=VGS)
        listGmId = np.flip(listGmOverId, 0)
        listIdG = np.flip(listId, 0)
        listFtG = np.flip(listFt, 0)
        listAvoG = np.flip(listAvo, 0)
        csId = CubicSpline(listGmId, listIdG)
        csFt = CubicSpline(listGmId, listFtG)
        csAvo = CubicSpline(listGmId, listAvoG)
        pltGmId = np.arange(self.minGmId, self.maxGmId, 0.01)
        pltId = csId(pltGmId)
        pltFt = csFt(pltGmId)
        pltAvo = csAvo(pltGmId)
        self.curveIdCornerG[cornerIndex] = pg.PlotDataItem(
            pltGmId, pltId, pen=self.cornerPen[cornerIndex], clear=True)
        self.curveFtCornerG[cornerIndex] = pg.PlotDataItem(
            pltGmId, pltFt, pen=self.cornerPen[cornerIndex], clear=True)
        self.curveAvoCornerG[cornerIndex] = pg.PlotDataItem(
            pltGmId, pltAvo, pen=self.cornerPen[cornerIndex], clear=True)

    def vstarCurve(self, mosDat, cornerIndex):
        VGS = np.arange(0, 1.8, 0.01)
        # For L
        listId = lp.lookupfz(mosDat,
                             'nch',
                             'ID',
                             VDS=0.9,
                             VSB=0,
                             L=self.L,
                             VGS=VGS)
        listGmOverId = lp.lookupfz(mosDat,
                                   'nch',
                                   'GMOVERID',
                                   VDS=0.9,
                                   VSB=0,
                                   L=self.L,
                                   VGS=VGS)
        listFt = lp.lookupfz(mosDat,
                             'nch',
                             'FUG',
                             VDS=0.9,
                             VSB=0,
                             L=self.L,
                             VGS=VGS)
        listAvo = lp.lookupfz(mosDat,
                              'nch',
                              'SELF_GAIN',
                              VDS=0.9,
                              VSB=0,
                              L=self.L,
                              VGS=VGS)
        listVstar = 2 * np.reciprocal(listGmOverId)
        csId = CubicSpline(listVstar, listId)
        csFt = CubicSpline(listVstar, listFt)
        csAvo = CubicSpline(listVstar, listAvo)
        #pltVstar = np.arange( listVstar.min(), listVstar.max(), 0.001)
        pltVstar = np.arange(self.minVstar, self.maxVstar, 0.0005)
        pltId = csId(pltVstar)
        pltFt = csFt(pltVstar)
        pltAvo = csAvo(pltVstar)
        self.curveIdCorner[cornerIndex] = pg.PlotDataItem(
            pltVstar, pltId, pen=self.cornerPen[cornerIndex], clear=True)
        self.curveFtCorner[cornerIndex] = pg.PlotDataItem(
            pltVstar, pltFt, pen=self.cornerPen[cornerIndex], clear=True)
        self.curveAvoCorner[cornerIndex] = pg.PlotDataItem(
            pltVstar, pltAvo, pen=self.cornerPen[cornerIndex], clear=True)
        # For LRef
        if (self.refLSet == 1):
            listId = lp.lookupfz(mosDat,
                                 'nch',
                                 'ID',
                                 VDS=0.9,
                                 VSB=0,
                                 L=self.Lref,
                                 VGS=VGS)
            listGmOverId = lp.lookupfz(mosDat,
                                       'nch',
                                       'GMOVERID',
                                       VDS=0.9,
                                       VSB=0,
                                       L=self.Lref,
                                       VGS=VGS)
            listFt = lp.lookupfz(mosDat,
                                 'nch',
                                 'FUG',
                                 VDS=0.9,
                                 VSB=0,
                                 L=self.Lref,
                                 VGS=VGS)
            listAvo = lp.lookupfz(mosDat,
                                  'nch',
                                  'SELF_GAIN',
                                  VDS=0.9,
                                  VSB=0,
                                  L=self.Lref,
                                  VGS=VGS)
            listVstar = 2 * np.reciprocal(listGmOverId)
            csId = CubicSpline(listVstar, listId)
            csFt = CubicSpline(listVstar, listFt)
            csAvo = CubicSpline(listVstar, listAvo)
            pltId = csId(pltVstar)
            pltFt = csFt(pltVstar)
            pltAvo = csAvo(pltVstar)
            self.curveIdCornerRef[cornerIndex] = pg.PlotDataItem(
                pltVstar, pltId, pen=self.cornerPen[cornerIndex], clear=True)
            self.curveFtCornerRef[cornerIndex] = pg.PlotDataItem(
                pltVstar, pltFt, pen=self.cornerPen[cornerIndex], clear=True)
            self.curveAvoCornerRef[cornerIndex] = pg.PlotDataItem(
                pltVstar, pltAvo, pen=self.cornerPen[cornerIndex], clear=True)

    def visibleRef(self, curveStae):
        print("TODO")

    def visibleCurve(self, curveIndex, curveState):
        self.curveIdCorner[curveIndex].setVisible(curveState)
        self.curveFtCorner[curveIndex].setVisible(curveState)
        self.curveAvoCorner[curveIndex].setVisible(curveState)
        self.curveIdCornerG[curveIndex].setVisible(curveState)
        self.curveFtCornerG[curveIndex].setVisible(curveState)
        self.curveAvoCornerG[curveIndex].setVisible(curveState)
        self.curveVthCorner[curveIndex].setVisible(curveState)

    def topMouseMovedVstar(self, evt):
        '''Read out the number at the point'''
        mousePoint = self.ui.topPlotVstar.plotItem.vb.mapSceneToView(evt)
        self.topVLineVstar.setPos(mousePoint.x())
        self.midVLineVstar.setPos(mousePoint.x())
        self.botVLineVstar.setPos(mousePoint.x())
        if (self.curveReady == 1):
            index = np.searchsorted(self.pltVstar, mousePoint.x(), side="left")
            if index > 0 and index < len(self.pltVstar):
                self.topHLineVstar.setPos(self.pltId[index])
                self.ui.topPlotVstar.addItem(self.topHLineVstar,
                                             ignoreBounds=True)
                self.ui.labelId.setText(self.sciPrint(self.pltId[index], 'A'))
                self.ui.labelVstar.setText(
                    self.sciPrint(self.pltVstar[index], 'V'))
                self.ui.labelGmId.setText(
                    self.sciPrint((2.0 / self.pltVstar[index]), '1/V'))
                self.ui.labelFt.setText(self.sciPrint(self.pltFt[index], 'Hz'))
                self.ui.labelGain.setText(
                    self.sciPrint(self.pltAvo[index], 'V/V'))
                self.ui.labelFOM.setText(
                    self.sciPrint(
                        (2.0 * self.pltFt[index] / self.pltVstar[index]),
                        'Hz/V'))
                self.arrowPos = index
            else:
                if index <= 0:
                    self.arrowPos = 0
                else:
                    self.arrowPos = len(self.pltVstar) - 1
                self.ui.topPlotVstar.removeItem(self.topHLineVstar)
                self.ui.labelId.setText('---')
                self.ui.labelGmId.setText('---')
                self.ui.labelFt.setText('---')
                self.ui.labelFOM.setText('---')
                self.ui.labelVstar.setText('---')
            #self.arrowFt.setPos(self.pltVstar[self.arrowPos], self.pltFt[self.arrowPos])
            #self.arrowAvo.setPos(self.pltVstar[self.arrowPos], self.pltAvo[self.arrowPos])
            #self.ui.botPlotVstar.addItem(self.arrowFt)
            #self.ui.midPlotVstar.addItem(self.arrowAvo)

    def topMouseMovedGmId(self, evt):
        '''Read out the number at the point'''
        mousePointG = self.ui.topPlotGmId.plotItem.vb.mapSceneToView(evt)
        self.topVLineGmId.setPos(mousePointG.x())
        self.botVLineGmId.setPos(mousePointG.x())
        self.midVLineGmId.setPos(mousePointG.x())
        if (self.curveReady == 1):
            index = np.searchsorted(self.pltGmId, mousePointG.x(), side="left")
            if index > 0 and index < len(self.pltGmId):
                self.topHLineGmId.setPos(self.pltIdG[index])
                self.ui.topPlotGmId.addItem(self.topHLineGmId,
                                            ignoreBounds=True)
                self.ui.labelId.setText(self.sciPrint(self.pltIdG[index], 'A'))
                self.ui.labelVstar.setText(
                    self.sciPrint((2.0 / self.pltGmId[index]), 'V'))
                self.ui.labelGmId.setText(
                    self.sciPrint(self.pltGmId[index], '1/V'))
                self.ui.labelFt.setText(self.sciPrint(self.pltFtG[index],
                                                      'Hz'))
                self.ui.labelGain.setText(
                    self.sciPrint(self.pltAvoG[index], 'V/V'))
                self.ui.labelFOM.setText(
                    self.sciPrint((self.pltFtG[index] * self.pltGmId[index]),
                                  'Hz/V'))
            else:
                self.ui.topPlotGmId.removeItem(self.topHLineGmId)
                self.ui.labelId.setText('---')
                self.ui.labelGmId.setText('---')
                self.ui.labelFt.setText('---')
                self.ui.labelFOM.setText('---')
                self.ui.labelVstar.setText('---')

    def sciPrint(self, rawNum, unit):
        '''Print the rawNum with autoscale'''
        shiftNum = (decimal.Decimal(str(rawNum)) *
                    decimal.Decimal('1E24')).normalize()
        preNum, scaleNum = shiftNum.to_eng_string().split('E')
        quanNum = decimal.Decimal(preNum).quantize(decimal.Decimal('.001'))
        scaleChar = const.UNIT_PREFIX[int(scaleNum) // 3]
        return str(quanNum) + " " + scaleChar + unit

    def closeEvent(self, event):
        event.accept()