예제 #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
예제 #2
0
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
예제 #3
0
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))
예제 #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
예제 #5
0
    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()
예제 #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 ''
예제 #7
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)
    # TODO: fix error if standardLocations is not what we expect
    try:
        if isOSX():
            return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]), "Pesterchum/")
        elif isLinux():
            return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]), ".pesterchum/")
        else:
            return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]), "pesterchum/")
    except UnicodeDecodeError:
        return ''
예제 #8
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
예제 #9
0
    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()
예제 #10
0
 def exportFile(self):
     fileFormats = [
         (self.tr("PostScript OT font {}").format("(*.otf)")),
         (self.tr("TrueType OT font {}").format("(*.ttf)")),
     ]
     state = settings.exportFileDialogState()
     # TODO: font.path as default?
     # TODO: store per-font export path in lib
     directory = None if state else QStandardPaths.standardLocations(
         QStandardPaths.DocumentsLocation)[0]
     dialog = QFileDialog(
         self, self.tr("Export File"), directory,
         ";;".join(fileFormats))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     ok = dialog.exec_()
     settings.setExportFileDialogState(dialog.saveState())
     if ok:
         fmt = "ttf" if dialog.selectedNameFilter(
             ) == fileFormats[1] else "otf"
         path = dialog.selectedFiles()[0]
         try:
             self._font.export(path, fmt)
         except Exception as e:
             errorReports.showCriticalException(e)
예제 #11
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     state = settings.saveFileDialogState()
     path = self._font.path or self._font.binaryPath
     if path:
         directory = os.path.dirname(path)
     else:
         directory = None if state else QStandardPaths.standardLocations(
             QStandardPaths.DocumentsLocation)[0]
     # TODO: switch to directory dlg on platforms that need it
     dialog = QFileDialog(
         self, self.tr("Save File"), directory,
         ";;".join(fileFormats.keys()))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if directory:
         dialog.setDirectory(directory)
     ok = dialog.exec_()
     settings.setSaveFileDialogState(dialog.saveState())
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         self.saveFile(path, fileFormats[nameFilter])
         self.setWindowTitle(self.fontTitle())
예제 #12
0
def main():
    """ Main loop to run test
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    print('home_dir:', home_dir)
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    print('stdPwlDict:', stdPwlDict)
예제 #13
0
def get(name):
    """ Retrieve setting and convert result
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    settings = QSettings("Davide Setti", "Lector")
    if name == 'scanner:height':
        return int(settings.value(name, 297))
    elif name == 'scanner:width':
        return int(settings.value(name, 210))
    elif name == 'scanner:resolution':
        return int(settings.value(name, 300))
    elif name == 'scanner:mode':
        return str(settings.value(name, "Color"))
    elif name == 'scanner:device':
        return str(settings.value(name, ""))
    elif name == 'editor:font':
        return settings.value(name, QFont(QFont("Courier New", 10)))
    elif name == 'editor:symbols':
        return settings.value(name)
    elif name in ('editor:clear', 'editor:spell', 'editor:whiteSpace',
                  'spellchecker:pwlLang',):
        return str(settings.value(name, "true")).lower() == "true"
    elif name in ('log:errors'):
        return str(settings.value(name, "false")).lower() == "true"
    elif name == 'spellchecker:pwlDict':
        return str(settings.value(name, stdPwlDict))
    else:
        return str(settings.value(name, ""))
예제 #14
0
    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)
예제 #15
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())
예제 #16
0
파일: utils.py 프로젝트: har5ha/qutebrowser
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)
예제 #17
0
 def _test_against_qt(self, location, qt_location):
     paths = get_standard_paths(location)
     path_strs = []
     for path in paths:
         assert_is_instance(path, pathlib.Path)
         path_strs.append(path.as_posix())
     eq_(path_strs, QStandardPaths.standardLocations(qt_location))
예제 #18
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
예제 #19
0
    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)
예제 #20
0
파일: app.py 프로젝트: daleathan/moneyguru
    def __init__(self, filepath=None):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        global APP_PREFS
        APP_PREFS = self.prefs
        locale = QLocale.system()
        dateFormat = self.prefs.dateFormat
        decimalSep = locale.decimalPoint()
        groupingSep = locale.groupSeparator()
        cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0]
        appdata = getAppData()
        DateEdit.DATE_FORMAT = dateFormat
        self.model = MoneyGuruModel(
            view=self, date_format=dateFormat, decimal_sep=decimalSep,
            grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata,
        )
        # on the Qt side, we're single document based, so it's one doc per app.
        self.doc = Document(app=self)
        self.doc.model.connect()
        self.mainWindow = MainWindow(doc=self.doc)
        self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self)
        self.aboutBox = AboutBox(self.mainWindow, self)
        self.initialFilePath = None
        if filepath and op.exists(filepath):
            self.initialFilePath = filepath
        elif self.prefs.recentDocuments:
            self.initialFilePath = self.prefs.recentDocuments[0]

        self.finishedLaunching.connect(self.applicationFinishedLaunching)
        QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
예제 #21
0
파일: app.py 프로젝트: brownnrl/moneyguru
    def __init__(self, filepath=None):
        QObject.__init__(self)
        QTimer.singleShot(0, self.__launchTimerTimedOut)
        self.prefs = Preferences()
        self.prefs.load()
        global APP_PREFS
        APP_PREFS = self.prefs
        locale = QLocale.system()
        dateFormat = self.prefs.dateFormat
        decimalSep = locale.decimalPoint()
        groupingSep = locale.groupSeparator()
        cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0]
        DateEdit.DATE_FORMAT = dateFormat
        self.model = MoneyGuruModel(
            view=self, date_format=dateFormat, decimal_sep=decimalSep,
            grouping_sep=groupingSep, cache_path=cachePath
        )
        self.mainWindow = MainWindow(app=self)
        self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self)
        self.aboutBox = AboutBox(self.mainWindow, self)
        self.initialFilePath = None
        if filepath and op.exists(filepath):
            self.initialFilePath = filepath
        elif self.prefs.recentDocuments:
            self.initialFilePath = self.prefs.recentDocuments[0]

        self.finishedLaunching.connect(self.applicationFinishedLaunching)
        QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
