Exemple #1
0
def _get(typ):
    """Get the directory where files of the given type should be written to.

    Args:
        typ: A member of the QStandardPaths::StandardLocation enum,
             see http://doc.qt.io/qt-5/qstandardpaths.html#StandardLocation-enum
    """
    overridden, path = _from_args(typ, _args)
    if not overridden:
        path = _writable_location(typ)
        appname = QCoreApplication.instance().applicationName()
        if typ == QStandardPaths.ConfigLocation and path.split(os.sep)[-1] != appname:
            # WORKAROUND - see
            # https://bugreports.qt.io/browse/QTBUG-38872
            path = os.path.join(path, appname)
        if typ == QStandardPaths.DataLocation and os.name == "nt":
            # Under windows, config/data might end up in the same directory.
            data_path = QStandardPaths.writableLocation(QStandardPaths.DataLocation)
            config_path = QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)
            if data_path == config_path:
                path = os.path.join(path, "data")
    # From the XDG basedir spec:
    #     If, when attempting to write a file, the destination directory is
    #     non-existant an attempt should be made to create it with permission
    #     0700. If the destination directory exists already the permissions
    #     should not be changed.
    if path is not None and not os.path.exists(path):
        os.makedirs(path, 0o700)
    return path
def get(typ, args=None):
    """Get the directory where files of the given type should be written to.

    Args:
        typ: A member of the QStandardPaths::StandardLocation enum,
             see http://qt-project.org/doc/qt-5/qstandardpaths.html#StandardLocation-enum
        args: An argparse namespace which could be used to override the
              locations.
    """
    overridden, path = _from_args(typ, args)
    if not overridden:
        path = _writable_location(typ)
        appname = QCoreApplication.instance().applicationName()
        if (typ == QStandardPaths.ConfigLocation and
                path.split(os.sep)[-1] != appname):
            # WORKAROUND - see
            # https://bugreports.qt-project.org/browse/QTBUG-38872
            path = os.path.join(path, appname)
        if typ == QStandardPaths.DataLocation and os.name == 'nt':
            # Under windows, config/data might end up in the same directory.
            data_path = QStandardPaths.writableLocation(
                QStandardPaths.DataLocation)
            config_path = QStandardPaths.writableLocation(
                QStandardPaths.ConfigLocation)
            if data_path == config_path:
                path = os.path.join(path, 'data')
    if path is not None and not os.path.exists(path):
        os.makedirs(path, 0o700)
    return path
def saveScreenshot(pixmap):
    global settings
    global soundEffect
    global savePathValue

    soundEffect.play()

    fileName = "%s%s.png" % (_("DeepinScreenshot"),
                             time.strftime("%Y%m%d%H%M%S", time.localtime()))
    save_op = settings.getOption("save", "save_op")
    save_op_index = int(save_op)

    absSavePath = os.path.abspath(savePathValue)
    if savePathValue and os.path.exists(os.path.dirname(absSavePath)):
        savePixmap(pixmap, absSavePath)
    else:
        saveDir = ""
        copy = False
        if save_op_index == 0: #saveId == "save_to_desktop":
            saveDir = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation)
        elif save_op_index == 1: #saveId == "auto_save" :
            saveDir = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
        elif save_op_index == 2: #saveId == "save_to_dir":
            saveDir = QFileDialog.getExistingDirectory()
        elif save_op_index == 4: #saveId == "auto_save_ClipBoard":
            copy = True
            saveDir = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
        else: copy = True

        if copy: copyPixmap(pixmap)
        if saveDir: savePixmap(pixmap, os.path.join(saveDir, fileName))
Exemple #4
0
def writablePath(suffix=None):
    if hasattr(QStandardPaths, "AppLocalDataLocation"):
        p = QStandardPaths.writableLocation(QStandardPaths.AppLocalDataLocation)
    else:
        # Qt < 5.4
        p = QStandardPaths.writableLocation(QStandardPaths.DataLocation)
    if suffix:
        p = os.path.join(p, suffix)
    if not os.path.exists(p):
        os.makedirs(p)
    return p
    def saveScreenshot(self, pixmap):
        self.needSound.emit()

        savePathValue = self.argValues["savePath"]
        timeStamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
        fileName = "%s%s.png" % (_("DeepinScreenshot"), timeStamp)
        save_op = self.settings.getOption("save", "save_op")
        save_op_index = int(save_op)

        absSavePath = ""
        copyToClipborad = False
        if savePathValue != "":
            absSavePath = os.path.abspath(savePathValue)
        else:
            if save_op_index == 0: #saveId == "save_to_desktop":
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.DesktopLocation)
                absSavePath = os.path.join(saveDir, fileName)
            elif save_op_index == 1: #saveId == "auto_save" :
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.PicturesLocation)
                absSavePath = os.path.join(saveDir, fileName)
            elif save_op_index == 2: #saveId == "save_to_dir":
                lastSavePath = self.settings.getOption("save", "folder")
                absSavePath = QFileDialog.getSaveFileName(None, _("Save"),
                    os.path.join(lastSavePath, fileName))[0]
                self.settings.setOption("save", "folder",
                    os.path.dirname(absSavePath) or lastSavePath)
            elif save_op_index == 4: #saveId == "auto_save_ClipBoard":
                copyToClipborad = True
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.PicturesLocation)
                absSavePath = os.path.join(saveDir, fileName)
            else: copyToClipborad = True

        if absSavePath or copyToClipborad:
            if copyToClipborad:
                self.copyPixmap(pixmap)
            if absSavePath:
                copyToClipborad = False
                self.savePixmap(pixmap, absSavePath)

            if self.callHelpManual:
                self._notificationId = self._notify(
                        _(" View Manual, the picture is automatically saved."),
                        [ACTION_ID_MANUAL, _("View")])

            if absSavePath:
                self._notificationId = self._notify(
                        _("Picture has been saved to %s") % absSavePath,
                        [ACTION_ID_OPEN, _("View")])
        else:
            self.finished.emit()
Exemple #6
0
def getDataDir():
    # Temporary fix for non-ascii usernames
    # If username has non-ascii characters, just store userdata
    # in the Pesterchum install directory (like before)
    try:
        if isOSX():
            return os.path.join(str(QStandardPaths.writableLocation(QStandardPaths.DataLocation)), "Pesterchum/")
        elif isLinux():
            return os.path.join(str(QStandardPaths.writeableLocation(QStandardPaths.HomeLocation)), ".pesterchum/")
        else:
            return os.path.join(str(QStandardPaths.writableLocation(QStandardPaths.DataLocation)), "pesterchum/")
    except UnicodeDecodeError:
        return ''
