Exemplo n.º 1
0
    def __ConfigureSysIniFile(self):
        iniFile = QFile("info.ini")

        if iniFile.exists():
            self.__infoSettings = QSettings("info.ini", QSettings.IniFormat)

            self.__appIDLineEdit.setText(
                self.__infoSettings.value("info/appid"))
            self.__keyLineEdit.setText(self.__infoSettings.value("info/key"))

        else:
            if iniFile.open(QFile.ReadWrite):
                self.__infoSettings = QSettings("info.ini",
                                                QSettings.IniFormat)

                self.__infoSettings.beginGroup("info")

                self.__infoSettings.setValue("appid", "00000000000000000")
                self.__infoSettings.setValue("key", "00000000000000000")
                self.__infoSettings.endGroup()

                iniFile.close()

                self.__appIDLineEdit.setText("00000000000000000")
                self.__keyLineEdit.setText("00000000000000000")
Exemplo n.º 2
0
    def loadConfig(self):
        self.initRiseRun = None
        self.initSetRun = None
        cfgFile = QFile(self.fileName)
        if cfgFile is not None:
            if cfgFile.exists():
                debugMessage("Config file found")

                if cfgFile.open(QIODevice.ReadOnly | QIODevice.Text):
                    inStream = QTextStream(cfgFile)
                    if inStream is not None:
                        # Assume correct for system timezone is OFF
                        self.setCorrectForSysTZ(False)
                        while not inStream.atEnd():
                            inStream.skipWhiteSpace()
                            line = inStream.readLine()
                            self.processConfigLine(line)
            else:
                debugMessage("Config file NOT found")
                self.setCorrectForSysTZ(False)

        # We are only successful if we have a latitude, longitude and timezone
        result = (self.latitude is not None)\
            and (self.longitude is not None)\
            and (self.homeTZ is not None)
        return result
Exemplo n.º 3
0
    def init(self) -> bool:
        """Create the Connection to the Database.

        For the Moment just SQLite

        Returns:
            Return true is the database successfull initialized.
        """
        self.database = QSqlDatabase.database()

        if self.dbType == "sqlite":
            if not self.database.isValid():
                self.database = QSqlDatabase.addDatabase("QSQLITE")
                if not self.database.isValid():
                    self.log.error("Cannot add database")
                    return False

            self.database_name = self.__get_sqlite_name()
            file = QFile(self.database_name)
            if file.exists():
                # When using the SQLite driver, open() will create the SQLite
                # database if it doesn't exist.
                self.log.info("Try open the existing db : {}".format(
                    self.database_name))
                self.database.setDatabaseName(self.database_name)
            else:
                self.database.setDatabaseName(self.database_name)
                self.log.info("Try create db : {}".format(self.database_name))
                self.prepare_db()

            if not self.database.open():
                self.log.error("Cannot open database")
                QFile.remove(self.database_name)
                return False
        elif self.dbType == "psql":
            self.database = QSqlDatabase.addDatabase("QPSQL")
        elif self.dbType == "odbc":
            self.database = QSqlDatabase.addDatabase("QODBC")

        self.database.setHostName(self.database_hostname)
        self.database.setPort(self.database_port)
        self.database.setUserName(self.database_user_name)
        self.database.setPassword(self.database_password)

        if not self.database.isValid():
            self.log.error("Cannot add database")
            return False

        if not self.database.open():
            self.log.error("Cannot open database")
            return False

        return True
Exemplo n.º 4
0
    def set_dark_style(self):
        f = QFile(Resource.darkstyle)

        if not f.exists():
            LOGGER.error(
                "Unable to load dark stylesheet, file not found in resources")
            return
        else:
            f.open(QFile.ReadOnly | QFile.Text)
            ts = QTextStream(f)
            stylesheet = ts.readAll()

            self.setStyleSheet(stylesheet)
            KnechtSettings.app['app_style'] = 'fusion-dark'
            IconRsc.update_icons(self.ui)

            self.setStyle('Fusion')
Exemplo n.º 5
0
    def update_file_menu(self):
        """Called to update the recent files portion of the file menu
        """

        self.fileMenu.clear()
        self.addActions(self.fileMenu, self.fileMenuActions[:-1])
        current = self.file_path or None
        recent_files = []
        if self.prefs['recent_files']:
            for name in self.prefs['recent_files']:
                if name != current and QFile.exists(name):
                    recent_files.append(name)
        if recent_files:
            self.fileMenu.addSeparator().setText('Recent Files')
            for i, name in enumerate(recent_files):
                file_name = QFileInfo(name).fileName()
                action = QAction(QIcon(":/images/icon.png"),
                                 '{} - {}'.format(i + 1, file_name), self)
                action.setData(name)
                action.triggered.connect(self.load_file)
                self.fileMenu.addAction(action)
            self.fileMenu.addAction(self.clearRecentAct)
            self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.fileMenuActions[-1])