예제 #22
0
    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)
예제 #23
0
 def test__app_local_data(self):
     if qt_version < (5, 4, 1):
         raise SkipTest
     paths = get_standard_paths(Location.app_local_data)
     path_strs = []
     for path in paths:
         assert_is_instance(path, pathlib.Path)
         path_strs.append(path.as_posix())
     qt_path_strs = QStandardPaths.standardLocations(
         QStandardPaths.AppLocalDataLocation,
     )
     if platform.system() == 'Darwin':
         # Exclude bundle path on OS X. See comments in
         # `get_standard_paths` implementation for more information.
         if qt_path_strs[-1].rstrip('/').endswith('Python.app'):
             qt_path_strs = qt_path_strs[:-1]
     elif platform.system() == 'Windows':
         # Exclude paths relative to executable. See comments in
         # `get_standard_paths` implementation for more information.
         python_loc = (pathlib.Path(sys.executable) / '..').resolve()
         qt_path_strs = [
             ps for ps in qt_path_strs
             if ps not in (
                 python_loc.as_posix(), (python_loc / 'data').as_posix(),
             )
         ]
     eq_(path_strs, qt_path_strs)
예제 #24
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
예제 #25
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
예제 #26
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())
예제 #27
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
예제 #28
0
 def _getCacheDir(self):
     local_data_dir = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)
     path = os.path.abspath(local_data_dir[0])
     try:
         # Apparently the cache location might not exist
         os.makedirs(path)
     except:
         pass
     return path
예제 #29
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))
예제 #30
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()
예제 #31
0
    def __init__(self, tab, editorPositionToSourceLineFunc,
                 sourceLineToEditorPositionFunc):

        QWebView.__init__(self)
        self.tab = tab

        self.syncscroll = SyncScroll(self.page().mainFrame(),
                                     editorPositionToSourceLineFunc,
                                     sourceLineToEditorPositionFunc)
        ReTextWebPreview.__init__(self, tab.editBox)

        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.page().linkClicked.connect(self._handleLinkClicked)
        self.settings().setAttribute(
            QWebSettings.LocalContentCanAccessFileUrls, False)
        # Avoid caching of CSS
        self.settings().setObjectCacheCapacities(0, 0, 0)

        self.cache = QNetworkDiskCache()
        cacheDirectory = QStandardPaths.writableLocation(
            QStandardPaths.CacheLocation)
        self.cache.setCacheDirectory(cacheDirectory)
        self.page().networkAccessManager().setCache(self.cache)
예제 #32
0
    def __init__(self, parent=None):
        super(SlippyMap, self).__init__(parent)

        self._offset = QPoint()
        self._tilesRect = QRect()
        self._tilePixmaps = {}  # Point(x, y) to QPixmap mapping
        self._manager = QNetworkAccessManager()
        self._url = QUrl()
        # public vars
        self.width = 400
        self.height = 300
        self.zoom = 15
        self.latitude = 59.9138204
        self.longitude = 10.7387413

        self._emptyTile = QPixmap(TDIM, TDIM)
        self._emptyTile.fill(Qt.lightGray)

        cache = QNetworkDiskCache()
        cache.setCacheDirectory(
            QStandardPaths.writableLocation(QStandardPaths.CacheLocation))
        self._manager.setCache(cache)
        self._manager.finished.connect(self.handleNetworkData)
예제 #33
0
 def __flashMicroPython(self):
     """
     Private slot to flash the default MicroPython firmware to the device.
     """
     # Attempts to find the path on the filesystem that represents the
     # plugged in micro:bit board in maintenance mode.
     deviceDirectory = Utilities.findVolume("MAINTENANCE")
     if not deviceDirectory:
         # BBC micro:bit is not ready or not mounted
         E5MessageBox.critical(
             self.microPython, self.tr("Flash MicroPython Firmware"),
             self.tr('The BBC micro:bit is not ready for flashing. See the'
                     ' <a href="https://microbit.org/guide/firmware/">'
                     'micro:bit web site</a> for details.'))
     else:
         downloadsPath = QStandardPaths.standardLocations(
             QStandardPaths.DownloadLocation)[0]
         firmware = E5FileDialog.getOpenFileName(
             self.microPython, self.tr("Flash MicroPython Firmware"),
             downloadsPath,
             self.tr("MicroPython Firmware Files (*.hex);;All Files (*)"))
         if firmware and os.path.exists(firmware):
             shutil.copy2(firmware, deviceDirectory)
예제 #34
0
 def press_record(self):
     """Press record"""
     if self.PLAYER.get_state() == vlc.State.Playing:
         record_state = self.button_record.isChecked()
         if record_state:
             time_current = time.strftime('%Y%m%d_%H%M%S', time.gmtime())
             station_name = self.LABEL_STATION.text().split(' ')[0]
             file_name = "{0}_{1}_record.mp3".format(
                 station_name, time_current)
             music_path = QStandardPaths.writableLocation(
                 QStandardPaths.MusicLocation)
             music_file_path = os.path.join(music_path, file_name)
             transcode = "#transcode{vcodec=none,acodec=mp3,ab=256,channels=2,samplerate=44100}"
             params = ":duplicate{dst=display,dst=std{access=file,mux=,dst=" + music_file_path + "}}"
             options = ("sout=" + transcode + params)
             self.PLAYER.set_mrl(self.CURRENT_URL, options)
             self.PLAYER.play()
         else:
             self.cancel_record()
             title = self.LABEL_STATION.text()
             self.player_play(title, self.CURRENT_URL)
     else:
         self.cancel_record()