Exemple #7
0
def data():
    """Get a location for data."""
    typ = QStandardPaths.DataLocation
    overridden, path = _from_args(typ, _args)
    if not overridden:
        path = _writable_location(typ)
        if os.name == "nt":
            # Under windows, config/data might end up in the same directory.
            data_path = QStandardPaths.writableLocation(QStandardPaths.DataLocation)
            config_path = QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)
            if data_path == config_path:
                path = os.path.join(path, "data")
    _maybe_create(path)
    return path
    def select_file(self):
        path = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
        file, ok = QFileDialog.getOpenFileName(self, 'Choose file', path,
                                               'All files (*)')

        if ok:
            self.filePath.setText('file://' + file)
    def select_file(self):
        path = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
        file = QFileDialog.getOpenFileName(self, 'Choose file', path,
                                           UriInputSettings.exts())[0]

        if file != '':
            self.filePath.setText('file://' + file)
Exemple #10
0
def main():
    """Check by which hostblock list a host was blocked."""
    if len(sys.argv) != 2:
        print("Usage: {} <host>".format(sys.argv[0]), file=sys.stderr)
        sys.exit(1)
    confdir = QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)
    confdir = confdir.replace('/', os.sep)
    if confdir.split(os.sep)[-1] != 'qutebrowser':
        confdir = os.path.join(confdir, 'qutebrowser')
    confpath = os.path.join(confdir, 'qutebrowser.conf')
    parser = configparser.ConfigParser()
    print("config path: {}".format(confpath))
    successful = parser.read(confpath, encoding='utf-8')
    if not successful:
        raise OSError("configparser did not read files successfully!")
    lists = parser['content']['host-block-lists']
    for url in lists.split(','):
        print("checking {}...".format(url))
        raw_file = urllib.request.urlopen(url)
        byte_io = io.BytesIO(raw_file.read())
        f = adblock.get_fileobj(byte_io)
        for line in f:
            if sys.argv[1] in line:
                print("FOUND {} in {}:".format(sys.argv[1], url))
                print("    " + line.rstrip())
Exemple #11
0
def get_standard_dir(typ):
    """Get the directory where files of the given type should be written to.

    Args:
        typ: A member of the QStandardPaths::StandardLocation enum,
             see http://qt-project.org/doc/qt-5/qstandardpaths.html#StandardLocation-enum
    """
    qapp = QCoreApplication.instance()
    orgname = qapp.organizationName()
    # We need to temporarily unset the organisationname here since the
    # webinspector wants it to be set to store its persistent data correctly,
    # but we don't want that to happen.
    qapp.setOrganizationName(None)
    try:
        path = QStandardPaths.writableLocation(typ)
        if not path:
            raise ValueError("QStandardPaths returned an empty value!")
        # Qt seems to use '/' as path separator even on Windows...
        path = path.replace('/', os.sep)
        appname = qapp.applicationName()
        if (typ == QStandardPaths.ConfigLocation and
                path.split(os.sep)[-1] != appname):
            # WORKAROUND - see
            # https://bugreports.qt-project.org/browse/QTBUG-38872
            path = os.path.join(path, appname)
        if not os.path.exists(path):
            os.makedirs(path)
        return path
    finally:
        qapp.setOrganizationName(orgname)
    def setUpDialogHeader(self):
        headerLayout = QGridLayout()
        self.destinationFolder = paths.writableLocation(paths.DownloadLocation)
        torrentName = self.torrentInfo.name()

        # Show the torrent name row
        nameLabel = QLabel("Torrent name:", self)
        headerLayout.addWidget(nameLabel, 0, 0)

        nameEdit = QLineEdit(torrentName, self)
        nameEdit.setReadOnly(True)
        headerLayout.addWidget(nameEdit, 0, 1)

        # Show the destination folder row
        dirLabel = QLabel("Destination folder:", self)
        headerLayout.addWidget(dirLabel, 1, 0)

        self.textField = QLineEdit(self.destinationFolder, self)
        self.textField.setReadOnly(True)
        headerLayout.addWidget(self.textField, 1, 1)

        button = QPushButton("Browse", self)
        button.clicked.connect(self.selectFolder)
        headerLayout.addWidget(button, 1, 2)

        self.layout.addLayout(headerLayout)
Exemple #13
0
def _writable_location(typ):
    """Wrapper around QStandardPaths.writableLocation.

    Arguments:
        typ: A QStandardPaths::StandardLocation member.
    """
    typ_str = debug.qenum_key(QStandardPaths, typ)

    # Types we are sure we handle correctly below.
    assert typ in [
        QStandardPaths.ConfigLocation, QStandardPaths.DataLocation,
        QStandardPaths.CacheLocation, QStandardPaths.DownloadLocation,
        QStandardPaths.RuntimeLocation, QStandardPaths.TempLocation,
        # FIXME old Qt
        getattr(QStandardPaths, 'AppDataLocation', object())], typ_str

    with _unset_organization():
        path = QStandardPaths.writableLocation(typ)

    log.misc.debug("writable location for {}: {}".format(typ_str, path))
    if not path:
        raise EmptyValueError("QStandardPaths returned an empty value!")

    # Qt seems to use '/' as path separator even on Windows...
    path = path.replace('/', os.sep)

    # Add the application name to the given path if needed.
    # This is in order for this to work without a QApplication (and thus
    # QStandardsPaths not knowing the application name), as well as a
    # workaround for https://bugreports.qt.io/browse/QTBUG-38872
    if (typ != QStandardPaths.DownloadLocation and
            path.split(os.sep)[-1] != APPNAME):
        path = os.path.join(path, APPNAME)

    return path
    def accept(self):

        self.language = self.field("language")

        base_path = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)

        lyrics_path = os.path.join(base_path, self.lyrics_folder, self.language)

        if self.old_language:
            old_lyrics_path = os.path.join(base_path, self.lyrics_folder, self.old_language)

            if os.path.exists(old_lyrics_path):
                os.rename(old_lyrics_path, lyrics_path)
            else:
                os.makedirs(lyrics_path)
        else:
            if not os.path.exists(lyrics_path):
                os.makedirs(lyrics_path)

        self._import_old_epub(lyrics_path)
        self._import_new_epub(lyrics_path)

        super(ImportLyricsWizard, self).accept()

        self.close()