def _get_icon(path: str, ) -> Optional[QIcon]:
    if QFile.exists(path):
        return QIcon(path)
    return None
Exemplo n.º 7
0
 def testCallingInstanceMethod(self):
     '''Call instance method.'''
     f1 = QFile(self.non_existing_filename)
     self.assertFalse(f1.exists())
     f2 = QFile(self.existing_filename)
     self.assertTrue(f2.exists())
Exemplo n.º 8
0
 def testCallingStaticMethodWithInstance(self):
     '''Call static method using instance of class.'''
     f = QFile(self.non_existing_filename)
     self.assertTrue(f.exists(self.existing_filename))
     self.assertFalse(f.exists(self.non_existing_filename))
Exemplo n.º 9
0
 def testCallingStaticMethodWithClass(self):
     '''Call static method using class.'''
     self.assertTrue(QFile.exists(self.existing_filename))
     self.assertFalse(QFile.exists(self.non_existing_filename))
Exemplo n.º 10
0
 def _validateEnginePath(self, path):
     return QFile.exists(path) and QFileInfo(path).isFile()
Exemplo n.º 11
0
def organize_files():
    separator = window.cmb_separator.currentText()

    target_dir = QDir(window.edit_target_dir.text())
    list_target_dirs = target_dir.entryList()

    progress = progress_window()
    progress.set_max(window.list_files.count())

    for index in range(window.list_files.count()):
        progress.set_value(index)

        #
        # STEP 1: Create target directory if necessary
        #

        # Get folder name for file
        fn_src = window.list_files.item(index).text()
        progress.set_text("Processing \"{0}\"".format(fn_src))

        md = pyexiv2.ImageMetadata(fn_src)

        image_ts = datetime.date
        try:
            md.read()
            image_ts = md['Exif.Photo.DateTimeOriginal'].value

        except:
            print("Cannot open file \"{0}\"".format(fn_src))
            continue

        # Makes sure the day and month are always two digits
        def correct_format(number):
            if number < 10:
                return "0" + str(number)
            else:
                return str(number)

        folder_name_trg = str(image_ts.year) + separator + correct_format(
            image_ts.month) + separator + correct_format(image_ts.day)
        dir_name_trg = target_dir.absolutePath() + QDir.separator(
        ) + folder_name_trg

        # Create folder for day if necessary
        target_folder = QDir(dir_name_trg)
        if not target_folder.exists():
            QDir.mkdir(target_dir, dir_name_trg)
            print("Created directory \"{0}\"".format(dir_name_trg))

        #
        # STEP 2: Move file
        #

        # absolute file name of the new file
        fn_trg_abs = dir_name_trg + QDir.separator() + fn_src.split(
            QDir.separator())[-1]
        file_trg = QFile(fn_trg_abs)

        # Don't overwrite existing files
        if file_trg.exists():
            print("Skipping file \"{0}\"".format(file_trg.fileName()))
            continue

        QFile.copy(fn_src, fn_trg_abs)
        print("Copied file from \"{0}\" to \"{1}\"".format(fn_src, fn_trg_abs))

    print("Finished!")
Exemplo n.º 12
0
 def testCallingInstanceMethod(self):
     '''Call instance method.'''
     f1 = QFile(self.non_existing_filename)
     self.assertFalse(f1.exists())
     f2 = QFile(self.existing_filename)
     self.assert_(f2.exists())
Exemplo n.º 13
0
 def testCallingStaticMethodWithInstance(self):
     '''Call static method using instance of class.'''
     f = QFile(self.non_existing_filename)
     self.assert_(f.exists(self.existing_filename))
     self.assertFalse(f.exists(self.non_existing_filename))
Exemplo n.º 14
0
 def testCallingStaticMethodWithClass(self):
     '''Call static method using class.'''
     self.assert_(QFile.exists(self.existing_filename))
     self.assertFalse(QFile.exists(self.non_existing_filename))