예제 #35
0
    def removeOldFiles(self):
        """Function that removes the settings from previous versions."""

        # This is the very first way settings were stored.
        root = QStandardPaths.standardLocations(
            QStandardPaths.GenericConfigLocation)[0]
        path = os.path.join(root, self.name)
        if parse(version) < parse("0.7.0"):
            try:
                os.remove(os.path.join(path, "settings.json"))
                os.rmdir(path)
                logger.debug("Removed old configuration file.")
            except (IOError, OSError):
                pass

        # Fix a naming error in version 2020.1rc0.
        if parse("2020.1rc0") <= parse(version):
            root, _ = os.path.split(self.settings.fileName())
            try:
                os.remove(os.path.join(root, "settings-new.ini"))
                logger.debug("Removed old configuration file.")
            except (IOError, OSError):
                pass
예제 #36
0
 def select_image(self):  #选择图像
     path, _ = QFileDialog.getOpenFileName(
         None, '请选择图片',
         QStandardPaths.writableLocation(QStandardPaths.DesktopLocation),
         '图片文件(*.jpg *.png)')
     if not path:
         return
     img = QPixmap(path)
     img.save('image_temp.jpg')  #为图像设置备份
     img.save('image_temp2.jpg')
     img.save('image_temp3.jpg')
     img.save('search_image.jpg')
     img = img.scaled(self.image1.width(),
                      self.image1.width() / img.width() *
                      img.height())  #缩放图像使其适应控件宽度
     self.image1.setMinimumSize(QtCore.QSize(img.width(), img.height()))
     self.image1.setMaximumSize(QtCore.QSize(img.width(), img.height()))
     self.image2.setMinimumSize(QtCore.QSize(img.width(), img.height()))
     self.image2.setMaximumSize(QtCore.QSize(img.width(), img.height()))
     self.image1.setPixmap(img)
     self.image2.setPixmap(img)
     self.spinBox.setEnabled(True)
     return
예제 #37
0
 def saveRecord(self):
     if not self.is_recording:
         print("saving Audio")
         musicfolder = QStandardPaths.standardLocations(
             QStandardPaths.MusicLocation)[0]
         recname = self.rec_name.replace("-", " ").replace(" - ",
                                                           " ") + ".mp3"
         infile = QFile(self.outfile)
         savefile, _ = QFileDialog.getSaveFileName(
             None, "Speichern als...", f'{musicfolder}/{recname}',
             "Audio (*.mp3)")
         if (savefile != ""):
             if QFile(savefile).exists:
                 QFile(savefile).remove()
             print(f"saving {savefile}")
             if not infile.copy(savefile):
                 QMessageBox.warning(
                     self, "Fehler",
                     f"File {savefile} {infile.errorString()}")
             print(f"Prozess-State: {str(self.process.state())}")
             if QFile(self.outfile).exists:
                 print(f"{self.outfile} existiert")
                 QFile(self.outfile).remove()
예제 #38
0
    def __init__(self, filepath=None):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        global APP_PREFS
        APP_PREFS = self.prefs
        locale = QLocale.system()
        dateFormat = self.prefs.dateFormat
        decimalSep = locale.decimalPoint()
        groupingSep = locale.groupSeparator()
        cachePath = QStandardPaths.standardLocations(
            QStandardPaths.CacheLocation)[0]
        appdata = getAppData()
        DateEdit.DATE_FORMAT = dateFormat
        self.model = MoneyGuruModel(
            view=self,
            date_format=dateFormat,
            decimal_sep=decimalSep,
            grouping_sep=groupingSep,
            cache_path=cachePath,
            appdata_path=appdata,
        )
        # on the Qt side, we're single document based, so it's one doc per app.
        self.doc = Document(app=self)
        self.doc.model.connect()
        self.mainWindow = MainWindow(doc=self.doc)
        self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self)
        self.aboutBox = AboutBox(self.mainWindow, self)
        self.initialFilePath = None
        if filepath and op.exists(filepath):
            self.initialFilePath = filepath
        elif self.prefs.recentDocuments:
            self.initialFilePath = self.prefs.recentDocuments[0]

        self.finishedLaunching.connect(self.applicationFinishedLaunching)
        QCoreApplication.instance().aboutToQuit.connect(
            self.applicationWillTerminate)
예제 #39
0
    def printToPdf(self):

        pdf_printer = QPrinter()
        pdf_printer.setOutputFormat(QPrinter.PdfFormat)
        pdf_printer.setPaperSize(self.frames.sceneRect().size(), QPrinter.Point)
        pdf_printer.setFullPage(True)

        pdf_printer.setOutputFileName(os.path.join(QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),self.projectName+".pdf"))
        pdf_printer.setResolution(144)
        pdf_printer.newPage()
        printDialog = QPrintDialog(pdf_printer, self)
        if(printDialog.exec_() == QDialog.Accepted):
            pdf_painter = QPainter()
            pdf_painter.begin(pdf_printer)
            for i,scene in enumerate(self.frames.sceneCollection):
                # self.frames.setScene(scene)
                # viewport = self.frames.viewport().rect()
                # self.frames.render(pdf_painter, QRectF(pdf_printer.width()*0.25, pdf_printer.height()*0.1,
                #        pdf_printer.width(), pdf_printer.height()/2. ),
                # (self.frames.mapFromScene(QRectF(viewport)).boundingRect()))
                scene.render(pdf_painter)
                if i<len(self.frames.sceneCollection)-1:
                    pdf_printer.newPage()
            pdf_painter.end()