Exemple #15
0
def make_short_filename(basedir, relpath, win_compat=False, relative_to=""):
    """Shorten a filename's path to proper limits.

    basedir: Absolute path of the base directory where files will be moved.
    relpath: File path, relative from the base directory.
    win_compat: Windows is quirky.
    relative_to: An ancestor directory of basedir, against which win_compat
                 will be applied.
    """
    # only deal with absolute paths. it saves a lot of grief,
    # and is the right thing to do, even for renames.
    try:
        basedir = os.path.abspath(basedir)
    except FileNotFoundError:
        # os.path.abspath raises an exception if basedir is a relative path and
        # cwd doesn't exist anymore
        basedir = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
    # also, make sure the relative path is clean
    relpath = os.path.normpath(relpath)
    if win_compat and relative_to:
        relative_to = os.path.abspath(relative_to)
        assert basedir.startswith(relative_to) and \
            basedir.split(relative_to)[1][:1] in (os.path.sep, ''), \
            "`relative_to` must be an ancestor of `basedir`"
    # always strip the relpath parts
    relpath = os.path.join(*[part.strip() for part in relpath.split(os.path.sep)])
    # if we're on windows, delegate the work to a windows-specific function
    if IS_WIN:
        reserved = len(basedir)
        if not basedir.endswith(os.path.sep):
            reserved += 1
        return _make_win_short_filename(relpath, reserved)
    # if we're being windows compatible, figure out how much
    # needs to be reserved for the basedir part
    if win_compat:
        # if a relative ancestor wasn't provided,
        # use the basedir's mount point
        if not relative_to:
            relative_to = _get_mount_point(basedir)
            # if it's root, presume the parent will be copied over
            # to windows, and hope for the best
            if relative_to == os.path.sep:
                relative_to = os.path.dirname(basedir)
        reserved = len(basedir) - len(relative_to) + 3 + 1
        #                             the drive name ^ + ^ the final separator
        relpath = _make_win_short_filename(relpath, reserved)
    # on *nix we can consider there is no path limit, but there is
    # a filename length limit.
    if IS_MACOS:
        # on OS X (i.e. HFS+), this is expressed in UTF-16 code points,
        # in NFD normalization form
        relpath = shorten_path(relpath, 255, mode=SHORTEN_UTF16_NFD)
    else:
        # on everything else the limit is expressed in bytes,
        # and filesystem-dependent
        limit = _get_filename_limit(basedir)
        relpath = shorten_path(relpath, limit, mode=SHORTEN_BYTES)
    return relpath
Exemple #16
0
 def runShortcut(self, index):
     if not index.isValid():
         return False
     shortcut = self.shortcuts[index.row()]
     if shortcut["path"].startswith("special://"):
         if shortcut["path"] == COMPUTER_PATH:
             if os.name == "nt":
                 explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe")
                 return QProcess.startDetached(explorer, ["::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"])
             else:
                 path = "/"
         elif shortcut["path"] == DOCUMENTS_PATH:
             path = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
         elif shortcut["path"] == MUSIC_PATH:
             path = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
         elif shortcut["path"] == PICTURES_PATH:
             path = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
         else:
             return False
         if os.name == "nt": #针对windows进行优化
             explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe")
             return QProcess.startDetached(explorer, [path])
         else:
             return QDesktopServices.openUrl(QUrl.fromLocalFile(path))
     else:
         currentDirectory = os.getcwd()
         try:
             if shortcut["dir"] is not None and shortcut["dir"] != "":
                 os.chdir(shortcut["dir"])
             if shortcut["openwith"] is not None and shortcut["openwith"] != "":
                 if not os.path.exists(shortcut["openwith"]):
                     return False
                 return QProcess.startDetached(shortcut["openwith"], [shortcut["path"]])
             else:
                 url = QUrl.fromUserInput(shortcut["path"])
                 if not url.isValid():
                     return False
                 if url.scheme() == "file" and not os.path.exists(url.toLocalFile()):
                     return False
                 return QDesktopServices.openUrl(url)
         except OSError: #raised by chdir()
             pass
         finally:
             os.chdir(currentDirectory)
     return False
Exemple #17
0
def _writable_location(typ):
    """Wrapper around QStandardPaths.writableLocation."""
    with qtutils.unset_organization():
        path = QStandardPaths.writableLocation(typ)
    if not path:
        raise ValueError("QStandardPaths returned an empty value!")
    # Qt seems to use '/' as path separator even on Windows...
    path = path.replace("/", os.sep)
    return path
Exemple #18
0
 def set_cache(self, cache_size_in_mb=100):
     cache = QtNetwork.QNetworkDiskCache()
     location = QStandardPaths.writableLocation(QStandardPaths.CacheLocation)
     cache.setCacheDirectory(os.path.join(location, 'picard'))
     cache.setMaximumCacheSize(cache_size_in_mb * 1024 * 1024)
     self.manager.setCache(cache)
     log.debug("NetworkDiskCache dir: %s", cache.cacheDirectory())
     log.debug("NetworkDiskCache size: %s / %s", cache.cacheSize(),
               cache.maximumCacheSize())
Exemple #19
0
def _move_webengine_data():
    """Move QtWebEngine data from an older location to the new one."""
    # Do NOT use _writable_location here as that'd give us a wrong path
    old_data_dir = QStandardPaths.writableLocation(QStandardPaths.DataLocation)
    old_cache_dir = QStandardPaths.writableLocation(
        QStandardPaths.CacheLocation)
    new_data_dir = os.path.join(data(), 'webengine')
    new_cache_dir = os.path.join(cache(), 'webengine')

    if (not os.path.exists(os.path.join(old_data_dir, 'QtWebEngine')) and
            not os.path.exists(os.path.join(old_cache_dir, 'QtWebEngine'))):
        return

    log.init.debug("Moving QtWebEngine data from {} to {}".format(
        old_data_dir, new_data_dir))
    log.init.debug("Moving QtWebEngine cache from {} to {}".format(
        old_cache_dir, new_cache_dir))

    if os.path.exists(new_data_dir):
        log.init.warning("Failed to move old QtWebEngine data as {} already "
                         "exists!".format(new_data_dir))
        return
    if os.path.exists(new_cache_dir):
        log.init.warning("Failed to move old QtWebEngine cache as {} already "
                         "exists!".format(new_cache_dir))
        return

    try:
        shutil.move(os.path.join(old_data_dir, 'QtWebEngine', 'Default'),
                    new_data_dir)
        shutil.move(os.path.join(old_cache_dir, 'QtWebEngine', 'Default'),
                    new_cache_dir)

        # Remove e.g.
        # ~/.local/share/qutebrowser/qutebrowser/QtWebEngine/Default
        if old_data_dir.split(os.sep)[-2:] == ['qutebrowser', 'qutebrowser']:
            log.init.debug("Removing {} / {}".format(
                old_data_dir, old_cache_dir))
            for old_dir in old_data_dir, old_cache_dir:
                os.rmdir(os.path.join(old_dir, 'QtWebEngine'))
                os.rmdir(old_dir)
    except OSError as e:
        log.init.exception("Failed to move old QtWebEngine data/cache: "
                           "{}".format(e))