Exemplo n.º 15
0
    def prepare_db(self) -> bool:
        """Create the Database from the DDL.

        The DDL is a script that provided as QResource

        Returns:
            True if creation succesful.
        """
        if not self.database.isValid():
            self.log.warning("The Database is not valid, reopen")
            self.database = QSqlDatabase.database(self.database_name)

        self.database.open()

        query = QSqlQuery(self.database)

        file = QFile(":/data/script.sql")
        if not file.exists():
            self.log.error("Kritischer Fehler beim erzeugen der Datenbank"
                           " {} nicht gefunden".format(file.fileName()))
            return False

        if not file.open(QIODevice.ReadOnly):
            self.log.error(
                "Kritischer Fehler bei der Initialisierung der Datenbank."
                "Die Datei {} konnte nicht geöffnet werden".format(
                    file.fileName()))

        ts = QTextStream(file)

        line: str = ""
        cleaned_line: str = ""
        string_list: list = []
        read_line: list = []

        self.log.info("File at end: {}".format(ts.atEnd()))

        while not ts.atEnd():
            has_text: bool = False
            line = ""
            string_list.clear()
            while not has_text:
                read_line = ts.read_line()
                self.log.info("read Line: {}".format(read_line))
                cleaned_line = read_line.strip()
                string_list = cleaned_line.split("--")
                cleaned_line = string_list[0]
                if not cleaned_line.startswith(
                        "--") and not cleaned_line.startswith("DROP"):
                    line += cleaned_line
                if cleaned_line.endswith(";"):
                    break
                if cleaned_line.startswith("COMMIT"):
                    has_text = True
            if not line == "":
                self.log.info("Line: {}".format(line))

                if not query.exec_(line):
                    self.log.error(
                        "Fehler beim Erzeugen der Tabelle {}".format(line))
                    self.log.error("Datenbank meldet Fehler {}".format(
                        query.lastError()))
                    return False
            else:
                self.log.error(
                    "Fehler beim Lesen der Datei zur Datenbank Erzeugung: ")
                return False
        file.close()
        self.log.info("Datenbank erfolgreich erzeugt")
        return True
Exemplo n.º 16
0
    def saveConfig(self):
        # We haven't yet saved each property
        self.savedShowLocationDMS = False
        self.savedLat = False
        self.savedLon = False
        self.savedTZ = False
        self.savedCorrectForSysTZ = False
        self.savedRiseRun = False
        self.savedSetRun = False
        self.savedRunLastEventAtLaunch = False

        # Get the config and temp filenames
        cfgFilename = self.getConfigFilename()
        tmpFilename = self.getConfigTempFilename()

        # Use any original config file to read and a temp file to write
        cfgFile = QFile(cfgFilename)
        tmpFile = QFile(tmpFilename)
        if (cfgFile is not None) and (tmpFile is not None):
            # Open the input
            inStream = None
            if cfgFile.exists():
                debugMessage("Config file found")

                if cfgFile.open(QIODevice.ReadOnly | QIODevice.Text):
                    inStream = QTextStream(cfgFile)

            # Open the output
            if tmpFile.open(QFile.WriteOnly | QFile.Truncate | QIODevice.Text):
                outStream = QTextStream(tmpFile)
            else:
                outStream = None

            if outStream is not None:
                # If we have an input file, read through it re-writing it to
                # the temp file and change any known settings to current values
                if inStream is not None:
                    while not inStream.atEnd():
                        line = inStream.readLine()
                        print("Saving Config line: {}".format(line))
                        self.processOutputConfigLine(outStream, line)

                    # Remove the original config file
                    cfgFile.remove()
                    cfgFile = None
                else:
                    warningMessage("Unable to open file to save "
                                   "configuration: {}".format(tmpFilename),
                                   self.configSrcFrom)

                # Fixup anything we didn't save in the temp file they will
                # only be written based on the third argument being True
                locationFmtCorrect = (self.savedShowLocationDMS is False) and\
                                     (self.getShowLocationDMS() is True)
                self.processOutputConfigLine(outStream,
                                             "showLocationInDMS",
                                             locationFmtCorrect)
                self.processOutputConfigLine(outStream,
                                             "latitude=0",
                                             not self.savedLat)
                self.processOutputConfigLine(outStream,
                                             "longitude=0",
                                             not self.savedLon)
                self.processOutputConfigLine(outStream,
                                             "timezone=0",
                                             not self.savedTZ)

                tzCorrect = (self.savedCorrectForSysTZ is False) and\
                            (self.getCorrectForSysTZ() is True)
                self.processOutputConfigLine(outStream,
                                             "CorrectForSystemTimezone",
                                             tzCorrect)
                self.processOutputConfigLine(outStream,
                                             "sunriserun=abc",
                                             not self.savedRiseRun)
                self.processOutputConfigLine(outStream,
                                             "sunsetrun=abc",
                                             not self.savedSetRun)

                launchRun = (self.savedRunLastEventAtLaunch is False) and\
                            (self.runLastEventAtLaunch is True)
                self.processOutputConfigLine(outStream,
                                             "runlasteventatlaunch",
                                             launchRun)

                # Rename the temp file as the config file
                tmpFile.rename(cfgFilename)
            else:
                warningMessage("Unable to open previous file to save "
                               "configuration: {}".format(cfgFilename),
                               self.configSrcFrom)