예제 #40
0
파일: __main__.py 프로젝트: Tydus/vidcutter
 def init_settings(self) -> None:
     if sys.platform == 'darwin':
         QSettings.setDefaultFormat(QSettings.IniFormat)
         self.settings = QSettings(self)
     else:
         try:
             settings_path = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation).lower()
         except AttributeError:
             if sys.platform == 'win32':
                 settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', qApp.applicationName().lower())
             elif sys.platform == 'darwin':
                 settings_path = os.path.join(QDir.homePath(), 'Library', 'Preferences',
                                              qApp.applicationName()).lower()
             else:
                 settings_path = os.path.join(QDir.homePath(), '.config', qApp.applicationName()).lower()
         os.makedirs(settings_path, exist_ok=True)
         settings_file = '%s.ini' % qApp.applicationName().lower()
         self.settings = QSettings(os.path.join(settings_path, settings_file), QSettings.IniFormat)
     if self.settings.value('geometry') is not None:
         self.restoreGeometry(self.settings.value('geometry'))
     if self.settings.value('windowState') is not None:
         self.restoreState(self.settings.value('windowState'))
     self.theme = self.settings.value('theme', 'light', type=str)
     self.startupvol = self.settings.value('volume', 100, type=int)
예제 #41
0
 def save_data_csv(self):
     path = QFileDialog.getSaveFileName(
         self, 'Save Acquisitiondata',
         QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),
         'csv (*.csv)')
     if not path[0] == '':
         tab_idx = self.plotTabWidget.currentIndex()
         if tab_idx == 2 or tab_idx == 1:
             try:
                 self.environment.saveData(path[0])
             except:
                 return
         else:
             with open(path[0], mode='w', newline='') as file:
                 writer = csv.writer(file, delimiter=',')
                 writer.writerow([params.dataTimestamp])
                 writer.writerow(['Center frequency', params.freq])
                 writer.writerow([''])
                 writer.writerow(['freq', 'cplx data', 'fft centered'])
                 for n in range(len(params.freqaxis)):
                     writer.writerow([
                         params.freqaxis[n], params.data[n], params.fft[n]
                     ])
         print("\nAcquisitiondata saved.")
예제 #42
0
 def changeBackground(self):
     filename, selectedFilter = QFileDialog.getOpenFileName(self, self.tr("Change Background"), \
         QStandardPaths.writableLocation(QStandardPaths.PicturesLocation), \
         self.tr("Image Files (*.png *.gif *.jpg *.jpeg *.bmp *.mng *ico)"))
     if not filename:
         return
     image = QImage(filename)
     if image.isNull():
         QMessageBox.information(self, self.tr("Change Background"), \
                 self.tr("不能读取图像文件,请检查文件格式是否正确,或者图片是否已经损坏。"))
         return
     if image.width() < 800 or image.height() < 600:
         answer = QMessageBox.information(self, self.tr("Change Background"), \
                 self.tr("不建议设置小于800x600的图片作为背景图案。如果继续,可能会使快捷面板显示错乱。是否继续?"),
                 QMessageBox.Yes | QMessageBox.No,
                 QMessageBox.No)
         if answer == QMessageBox.No:
             return
     self._makeBackground(image)
     moveToCenter(self)
     self.canvas.positWidgets()
     self.update()
     with self.platform.getSettings() as settings:
         settings.setValue("background", filename)
예제 #43
0
    def cutpic(self, save_as=False):  # 图片裁剪函数
        # img = cv2.imread("jamtools截屏/get.png")
        pix = self.pixmap()
        # pix.save('jamtools截屏/background.png')
        paintlayer = self.paintlayer.pixmap()
        paintlayer.save('jamtools截屏/getpainter.png')
        painter = QPainter(pix)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPixmap(0, 0, paintlayer)
        painter.end()  # 一定要end
        pix.save('jamtools截屏/get.png')

        x0 = min(self.x0, self.x1)
        y0 = min(self.y0, self.y1)
        x1 = max(self.x0, self.x1)
        y1 = max(self.y0, self.y1)

        if (x1 - x0) < 1 or (y1 - y0) < 1:
            return
        cropped = (x0, y0, x1, y1)  # 裁剪
        img = Image.open("jamtools截屏/get.png")
        img = img.crop(cropped)
        img.save("jamtools截屏/jam_outputfile.png")
        if save_as:
            path, l = QFileDialog.getSaveFileName(
                self, "选择图片",
                QStandardPaths.writableLocation(
                    QStandardPaths.PicturesLocation),
                "img Files (*.PNG *.jpg *.JPG *.JPEG *.BMP *.ICO)"
                ";;all files(*.*)")
            if path:
                print(path)
                img.save(path)

        # self.hide()
        self.manage_data()
예제 #44
0
파일: protocol.py 프로젝트: schote/GOMRI
 def save_protocol(self):
     print('Saving protocol.')
     colIdx = [1, 3, 5, 7, 9, 11]
     values = []
     #print("row: {}, col: {}".format(row, col))
     for row in range(self.protocol.rowCount()):
         if not any(
             [self.protocol.item(row, col) is None for col in colIdx]):
             rowVals = [
                 int(self.protocol.item(row, col).text()) for col in colIdx
             ]
         elif not self.protocol.item(row, 1) is None:
             rowVals = [int(self.protocol.item(row, 1).text())
                        ] + [None] * len(colIdx[1:-1])
         else:
             rowVals = [None] * len(colIdx)
         values.append(rowVals)
     if values == []:
         print("Empty protocol.")
         return
     else:
         dataframe = pd.DataFrame(data=values,
                                  index=self.cmdList,
                                  columns=[
                                      't_start', 't_stop', 'steps',
                                      'recovery', 'avg_datp', 'avg_meas'
                                  ])
         print(dataframe)
         path = QFileDialog.getSaveFileName(
             self, 'Save Acquisitiondata',
             QStandardPaths.writableLocation(
                 QStandardPaths.DocumentsLocation), 'csv (*.csv)')
         if not path[0] == '':
             with open(path[0], 'w') as file:
                 file.write('Relax Measurement Protocol \n key=00 \n\n' +
                            dataframe.to_csv())