Exemple #20
0
def openDataBase():
    db = QSqlDatabase.addDatabase('QSQLITE')
    dataPath = QStandardPaths.writableLocation(QStandardPaths.AppLocalDataLocation)
    if not QDir(dataPath).mkpath('.'):
        raise Exception('Failed to create data directory {}'.format(dataPath))

    dbPath = dataPath + '/infinitecopy_items.sql'
    print('Using item database "{}".'.format(dbPath))
    db.setDatabaseName(dbPath)
    db.open()
Exemple #21
0
 def init(self):
     self.app_name = qApp.applicationName().lower()
     self.app_dir = Path(
         QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation))
     self.app_dir.mkdir(exist_ok=True)
     settings_file = f"{self.app_name}.ini"
     self.settings = QSettings(
         self.app_dir.joinpath(settings_file).as_posix(),
         QSettings.IniFormat)
     self.settings.sync()
     self.data = DataStore(self.app_dir)
Exemple #22
0
def _writable_location(typ):
    """Wrapper around QStandardPaths.writableLocation."""
    with qtutils.unset_organization():
        path = QStandardPaths.writableLocation(typ)
    typ_str = debug.qenum_key(QStandardPaths, typ)
    log.misc.debug("writable location for {}: {}".format(typ_str, path))
    if not path:
        raise EmptyValueError("QStandardPaths returned an empty value!")
    # Qt seems to use '/' as path separator even on Windows...
    path = path.replace('/', os.sep)
    return path
def test_root_data_en_test():
    appdata = (
        Path(QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)) /
        "MyCartable")
    # desactive en attendant la sauvegarde
    # appdata = Path(QStandardPaths.writableLocation(QStandardPaths.AppDataLocation))
    rrr = root_data()
    assert rrr == appdata
    shutil.rmtree(rrr)
    rrr = root_data()
    assert rrr.is_dir()
 def nextImageFileName(self):
     picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
     dateString = QDate.currentDate().toString("yyyyMMdd")
     pattern = picturesLocation + "/pyside2_camera_" + dateString + "_{:03d}.jpg"
     n = 1
     while True:
         result = pattern.format(n)
         if not os.path.exists(result):
             return result
         n = n + 1
     return None
    def _default_documents_directory(game):

        folders = [
            "{}/My Games/{}".format(
                QStandardPaths.writableLocation(
                    QStandardPaths.DocumentsLocation),
                game.gameName(),
            ),
            "{}/{}".format(
                QStandardPaths.writableLocation(
                    QStandardPaths.DocumentsLocation),
                game.gameName(),
            ),
        ]
        for folder in folders:
            qdir = QDir(folder)
            if qdir.exists():
                return qdir

        return QDir()
Exemple #26
0
def _writable_location(typ):
    """Wrapper around QStandardPaths.writableLocation."""
    with qtutils.unset_organization():
        path = QStandardPaths.writableLocation(typ)
    typ_str = debug.qenum_key(QStandardPaths, typ)
    log.misc.debug("writable location for {}: {}".format(typ_str, path))
    if not path:
        raise ValueError("QStandardPaths returned an empty value!")
    # Qt seems to use '/' as path separator even on Windows...
    path = path.replace('/', os.sep)
    return path
Exemple #27
0
 def save_log(self):
     path = QFileDialog.getSaveFileName(
         self, 'Save Logfile',
         QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),
         'Textfile (*.txt)')
     if not path[0] == '':
         file = open(path[0], 'w')
         for line in logger.log:
             file.write(str(line))
         file.close()
         print("\nLogfile saved.")
Exemple #28
0
 def save_flipangle(self):
     path = QFileDialog.getSaveFileName(self, 'Save Flipangle Data', QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation), 'csv (*.csv)')
     if not path[0] == '':
         with open(path[0], mode='w', newline='') as file:
             writer = csv.writer(file, delimiter=',')
             writer.writerow(['Flipangletool Data', params.dataTimestamp])
             writer.writerow([''])
             writer.writerow(['attenuation [dB]', 'fft peak magnitude'])
             for n in range(len(self.at_values)):
                 writer.writerow([self.at_values[n], self.at_results[n]])
         print("\nFlipangledata saved.")
    def saveScreenshot(self, pixmap):
        self.needSound.emit()

        savePathValue = self.argValues["savePath"]
        timeStamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
        fileName = "%s%s.png" % (_("DeepinScreenshot"), timeStamp)

        save_op = self.settings.getOption("save", "save_op")
        save_op_index = int(save_op)

        absSavePath = ""
        copyToClipborad = False
        if savePathValue and os.path.exists(os.path.dirname(absSavePath)):
            absSavePath = os.path.abspath(savePathValue)
        else:
            if save_op_index == 0: #saveId == "save_to_desktop":
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.DesktopLocation)
                absSavePath = os.path.join(saveDir, fileName)
            elif save_op_index == 1: #saveId == "auto_save" :
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.PicturesLocation)
                absSavePath = os.path.join(saveDir, fileName)
            elif save_op_index == 2: #saveId == "save_to_dir":
                lastSavePath = self.settings.getOption("save", "folder")
                absSavePath = QFileDialog.getSaveFileName(None, _("Save"),
                    os.path.join(lastSavePath, fileName))[0]
                self.settings.setOption("save", "folder",
                    os.path.dirname(absSavePath) or lastSavePath)
            elif save_op_index == 4: #saveId == "auto_save_ClipBoard":
                copyToClipborad = True
                saveDir = QStandardPaths.writableLocation(
                    QStandardPaths.PicturesLocation)
                absSavePath = os.path.join(saveDir, fileName)
            else: copyToClipborad = True

        if absSavePath or copyToClipborad:
            if copyToClipborad: self.copyPixmap(pixmap)
            if absSavePath: self.savePixmap(pixmap, absSavePath)
        else:
            self.finished.emit()
    def run(self) -> None:
        self.servering = True
        olddir = ""

        def initems(list1, target):
            for i in list1:
                if i in target:
                    return True
            return False

        while self.servering:
            if not self.q.empty():
                log = self.q.get()
                ip = log["ip"]
                actiontime = log["time"].split()[1]
                ms = ""
                # print("action", log["action"])
                if ip not in self.iplist:
                    self.iplist.append(ip)
                    ms = "{}正在访问你的共享文件\n{}".format(ip, actiontime)

                elif type(
                        log["action"][0]) == str and log["action"][1] == "200":
                    if "get" in log["action"][0].lower():
                        getfile = urllib.parse.unquote(
                            log["action"][0].split()[1])
                        # print("getfile", getfile)
                        if getfile[-1] == "/" or "/home" in getfile:
                            # print("正在访问:", getfile)
                            if getfile != olddir:
                                olddir = getfile
                                ms = "{}正在访问{}\nat{}".format(
                                    ip, getfile, actiontime)
                        elif not initems(
                            ["/favicon.ico", "jamcss", "jamjs", "jamhtmlpic"],
                                getfile):
                            # print("下载了", getfile)
                            ms = "{}下载了一个文件:\n{}\nat{}".format(
                                ip, getfile, actiontime)
                    elif "post" in log["action"][0].lower():
                        ms = "{}上传了一个文件到共享文件夹\nat{}".format(ip, actiontime)
                if ms != "":
                    with open(os.path.join(
                            QStandardPaths.writableLocation(
                                QStandardPaths.DocumentsLocation),
                            "jamWebTransmitter.log"),
                              "a",
                              encoding="utf-8") as log:
                        log.write(actiontime + ms.replace("\n", "") + "\n")
                    self.showm_signal.emit(ms)
                time.sleep(0.2)
            else:
                time.sleep(0.5)