예제 #45
0
    def __init__(self):
        QObject.__init__(self)
        self._settings = None
        # Create the QApplication
        self._app = QApplication(sys.argv)
        self._app.setOrganizationName(Config.ORG_NAME)
        self._app.setApplicationName(Config.APP_NAME)

        # initialize the logger
        logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s", datefmt="%m/%d/%Y %H:%M:%S")
        self._logger = logging.getLogger()
        if getattr(sys, 'frozen', False):
            # remove default (stdout) handler
            self._logger.handlers = []
        self._logger.setLevel(logging.DEBUG)
        app_data_dir = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)
        os.makedirs(app_data_dir, exist_ok=True)
        Config.LOG_FILE_PATH = os.path.join(app_data_dir, "TSMApplication.log")
        Config.BACKUP_DIR_PATH = os.path.join(app_data_dir, "Backups")
        os.makedirs(Config.BACKUP_DIR_PATH, exist_ok=True)
        handler = RotatingFileHandler(Config.LOG_FILE_PATH, mode='w', maxBytes=200000, backupCount=1)
        handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s", "%m/%d/%Y %H:%M:%S"))
        handler.doRollover() # clear the log everytime we start
        self._logger.addHandler(handler)
 def nf2_ui_add_output(x_row):
     fv2_row = x_row
     self.wu_lb_o_pn = QLabel('Output path')
     self.wu_le_o_pn = nf2_new_le()
     self.wu_le_o_pn.setText(
         gf_pj(
             QStandardPaths.writableLocation(
                 QStandardPaths.DownloadLocation), 'TMPS'))
     self.wu_lo.addWidget(self.wu_lb_o_pn, fv2_row, 0, 1, 1,
                          Qt.AlignRight)
     self.wu_lo.addWidget(self.wu_le_o_pn, fv2_row, 1, 1, -1)
     self.wu_lb_o_bn = QLabel('Output base name')
     self.wu_le_o_bn = nf2_new_le()
     self.wu_lb_o_nfo = QLabel('Output file info')
     self.wu_le_o_nfo = nf2_new_le()
     fv2_row += 1
     self.wu_lo.addWidget(self.wu_lb_o_bn, fv2_row, 0, 1, 1,
                          Qt.AlignRight)
     self.wu_lo.addWidget(self.wu_le_o_bn, fv2_row, 1, 1, -1)
     fv2_row += 1
     self.wu_lo.addWidget(self.wu_lb_o_nfo, fv2_row, 0, 1, 1,
                          Qt.AlignRight)
     self.wu_lo.addWidget(self.wu_le_o_nfo, fv2_row, 1, 1, -1)
     return fv2_row
예제 #47
0
파일: constants.py 프로젝트: yxsyxs/QMusic
ProjectName = "QMusic"
ProjectPath = os.path.join(ConfigPath, ProjectName)

MusicManagerPath = os.path.join(ProjectPath, 'music')
PlaylistPath = os.path.join(ProjectPath, 'playlist')
CoverPath = os.path.join(ProjectPath, 'cover')
ArtistCoverPath = os.path.join(CoverPath, 'artist')
AlbumCoverPath = os.path.join(CoverPath, 'album')
SongCoverPath = os.path.join(CoverPath, 'song')
OnlineSongCoverPath = os.path.join(CoverPath, 'onlineSong')
OnlineAlbumCoverPath = os.path.join(CoverPath, 'onlineAlbum')
LevevDBPath = os.path.join(ProjectPath, 'leveldb')
MusicDBFile = os.path.join(ProjectPath, 'music.db')

DownloadSongPath = os.path.join(
    QStandardPaths.writableLocation(QStandardPaths.MusicLocation), 'download')
LRCPath = os.path.join(
    QStandardPaths.writableLocation(QStandardPaths.MusicLocation), 'lyrics')
LogCachePath = os.path.join(Home, '.cache', 'qmuisc')
LogPath = os.path.join(LogCachePath, 'main.log')

paths = [
    ProjectPath, MusicManagerPath, PlaylistPath, CoverPath, ArtistCoverPath,
    AlbumCoverPath, SongCoverPath, OnlineSongCoverPath, OnlineAlbumCoverPath,
    LevevDBPath, DownloadSongPath, LRCPath, LogCachePath
]

for path in paths:
    if not os.path.exists(path):
        os.makedirs(path)
예제 #48
0
파일: renaming.py 프로젝트: zer03nvy/picard
from picard.script import ScriptParser, ScriptSyntaxError, ScriptError
from picard.ui.options import OptionsPage, OptionsCheckError, register_options_page
from picard.ui.ui_options_renaming import Ui_RenamingOptionsPage
from picard.ui.util import enabledSlot
from picard.ui.options.scripting import TaggerScriptSyntaxHighlighter


_DEFAULT_FILE_NAMING_FORMAT = "$if2(%albumartist%,%artist%)/" \
    "$if($ne(%albumartist%,),%album%/,)" \
    "$if($gt(%totaldiscs%,1),%discnumber%-,)" \
    "$if($ne(%albumartist%,),$num(%tracknumber%,2) ,)" \
    "$if(%_multiartist%,%artist% - ,)" \
    "%title%"


_default_music_dir = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)