Exemple #31
0
 def choise_drawpix():
     pic, l = QFileDialog.getOpenFileName(
         self, "选择图片",
         QStandardPaths.writableLocation(
             QStandardPaths.PicturesLocation),
         "img Files (*.PNG *.jpg *.JPG *.JPEG *.BMP *.ICO)"
         ";;all files(*.*)")
     if pic:
         self.paintlayer.pixpng = pic
         icon4 = QIcon()
         icon4.addPixmap(QPixmap(pic), QIcon.Normal, QIcon.Off)
         choise_pix.setIcon(icon4)
Exemple #32
0
    def on_upload_task(self, action):
        """Import an UploadJob task file and add it to the queue

        This functionality is mainly used for automation. Another
        software creates upload tasks which are then loaded by
        DCOR-Aid.
        """
        if action.data() == "single":
            files, _ = QtWidgets.QFileDialog.getOpenFileNames(
                self,
                "Select DCOR-Aid task files",
                ".",
                "DCOR-Aid task files (*.dcoraid-task)",
            )
        else:
            tdir = QtWidgets.QFileDialog.getExistingDirectory(
                self,
                "Select folder to search for DCOR-Aid task files",
                ".",
                QtWidgets.QFileDialog.ShowDirsOnly,
            )
            files = pathlib.Path(tdir).rglob("*.dcoraid-task")

        # Keep track of a persistent task ID to dataset ID dictionary
        path_id_dict = os_path.join(
            QStandardPaths.writableLocation(
                QStandardPaths.AppLocalDataLocation),
            "map_task_to_dataset_id.txt")
        map_task_to_dataset_id = task.PersistentTaskDatasetIDDict(path_id_dict)
        dataset_kwargs = {}
        with ShowWaitCursor():
            api = get_ckan_api()
            for pp in files:
                if not task.task_has_circle(pp):
                    # let the user choose a circle
                    cdict = circle_mgr.request_circle(self)
                    if cdict is None:
                        # The user aborted, so we won't continue!
                        break
                    else:
                        dataset_kwargs["owner_org"] = cdict["name"]
                settings = QtCore.QSettings()
                update_dataset_id = bool(
                    int(
                        settings.value("uploads/update task with dataset id",
                                       "1")))
                upload_job = task.load_task(
                    path=pp,
                    map_task_to_dataset_id=map_task_to_dataset_id,
                    api=api,
                    dataset_kwargs=dataset_kwargs,
                    update_dataset_id=update_dataset_id)
                self.jobs.add_job(upload_job)
Exemple #33
0
    def lastPath(self, fileType):
        path = self.mSettings.value(lastPathKey(fileType))
        if path==None or path=='':
            documentManager = DocumentManager.instance()
            mapDocument = documentManager.currentDocument()
            if mapDocument:
                path = QFileInfo(mapDocument.fileName()).path()

        if path==None or path=='':
            path = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)

        return path
Exemple #34
0
def replace_variables(value: str, game: "BasicGame") -> str:
    """ Replace special paths in the given value. """

    if value.find("%DOCUMENTS%") != -1:
        value = value.replace(
            "%DOCUMENTS%",
            QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),
        )
    if value.find("%USERPROFILE%") != -1:
        value = value.replace(
            "%USERPROFILE%",
            QStandardPaths.writableLocation(QStandardPaths.HomeLocation),
        )
    if value.find("%GAME_DOCUMENTS%") != -1:
        value = value.replace("%GAME_DOCUMENTS%",
                              game.documentsDirectory().absolutePath())
    if value.find("%GAME_PATH%") != -1:
        value = value.replace("%GAME_PATH%",
                              game.gameDirectory().absolutePath())

    return value
def _standardpath(location: QStandardPaths.StandardLocation, name: str,
                  *paths: str) -> str:
    """Return absolute path to a standard storage directory.

    Args:
        location: Location ID according to QStandardPaths.
        name: Fallback name to use in case there is a base directory.
        paths: Any additional paths passed to os.path.join.
    """
    if basedir is not None:
        return os.path.join(basedir, name, *paths)
    return os.path.join(QStandardPaths.writableLocation(location), *paths)
Exemple #36
0
def getDataDir():
    # Temporary fix for non-ascii usernames
    # If username has non-ascii characters, just store userdata
    # in the Pesterchum install directory (like before)
    try:
        if isOSX():
            return os.path.join(
                str(
                    QStandardPaths.writableLocation(
                        QStandardPaths.DataLocation)), "Pesterchum/")
        elif isLinux():
            return os.path.join(
                str(
                    QStandardPaths.writableLocation(
                        QStandardPaths.HomeLocation)), ".pesterchum/")
        else:
            return os.path.join(
                str(
                    QStandardPaths.writableLocation(
                        QStandardPaths.DataLocation)), "pesterchum/")
    except UnicodeDecodeError:
        return ''
    def __init__(self, parent=None):
        super(CopyrightDatabase, self).__init__(parent)
        settings_folder = QStandardPaths.writableLocation(
            QStandardPaths.DataLocation)
        db_path = os.path.join(settings_folder, 'copyright.db')

        self.db = QSqlDatabase.addDatabase('QSQLITE')  # type: QSqlDatabase
        self.db.setDatabaseName(db_path)

        self.db.open()

        if 'copyright' not in self.db.tables():
            self.create_copyright_table()