class RenamingOptionsPage(OptionsPage):

    NAME = "filerenaming"
    TITLE = N_("File Naming")
    PARENT = None
    SORT_ORDER = 40
    ACTIVE = True

    options = [
        config.BoolOption("setting", "windows_compatibility", True),
        config.BoolOption("setting", "ascii_filenames", False),
        config.BoolOption("setting", "rename_files", False),
        config.TextOption(
예제 #49
0
    def __init__(self):
        super().__init__()

        self.settings = QSettings("Vial", "Vial")
        themes.set_theme(self.get_theme())

        self.current_device = None
        self.devices = []
        # create empty VIA definitions. Easier than setting it to none and handling a bunch of exceptions
        self.via_stack_json = {"definitions": {}}
        self.sideload_json = None
        self.sideload_vid = self.sideload_pid = -1

        self.combobox_devices = QComboBox()
        self.combobox_devices.currentIndexChanged.connect(
            self.on_device_selected)

        self.btn_refresh_devices = QToolButton()
        self.btn_refresh_devices.setToolButtonStyle(Qt.ToolButtonTextOnly)
        self.btn_refresh_devices.setText(tr("MainWindow", "Refresh"))
        self.btn_refresh_devices.clicked.connect(self.on_click_refresh)

        layout_combobox = QHBoxLayout()
        layout_combobox.addWidget(self.combobox_devices)
        layout_combobox.addWidget(self.btn_refresh_devices)

        self.layout_editor = LayoutEditor()
        self.keymap_editor = KeymapEditor(self.layout_editor)
        self.firmware_flasher = FirmwareFlasher(self)
        self.macro_recorder = MacroRecorder()
        self.matrix_tester = MatrixTest(self.layout_editor)

        self.editors = [(self.keymap_editor, "Keymap"),
                        (self.layout_editor, "Layout"),
                        (self.macro_recorder, "Macros"),
                        (self.matrix_tester, "Matrix tester"),
                        (self.firmware_flasher, "Firmware updater")]
        Unlocker.global_layout_editor = self.layout_editor

        self.tabs = QTabWidget()
        self.refresh_tabs()

        self.lbl_no_devices = QLabel(
            tr(
                "MainWindow",
                'No devices detected. Connect a Vial-compatible device and press '
                '"Refresh"\n'
                'or select "File" → "Download VIA definitions" in order to enable'
                ' support for VIA keyboards.'))
        self.lbl_no_devices.setAlignment(Qt.AlignCenter)

        layout = QVBoxLayout()
        layout.addLayout(layout_combobox)
        layout.addWidget(self.tabs)
        layout.addWidget(self.lbl_no_devices)
        layout.setAlignment(self.lbl_no_devices, Qt.AlignHCenter)
        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        self.init_menu()

        # cache for via definition files
        self.cache_path = QStandardPaths.writableLocation(
            QStandardPaths.CacheLocation)
        if not os.path.exists(self.cache_path):
            os.makedirs(self.cache_path)
        # check if the via defitions already exist
        if os.path.isfile(os.path.join(self.cache_path, "via_keyboards.json")):
            with open(os.path.join(self.cache_path,
                                   "via_keyboards.json")) as vf:
                self.via_stack_json = json.load(vf)
                vf.close()

        # make sure initial state is valid
        self.on_click_refresh()
예제 #50
0
파일: paths.py 프로젝트: oltulu/zvvradio
            current_version = int(
                QSettings(CONFIG_PATH,
                          QSettings.IniFormat).value("config/version"))
            if current_version < 11:
                src_path = os.path.join(os.getcwd(), "config.ini")
                dst_path = APP_FOLDER
                shutil.copy(src_path, dst_path)
                #copy base
                src_path = os.path.join(os.getcwd(), "zvvbase.db")
                dst_path = APP_FOLDER
                shutil.copy(src_path, dst_path)
    #base path
    BASE_PATH = os.path.join(APP_FOLDER, "zvvbase.db")
    if not os.path.exists(BASE_PATH):
        src_path = os.path.join(os.getcwd(), "zvvbase.db")
        dst_path = APP_FOLDER
        shutil.copy(src_path, dst_path)
    #record path
    RECORD_PATH = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)

if sys.platform.startswith("win"):
    APP_FOLDER = os.getcwd()
    PLS_FOLDER = os.path.join(APP_FOLDER, "playlists")
    CONFIG_PATH = os.path.join(APP_FOLDER, "config.ini")
    BASE_PATH = os.path.join(APP_FOLDER, "zvvbase.db")

BASE_CONNECTION = sqlite3.connect(BASE_PATH)
BASE_CURSOR = BASE_CONNECTION.cursor()

###############################################################################################
예제 #51
0
 def wn_init_ni(self):
     self.wv_i_recent_pn = QStandardPaths.writableLocation(
         QStandardPaths.DesktopLocation)
     self.wv_o_recent_pn = None
예제 #52
0
    "AddTableDialog/autogen identifier/type":
    "bool",
    "AddTableDialog/autonumber/value":
    True,
    "AddTableDialog/autonumber/type":
    "bool",

    # Add footnote dialog
    "AddFootnoteDialog/autogen identifier/value":
    True,
    "AddFootnoteDialog/autogen identifier/type":
    "bool",

    # Application
    "Application/Project folder/value":
    QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation),
    "Application/Project folder/type":
    "str",

    # General
    "General/Document_parsing_interval/value":
    2000,
    "General/Document_parsing_interval/type":
    "int",

    # Editor
    "Editor/Font name/value":
    "Hack",
    "Editor/Font name/type":
    "str",
    "Editor/Font size/value":
예제 #53
0
from collections import OrderedDict
import os

from PyQt5.QtCore import QStandardPaths
from picard import (
    PICARD_APP_NAME,
    PICARD_ORG_NAME,
)

# Install gettext "noop" function in case const.py gets imported directly.
import builtins
builtins.__dict__['N_'] = lambda a: a

# Config directory
_appconfiglocation = QStandardPaths.writableLocation(
    QStandardPaths.AppConfigLocation)
USER_DIR = os.path.normpath(
    os.path.join(_appconfiglocation, PICARD_ORG_NAME, PICARD_APP_NAME))
USER_PLUGIN_DIR = os.path.normpath(os.path.join(USER_DIR, "plugins"))

# Network Cache default settings
CACHE_DIR = os.path.normpath(
    QStandardPaths.writableLocation(QStandardPaths.CacheLocation))
CACHE_SIZE_IN_BYTES = 100 * 1000 * 1000

# AcoustID client API key
ACOUSTID_KEY = 'v8pQ6oyB'
ACOUSTID_HOST = 'api.acoustid.org'
ACOUSTID_PORT = 80
FPCALC_NAMES = ['fpcalc', 'pyfpcalc']
예제 #54
0
파일: util.py 프로젝트: legwak/dupeguru
def getAppData():
    return QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]
예제 #55
0
 def _special_folder_path(special_folder, appname=None):
     if special_folder == SpecialFolder.Cache:
         qtfolder = QStandardPaths.CacheLocation
     else:
         qtfolder = QStandardPaths.DataLocation
     return QStandardPaths.standardLocations(qtfolder)[0]