Exemple #38
0
 def get_app_config_path(self) -> str:
     if self.flatpak:
         confpath = QProcessEnvironment.systemEnvironment().value(
             'XDG_CONFIG_HOME', '')
         if len(confpath):
             return confpath
         else:
             return os.path.join(QDir.homePath(), '.var', 'app',
                                 vidcutter.__desktopid__, 'config')
     return QStandardPaths.writableLocation(
         QStandardPaths.AppConfigLocation).replace(
             qApp.applicationName(),
             qApp.applicationName().lower())
Exemple #39
0
 def get_app_settings() -> QSettings:
     FixedSettings.config_path = QStandardPaths.writableLocation(
         QStandardPaths.AppConfigLocation)
     settings_ini = os.path.join(
         FixedSettings.config_path,
         '%s.ini' % FixedSettings.applicationName.lower())
     if not os.path.exists(settings_ini):
         os.makedirs(FixedSettings.config_path, exist_ok=True)
         QFile.copy(':%s.ini' % FixedSettings.applicationName.lower(),
                    settings_ini)
         QFile.setPermissions(settings_ini,
                              QFile.ReadOwner | QFile.WriteOwner)
     return QSettings(settings_ini, QSettings.IniFormat)
class TheBindingOfIsaacRebirthGame(BasicGame):
    Name = "The Binding of Isaac: Rebirth - Support Plugin"
    Author = "Luca/EzioTheDeadPoet"
    Version = "0.1.0"

    GameName = "The Binding of Isaac: Rebirth"
    GameShortName = "thebindingofisaacrebirth"
    GameNexusName = "thebindingofisaacrebirth"
    GameNexusId = 1293
    GameSteamId = 250900
    GameBinary = "isaac-ng.exe"
    GameDocumentsDirectory = str(
        Path(QStandardPaths.writableLocation(
            QStandardPaths.HomeLocation)).joinpath(
                "Documents", "My Games", "Binding of Isaac Afterbirth+"))
    GameDataPath = str(
        Path(QStandardPaths.writableLocation(
            QStandardPaths.HomeLocation)).joinpath(
                "Documents", "My Games", "Binding of Isaac Afterbirth+ Mods"))

    def iniFiles(self):
        return ["options.ini"]
Exemple #41
0
    def initConfig(self, confPath=None):

        if confPath is None:
            confRoot = QStandardPaths.writableLocation(
                QStandardPaths.ConfigLocation)
            self.confPath = path.join(path.abspath(confRoot), self.appHandle)
        else:
            logger.info("Setting config from alternative path: %s" % confPath)
            self.confPath = confPath

        self.confFile = self.appHandle + ".conf"
        self.homePath = path.expanduser("~")
        self.lastPath = self.homePath
        self.appPath = getattr(sys, "_MEIPASS",
                               path.abspath(path.dirname(__file__)))
        self.appRoot = path.join(self.appPath, path.pardir)
        self.assetPath = path.join(self.appPath, "assets")
        self.themeRoot = path.join(self.assetPath, "themes")
        self.graphPath = path.join(self.assetPath, "graphics")
        self.dictPath = path.join(self.assetPath, "dict")
        self.iconPath = path.join(self.assetPath, "icons")
        self.appIcon = path.join(self.iconPath, nwFiles.APP_ICON)

        # If config folder does not exist, make it.
        # This assumes that the os config folder itself exists.
        if not path.isdir(self.confPath):
            try:
                mkdir(self.confPath)
            except Exception as e:
                logger.error("Could not create folder: %s" % self.confPath)
                logger.error(str(e))
                return False

        # Check if config file exists
        if path.isfile(path.join(self.confPath, self.confFile)):
            # If it exists, load it
            self.loadConfig()
        else:
            # If it does not exist, save a copy of the default values
            self.saveConfig()

        # Check the availability of optional packages
        self._checkOptionalPackages()

        if self.spellTool is None:
            self.spellTool = "internal"
        if self.spellLanguage is None:
            self.spellLanguage = "en"

        return True
Exemple #42
0
    def openFiles(self):
        #fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files")
        music = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
        path, _ = QFileDialog.getOpenFileName(
            self,
            "Open file",
            directory=music,
            options=QFileDialog.DontUseNativeDialog)
        print(type(path))
        print(path)
        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(path)))

        print(type(path))
        print(path)
Exemple #43
0
    def __init__(self):
        self.backend = DURRABackendExt()

        self.lastlog = ""

        # add more dirs and stuff, setup, ...
        app_data_location = QStandardPaths.AppDataLocation
        pykrita_directory = QStandardPaths.writableLocation(app_data_location)
        if not CONTEXT_KRITA:
            pykrita_directory = os.path.join(pykrita_directory, "krita")
        pykrita_directory = os.path.join(pykrita_directory, "pykrita")
        self.pykrita_directory = pykrita_directory

        self.script_abs_path = os.path.dirname(os.path.realpath(__file__))
Exemple #44
0
 def running_change(self, delay=0, execute_count=1, speed=1,
                    comparison_info: dict = None,
                    path=QStandardPaths.writableLocation(
                        QStandardPaths.DocumentsLocation) + '/jam_control/current.jam'):
     if comparison_info is None:
         comparison_info = {"areas": [(0, 0, 0, 0), ], "pixs": ["j_temp/triggerpix00.png", ], "sampling_same": 0.9,
                            "dtime": 500}
     self.comparison_info = comparison_info
     print('runningchanged', self.waiting and not self.stop_wait and not self.listening)
     if self.waiting and not self.stop_wait and not self.listening:
         print("中止等待")
         self.stop_wait = True
         self.showrect_signal.emit(False)
         self.showm_signal.emit("中止等待!")
     else:
         if self.listening:
             print('正在录制动作,不能播放!')
             self.showm_signal.emit('正在录制动作,不能播放!')
             return
         if self.running:
             print("播放中停止")
             self.controlerrun_stop()
         elif not self.running:
             def on_press(key):
                 if key == keyboard.Key.f4:
                     self.controlerrun_stop()
                     self.runnerstopper.stop()
             self.runnerstopper = keyboard.Listener(on_press=on_press)
             self.runnerstopper.start()
             if os.path.exists(path):
                 self.controlerrun_start(delay=delay, path=path,
                                         execute_count=execute_count, speed=speed)
             else:
                 self.controlerrun_start(delay=delay, execute_count=execute_count,
                                         speed=speed,
                                         path=QStandardPaths.writableLocation(
                                             QStandardPaths.DocumentsLocation) + '/jam_control/current.jam')