예제 #56
0
파일: main.py 프로젝트: AFM-analysis/PyJibe
    def __init__(self, *args, **kwargs):
        """Initialize PyJibe

        If you pass the "--version" command line argument, the
        application will print the version after initialization
        and exit.
        """
        super(PyJibe, self).__init__(*args, **kwargs)
        # Settings are stored in the .ini file format. Even though
        # `self.settings` may return integer/bool in the same session,
        # in the next session, it will reliably return strings. Lists
        # of strings (comma-separated) work nicely though.
        QtCore.QCoreApplication.setOrganizationName("AFM-Analysis")
        QtCore.QCoreApplication.setOrganizationDomain("pyjibe.mpl.mpg.de")
        QtCore.QCoreApplication.setApplicationName("PyJibe")
        QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
        #: PyJibe settings
        self.settings = QtCore.QSettings()
        self.settings.setIniCodec("utf-8")

        # update check
        self._update_thread = None
        self._update_worker = None

        # load ui files
        path_ui = pkg_resources.resource_filename("pyjibe.head", "main.ui")
        uic.loadUi(path_ui, self)

        self.setWindowTitle("PyJibe {}".format(__version__))
        # Disable native menubar (e.g. on Mac)
        self.menubar.setNativeMenuBar(False)
        # Connect menu entries
        # File menu
        self.action_open_bulk.triggered.connect(self.on_open_bulk)
        self.action_open_single.triggered.connect(self.on_open_single)
        self.action_open_multiple.triggered.connect(self.on_open_multiple)
        # Edit menu
        self.actionPreferences.triggered.connect(self.on_preferences)
        # Tool menu
        self.actionConvert_AFM_data.triggered.connect(self.on_tool_convert)
        # Help menu
        self.actionDocumentation.triggered.connect(self.on_documentation)
        self.actionSoftware.triggered.connect(self.on_software)
        self.actionAbout.triggered.connect(self.on_about)

        #: Extensions
        store_path = os_path.join(
            QStandardPaths.writableLocation(
                QStandardPaths.AppLocalDataLocation), "extensions")
        try:
            self.extensions = ExtensionManager(store_path)
        except BaseException:
            QtWidgets.QMessageBox.warning(
                self,
                "Extensions automatically disabled",
                "Some extensions could not be loaded and were disabled:\n\n" +
                traceback.format_exc(),
            )

        self.subwindows = []
        self.subwindow_data = []
        self.mdiArea.cascadeSubWindows()
        self.showMaximized()
        # if "--version" was specified, print the version and exit
        if "--version" in sys.argv:
            print(__version__)
            QtWidgets.QApplication.processEvents(QtCore.QEventLoop.AllEvents,
                                                 300)
            sys.exit(0)

        # check for updates
        do_update = int(self.settings.value("check for updates", 1))
        self.on_action_check_update(do_update)

        self.show()
        self.raise_()
        self.activateWindow()
        self.setWindowState(QtCore.Qt.WindowState.WindowActive)