Exemple #45
0
    def _set_defaults(self):
        """Set settings default values for fields that do not already exist"""

        # Hidden settings
        self._get_or_set('version', 'pdf')
        self._get_or_set(
            'lastDir',
            QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation))
        self._get_or_set(
            'lastSSHBackupDir',
            QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation))
        self._get_or_set('lastSaveMode', 'pdf')
        self._get_or_set('KDF.Algorithm', '')
        self._get_or_set('KDF.Salt', '')
        self._get_or_set('KDF.Iterations', '')
        self._get_or_set('KDF.Hash', '')
        #
        # Settings on the Settings dialog
        self._get_or_set('downloadURL',
                         'http://10.11.99.1/download/%s/placeholder')
        self._get_or_set('uploadURL', 'http://10.11.99.1/upload')
        self._get_or_set('listFolderURL', 'http://10.11.99.1/documents/%s')
        self._get_or_set('HTTPTimeout', 60)
        self._get_or_set('HTTPShortTimeout', 1.0)
        self._get_or_set('PNGResolution', 360)
        self._get_or_set('TabletHostname', '')
        self._get_or_set('SSHUsername', 'root')
        self._get_or_set('TabletDocumentsDir',
                         '/home/root/.local/share/remarkable/xochitl')

        # Group containing all settings encrypted with the master key
        self.beginGroup('Encrypted')
        self._get_or_set('TestString.IV', '')
        self._get_or_set('TestString.CipherText', '')
        self._get_or_set('SSHPassword.IV', '')
        self._get_or_set('SSHPassword.CipherText', '')
        self.endGroup()
Exemple #46
0
def getShortcutIcon(shortcut):
    if shortcut["icon"]:
        icon = QIcon(shortcut["icon"])
        if not icon.isNull():
            return icon
    iconProvider = QFileIconProvider()
    if shortcut["path"] == COMPUTER_PATH:
        return QIcon(":/images/user-home.png")
    elif shortcut["path"] == DOCUMENTS_PATH:
        documentsIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)))
        if documentsIcon.isNull():
            return QIcon(":/images/folder-documents.png")
        else:
            return documentsIcon
    elif shortcut["path"] == MUSIC_PATH:
        musicIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.MusicLocation)))
        if musicIcon.isNull():
            return QIcon(":/images/folder-sound.png")
        else:
            return musicIcon
    elif shortcut["path"] == PICTURES_PATH:
        picturesIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)))
        if picturesIcon.isNull():
            return QIcon(":/images/folder-image.png")
        else:
            return picturesIcon
    else:
        url = QUrl.fromUserInput(shortcut["path"])
        if url.scheme() == "file":
            if os.path.exists(shortcut["path"]):
                icon = iconProvider.icon(QFileInfo(url.toLocalFile()))
                if not icon.isNull():
                    return icon
            return QIcon(":/images/unknown.png")
        else:
            return QIcon(":/images/httpurl.png")
    return QIcon(":/images/unknown.png")
 def get_fits(catname, filename, url, is_gzipped):
     cache_path = os.path.join(QStandardPaths.writableLocation(QStandardPaths.CacheLocation), catname)
     file_path = os.path.join(cache_path, '{}.gz'.format(filename))
     try:
         os.makedirs(cache_path)
     except FileExistsError:
         pass
     if not os.path.exists(file_path):
         if is_gzipped:
             urllib.request.urlretrieve(url.format("{}.gz".format(filename)), file_path )
         else:
             request = urllib.request.urlopen(url.format(filename))
             with gzip.open(file_path, 'wb') as f:
                 f.write(request.read())
     return file_path
Exemple #48
0
def init_logger():
    logging.basicConfig(level=logging.INFO)
    directory = QStandardPaths.writableLocation(
        QStandardPaths.AppLocalDataLocation)
    if not os.path.exists(directory):
        os.mkdir(directory)
    path = os.path.join(directory, "vial.log")
    handler = RotatingFileHandler(path,
                                  maxBytes=5 * 1024 * 1024,
                                  backupCount=5)
    handler.setFormatter(
        logging.Formatter(
            "%(asctime)s - %(levelname)s - %(module)s:%(lineno)d - %(message)s"
        ))
    logging.getLogger().addHandler(handler)
Exemple #49
0
    def __init__(self):
        from src import get_metadata
        md = get_metadata()

        dir_program = Path(md.dir_program)
        is_portable = (dir_program / "portable").is_file()

        if is_portable:
            self.__dir_backup = dir_program / "appdata" / "backups"
            self.__dir_config = dir_program / "appdata"
            self.__dir_screenshots = dir_program / "appdata" / "screenshots"
        else:
            from os import environ
            from PyQt5.QtCore import QStandardPaths

            app_name = md.app_name

            config = environ.get('APPDATA') or environ.get('XDG_CONFIG_HOME')
            config = Path(config) if config else Path.home() / ".config"

            documents = Path(QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation))
            pictures = Path(QStandardPaths.writableLocation(QStandardPaths.PicturesLocation))

            self.__dir_backup = documents / app_name / "backups"
            self.__dir_config = config / app_name
            self.__dir_screenshots = pictures / app_name

        self.__dir_backup.mkdir(exist_ok=True, parents=True)
        self.__dir_config.mkdir(exist_ok=True, parents=True)
        self.__dir_screenshots.mkdir(exist_ok=True, parents=True)

        self.__dir_i18n = dir_program / "i18n"

        self.__file_input_conf = self.__dir_config / "input.conf"
        self.__file_mpv_conf = self.__dir_config / "mpv.conf"
        self.__file_settings = self.__dir_config / "settings.json"
Exemple #50
0
 def __init__(self, id=0):
     super(ActionController, self).__init__()
     self.id = id
     self.listening = False
     self.running = False
     self.stop_wait = False
     self.waiting = False
     self.execute_count = 1
     self.delay = 0
     self.speed = 1
     self.comparison_info = None
     documentpath = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
     self.open_path = documentpath + '/jam_control/current.jam'
     if not os.path.exists(documentpath + '/jam_control'):
         os.mkdir(documentpath + '/jam_control')
Exemple #51
0
 def save_autocenter(self):
     path = QFileDialog.getSaveFileName(
         self, 'Save Flipangle Data',
         QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),
         'csv (*.csv)')
     if not path[0] == '':
         with open(path[0], mode='w', newline='') as file:
             writer = csv.writer(file, delimiter=',')
             writer.writerow(['Autocenter Data', params.dataTimestamp])
             writer.writerow([''])
             writer.writerow(['frequency [MHz]', 'fft peak magnitude'])
             for n in range(len(self.freqSpace)):
                 writer.writerow(
                     [round(self.freqSpace[n], 5), self.peaks[n]])
         print("\nAutosavedata saved.")
Exemple #52
0
    def setup(self):
        self.script_abs_path = os.path.dirname(os.path.realpath(__file__))
        self.ui_file = os.path.join(self.script_abs_path, UI_FILE)
        self.ui = load_ui(self.ui_file)

        self.ui.e_name_of_script.textChanged.connect(self.name_change)
        self.ui.cancel_button.clicked.connect(self.cancel)
        self.ui.create_button.clicked.connect(self.create)

        app_data_location = QStandardPaths.AppDataLocation
        target_directory = QStandardPaths.writableLocation(app_data_location)
        if not CONTEXT_KRITA:
            target_directory = os.path.join(target_directory, "krita")
        target_directory = os.path.join(target_directory, "pykrita")
        self.target_directory = target_directory
Exemple #53
0
 def init(self):
     self.app_name = qApp.applicationName().lower()
     self.app_dir = Path(
         QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation))
     self.app_dir.mkdir(exist_ok=True)
     settings_file = f"{self.app_name}.ini"
     self.settings = QSettings(
         self.app_dir.joinpath(settings_file).as_posix(),
         QSettings.IniFormat)
     self.settings.sync()
     self.data = DataStore(self.app_dir)
     self.app_state_store = AppStateStore(self.data)
     self.folder_store = FolderStore(self.data)
     self.step_store = StepStore(self.data)
     self.environment_store = EnvironmentStore(self.data)
     self.worker_pool = WorkerPool(self)
Exemple #54
0
class Resources(QObject):

    resDir = os.path.abspath('res')

    appDataDir = QStandardPaths.writableLocation(
        QStandardPaths.AppDataLocation)

    soundFileExt = '.wav'

    @pyqtSlot(str, result=str)
    def getSoundPath(self, soundName):
        soundFile = soundName + self.soundFileExt
        path = os.path.join(self.appDataDir, soundFile)
        if not os.path.exists(path):
            path = os.path.join(self.resDir, soundFile)
        return path
Exemple #55
0
    def _gstmediacue_file_dialog():
        path = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)

        files, _ = QFileDialog.getOpenFileNames(MainWindow(), 'Choose files',
                                                path, UriInputSettings.exts())

        options = []
        pipe = 'URIInput!' + config['Gst']['Pipeline']

        for file in files:
            elements = {'URIInput': {'uri': 'file://' + file}}
            options.append({'media': {'pipe': pipe, 'elements': elements},
                            'type': config['Gst']['CueType'],
                            'name': os.path.basename(file)})

        return options
Exemple #56
0
def _writable_location(typ):
    """Wrapper around QStandardPaths.writableLocation."""
    qapp = QCoreApplication.instance()
    orgname = qapp.organizationName()
    # We need to temporarily unset the organisationname here since the
    # webinspector wants it to be set to store its persistent data correctly,
    # but we don't want that to happen.
    qapp.setOrganizationName(None)
    try:
        path = QStandardPaths.writableLocation(typ)
    finally:
        qapp.setOrganizationName(orgname)
    if not path:
        raise ValueError("QStandardPaths returned an empty value!")
    # Qt seems to use '/' as path separator even on Windows...
    path = path.replace('/', os.sep)
    return path
 def __init__(self):
     QObject.__init__(self)
     documentsLocation = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
     self.databaseFile = os.path.join(documentsLocation, "quickpanel.db")
     self._settings = _Settings(self.databaseFile)
     self.globalKey = GlobalKey()
     self.quickPanel = QuickPanel(self)
     self.actionConfigure = QAction(QIcon(":/images/configure.png"), \
             self.tr("&Configure"), self)
     self.actionExit = QAction(QIcon(":/images/close.png"), \
             self.tr("&Exit"), self)
     self.trayIcon = QSystemTrayIcon(QIcon(":/images/angelfish.png"))
     self.contextMenu = QMenu()
     self.contextMenu.addAction(self.actionConfigure)
     self.contextMenu.addAction(self.actionExit)
     self.trayIcon.setContextMenu(self.contextMenu)
     self.actionConfigure.triggered.connect(self.configure)
     self.actionExit.triggered.connect(self.exit)
     self.trayIcon.activated.connect(self.onTrayIconActivated)
Exemple #58
0
    def __init__(self, url, apithread):
        super(KCView, self).__init__()

        am = NetworkAccessManager(self, apithread)
        self.web_view.page().setNetworkAccessManager(am)

        disk_cache = QNetworkDiskCache()
        cache_location = QStandardPaths.writableLocation(QStandardPaths.CacheLocation)
        disk_cache.setCacheDirectory(cache_location)
        am.setCache(disk_cache)

        self.cookiejar = CookieJar()
        am.setCookieJar(self.cookiejar)

        web_setting = QtWebKit.QWebSettings.globalSettings()
        web_setting.setAttribute(QtWebKit.QWebSettings.PluginsEnabled, True)
        web_setting.setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, True)

        self.web_view.load(url)
        self.web_view.show()
Exemple #59
0
    def load(self):
        """ Load user settings file from disk, merging with allowed settings in default settings file.
        Creates user settings if missing. """

        # Default and user settings objects
        default_settings, user_settings = {}, {}

        # try to load default settings, on failure will raise exception to caller
        default_settings = self.read_from_file(self.default_settings_filename)

        # Try to find user settings file
        file_path = QStandardPaths.locate(QStandardPaths.ConfigLocation, self.settings_filename)

        # If user settings file doesn't exist yet, try to create a default settings file
        if not file_path:
            writable_path = QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)

            # Create folder if not found
            if not os.path.exists(writable_path.encode('UTF-8')):
                try:
                    os.mkdir(writable_path)
                except Exception as ex:
                    msg = ("Couldn't create {} folder for openshot:\n{}\n{}".format(self.data_type, writable_path, ex))
                    log.error(msg)
                    raise Exception(msg)

            # Set path to user settings file (will be created below)
            file_path = os.path.join(writable_path, self.settings_filename)

        # File was found, try to load settings
        else:
            # Will raise exception to caller on failure to read
            user_settings = self.read_from_file(file_path)

        # Merge default and user settings, excluding settings not in default, Save settings
        self._data = self.merge_settings(default_settings, user_settings)

        # Return success of saving user settings file back after merge
        return self.write_to_file(file_path, self._data)