예제 #57
0
        def change_homescreen():
            le_dir = ((__class__.last_hs_dir and [__class__.last_hs_dir])
                      or QStandardPaths.standardLocations(
                          QStandardPaths.DesktopLocation)
                      or QStandardPaths.standardLocations(
                          QStandardPaths.PicturesLocation)
                      or QStandardPaths.standardLocations(
                          QStandardPaths.HomeLocation) or [''])[0]
            filename, __ = QFileDialog.getOpenFileName(self,
                                                       _("Choose Homescreen"),
                                                       le_dir)

            if not filename:
                return  # user cancelled

            __class__.last_hs_dir = os.path.dirname(
                filename)  # remember previous location

            if filename.lower().endswith('.toif') or filename.lower().endswith(
                    '.toig'):
                which = filename.lower()[-1].encode(
                    'ascii')  # .toif or .toig = f or g in header
                if which == b'g':
                    # For now I couldn't get Grayscale TOIG to work on any device, disabled
                    handler.show_error(
                        _('Grayscale TOI files are not currently supported. Try a PNG or JPG file instead.'
                          ))
                    return
                if not is_model_T:
                    handler.show_error(
                        _('At this time, only the Trezor Model T supports the direct loading of TOIF files. Try a PNG or JPG file instead.'
                          ))
                    return
                try:
                    img = open(filename, 'rb').read()
                    if img[:8] != b'TOI' + which + int(hs_cols).to_bytes(
                            2, byteorder='little') + int(hs_rows).to_bytes(
                                2, byteorder='little'):
                        handler.show_error(
                            _('Image must be a TOI{} file of size {}x{}').
                            format(
                                which.decode('ascii').upper(), hs_cols,
                                hs_rows))
                        return
                except OSError as e:
                    handler.show_error('Error reading {}: {}'.format(
                        filename, e))
                    return
            else:

                def read_and_convert_using_qt_to_raw_mono(
                        handler, filename, hs_cols, hs_rows, invert=True):
                    img = QImage(filename)
                    if img.isNull():
                        handler.show_error(
                            _('Could not load the image {} -- unknown format or other error'
                              ).format(os.path.basename(filename)))
                        return
                    if (img.width(), img.height()) != (
                            hs_cols, hs_rows):  # do we need to scale it ?
                        img = img.scaled(
                            hs_cols, hs_rows, Qt.IgnoreAspectRatio,
                            Qt.SmoothTransformation
                        )  # force to our dest size. Note that IgnoreAspectRatio guarantess the right size. Ther other modes don't
                        if img.isNull() or (img.width(), img.height()) != (
                                hs_cols, hs_rows):
                            handler.show_error(
                                _("Could not scale image to {} x {} pixels").
                                format(hs_cols, hs_rows))
                            return
                    bm = QBitmap.fromImage(
                        img, Qt.MonoOnly)  # ensures 1bpp, dithers any colors
                    if bm.isNull():
                        handler.show_error(
                            _('Could not convert image to monochrome'))
                        return
                    target_fmt = QImage.Format_Mono
                    img = bm.toImage().convertToFormat(
                        target_fmt,
                        Qt.MonoOnly | Qt.ThresholdDither | Qt.AvoidDither
                    )  # ensures MSB bytes again (above steps may have twiddled the bytes)
                    lineSzOut = hs_cols // 8  # bits -> num bytes per line
                    bimg = bytearray(hs_rows *
                                     lineSzOut)  # 1024 bytes for a 128x64 img
                    bpl = img.bytesPerLine()
                    if bpl < lineSzOut:
                        handler.show_error(
                            _("Internal error converting image"))
                        return
                    # read in 1 scan line at a time since the scan lines may be > our target packed image
                    for row in range(hs_rows):
                        # copy image scanlines 1 line at a time to destination buffer
                        ucharptr = img.constScanLine(
                            row)  # returned type is basically void*
                        ucharptr.setsize(
                            bpl)  # inform python how big this C array is
                        b = bytes(ucharptr)  # aaand.. work with bytes.

                        begin = row * lineSzOut
                        end = begin + lineSzOut
                        bimg[begin:end] = b[0:lineSzOut]
                        if invert:
                            for i in range(begin, end):
                                bimg[i] = ~bimg[i] & 0xff  # invert b/w
                    return bytes(bimg)

                def read_and_convert_using_qt_to_toif(handler, filename,
                                                      hs_cols, hs_rows):
                    img = QImage(filename)
                    if img.isNull():
                        handler.show_error(
                            _('Could not load the image {} -- unknown format or other error'
                              ).format(os.path.basename(filename)))
                        return
                    if (img.width(), img.height()) != (
                            hs_cols, hs_rows):  # do we need to scale it ?
                        img = img.scaled(
                            hs_cols, hs_rows, Qt.IgnoreAspectRatio,
                            Qt.SmoothTransformation
                        )  # force to our dest size. Note that IgnoreAspectRatio guarantess the right size. Ther other modes don't
                        if img.isNull() or (img.width(), img.height()) != (
                                hs_cols, hs_rows):
                            handler.show_error(
                                _("Could not scale image to {} x {} pixels").
                                format(hs_cols, hs_rows))
                            return
                    target_fmt = QImage.Format_RGB888
                    img = img.convertToFormat(
                        QImage.Format_Indexed8
                    ).convertToFormat(
                        target_fmt
                    )  # dither it down to 256 colors to reduce image complexity then back up to 24 bit for easy reading
                    if img.isNull():
                        handler.show_error(
                            _("Could not dither or re-render image"))
                        return

                    def qimg_to_toif(img, handler):
                        try:
                            import struct, zlib
                        except ImportError as e:
                            handler.show_error(
                                _("Could not convert image, a required library is missing: {}"
                                  ).format(e))
                            return
                        data, pixeldata = bytearray(), bytearray()
                        data += b'TOIf'
                        for y in range(img.width()):
                            for x in range(img.height()):
                                rgb = img.pixel(x, y)
                                r, g, b = qRed(rgb), qGreen(rgb), qBlue(rgb)
                                c = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (
                                    (b & 0xF8) >> 3)
                                pixeldata += struct.pack(">H", c)
                        z = zlib.compressobj(level=9, wbits=10)
                        zdata = z.compress(bytes(pixeldata)) + z.flush()
                        zdata = zdata[2:-4]  # strip header and checksum
                        data += struct.pack("<HH", img.width(), img.height())
                        data += struct.pack("<I", len(zdata))
                        data += zdata
                        return bytes(data)

                    return qimg_to_toif(img, handler)

                # /read_and_convert_using_qt
                if hs_mono and not is_model_T:
                    img = read_and_convert_using_qt_to_raw_mono(
                        handler, filename, hs_cols, hs_rows)
                else:
                    img = read_and_convert_using_qt_to_toif(
                        handler, filename, hs_cols, hs_rows)
                if not img:
                    return
            invoke_client('change_homescreen', img)
예제 #58
0
		settings.setValue(key, value)
	elif len(value) == 1:
		settings.setValue(key, value[0])
	else:
		settings.remove(key)

class ReTextSettings(object):
	def __init__(self):
		for option in configOptions:
			value = configOptions[option]
			object.__setattr__(self, option, readFromSettings(
				option, type(value), default=value))

	def __setattr__(self, option, value):
		if not option in configOptions:
			raise AttributeError('Unknown attribute')
		object.__setattr__(self, option, value)
		writeToSettings(option, value, configOptions[option])

globalSettings = ReTextSettings()

markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle

monofont = QFont()
monofont.setFamily(globalSettings.editorFont)
if globalSettings.editorFontSize:
	monofont.setPointSize(globalSettings.editorFontSize)

datadirs = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation)
datadirs = [abspath('.')] + [join(d, 'retext') for d in datadirs]
예제 #59
0
    IS_HAIKU,
    IS_MACOS,
    IS_WIN,
)
from picard.util import icontheme

from picard.ui import PicardDialog
from picard.ui.moveable_list_view import MoveableListView
from picard.ui.options import (
    OptionsPage,
    register_options_page,
)
from picard.ui.ui_options_interface import Ui_InterfaceOptionsPage
from picard.ui.util import enabledSlot

_default_starting_dir = QStandardPaths.writableLocation(
    QStandardPaths.HomeLocation)


class InterfaceOptionsPage(OptionsPage):

    NAME = "interface"
    TITLE = N_("User Interface")
    PARENT = None
    SORT_ORDER = 80
    ACTIVE = True
    HELP_URL = '/config/options_interface.html'
    SEPARATOR = '—' * 5
    TOOLBAR_BUTTONS = {
        'add_directory_action': {
            'label': N_('Add Folder'),
            'icon': 'folder'
 def savesDirectory(self):
     return QDir("{}/Darkest".format(
         QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)))