Exemple #1
0
 def backup(self):
     model = self.state.model
     if not model:
         return
     widget = QApplication.focusWidget()
     filename = Lib.incrementedFilename(model.filename)
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         filename, _ = QFileDialog.getSaveFileName(
             self.window,
             "Backup Index — {}".format(QApplication.applicationName()),
             filename,
             "{} index (*{})".format(QApplication.applicationName(),
                                     EXTENSION))
     if filename:
         with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
             self.state.saving = True
             try:
                 self.state.maybeSave()
                 if not filename.endswith(EXTENSION):
                     filename += EXTENSION
                 say("Backing up to “{}”...".format(
                     QDir.toNativeSeparators(filename)))
                 model.optimize()
                 model.backup(filename, "Backing up",
                              self.window.reportProgress)
                 say("Backed up to “{}”".format(
                     QDir.toNativeSeparators(filename)))
             finally:
                 self.state.saving = False
     Lib.restoreFocus(widget)
Exemple #2
0
 def saveAs(self):  # No need to restore focus widget
     filename = self._getSaveAsFilename()
     if filename:
         # Do a backup to the new filename, then open it
         say("Saving to “{}”...".format(QDir.toNativeSeparators(filename)))
         self.state.model.backup(filename, "Saving",
                                 self.window.reportProgress)
         self.window.openXix(filename)
Exemple #3
0
 def localFromServer(self, serverpath):
     # Removing leading '/' so `os.path.join` doesn't treat
     # `localpath` as an absolute path
     localpath = serverpath[1:] if serverpath.startswith('/') else serverpath
     localpath = QDir.toNativeSeparators(localpath)
     localpath = os.path.join(self.localdir, localpath)
     
     return localpath
Exemple #4
0
    def localFromServer(self, serverpath):
        # Removing leading '/' so `os.path.join` doesn't treat
        # `localpath` as an absolute path
        localpath = serverpath[1:] if serverpath.startswith(
            '/') else serverpath
        localpath = QDir.toNativeSeparators(localpath)
        localpath = os.path.join(self.localdir, localpath)

        return localpath
Exemple #5
0
 def onBrowseClicked(self):
     """Slot. Called when the user clicks on the `browseButton` button"""
     
     # Presents the user with a native directory selector window
     localdir = QFileDialog.getExistingDirectory()
     localdir = QDir.fromNativeSeparators(localdir)
     if len(localdir) > 0:
         # If `localdir`'s value is good, store it using a `QSettings` object
         # and triggers a sync request.
         # Careful with '\' separators on Windows.
         localdir = QDir.toNativeSeparators(localdir)
         get_settings().setValue(SettingsKeys['localdir'], localdir)
         self.localdirEdit.setText(localdir)
Exemple #6
0
    def onBrowseClicked(self):
        """Slot. Called when the user clicks on the `browseButton` button"""

        # Presents the user with a native directory selector window
        localdir = QFileDialog.getExistingDirectory()
        localdir = QDir.fromNativeSeparators(localdir)
        if len(localdir) > 0:
            # If `localdir`'s value is good, store it using a `QSettings` object
            # and triggers a sync request.
            # Careful with '\' separators on Windows.
            localdir = QDir.toNativeSeparators(localdir)
            get_settings().setValue(SettingsKeys['localdir'], localdir)
            self.localdirEdit.setText(localdir)
Exemple #7
0
    def parsePluginSpecs(self, parentItem, plugins):
        ret = 0
        loadCount = 0

        for i in range(len(plugins)):
            spec = plugins[i]
            if spec.hasError():
                ret |= ParsedState.ParsedWithErrors
            pluginItem = QTreeWidgetItem([spec.name(), "",
                                         "{0} ({1})".format(spec.version(), spec.compatVersion()),
                                         spec.vendor()])
            pluginItem.setToolTip(0, QDir.toNativeSeparators(spec.filePath()))
            ok = not spec.hasError()
            icon = self.okIcon if ok else self.errorIcon
            if ok and spec.state() is not PluginState.Running:
                icon = self.notLoadedIcon
            pluginItem.setIcon(0, icon)
            pluginItem.setData(0, Qt.UserRole, spec)

            state = Qt.Unchecked
            if spec.isEnabled():
                state = Qt.Checked
                loadCount += 1

            if spec.name() not in self.whitelist:
                pluginItem.setData(C_LOAD, Qt.CheckStateRole, state)
            else:
                pluginItem.setData(C_LOAD, Qt.CheckStateRole, Qt.Checked)
                pluginItem.setFlags(Qt.ItemIsSelectable)
            pluginItem.setToolTip(C_LOAD, "Load on Startup")

            self.specToItem[spec] = pluginItem

            if parentItem:
                parentItem.addChild(pluginItem)
            else:
                self.items.append(pluginItem)

        if loadCount == len(plugins):
            groupState = Qt.Checked
            ret |= ParsedState.ParsedAll
        elif loadCount == 0:
            groupState = Qt.Unchecked
            ret |= ParsedState.ParsedNone
        else:
            groupState = Qt.PartiallyChecked
            ret |= ParsedState.ParsedPartial

        return ret, groupState
Exemple #8
0
 def loadLibrary(self):
     if self.hasError:
         return False
     if self.state is not PluginState.Resolved:
         if self.state is PluginState.Loaded:
             return True
         self.errorString = QCoreApplication.translate(None, "Loading the library failed because state != Resolved")
         self.hasError = True
         return False
     pluginPath = QDir.toNativeSeparators(self.location)
     pluginClass = pluginloader.loadIPlugin(pluginPath, self.name + "." + self.mainClass)
     if not pluginClass:
         self.hasError = True
         self.errorString = QCoreApplication.translate(None,
                                                       "Plugin is not valid (does not derive from IPlugin")
         return False
     self.state = PluginState.Loaded
     self.plugin = pluginClass(self.manager)
     self.plugin.private.pluginSpec = self.pluginSpec
     return True
Exemple #9
0
 def updateRecentFilesMenu(self):
     recentAction = self.fileActions.openRecentAction
     if self.recent_files:
         self.recent_files = [
             filename for filename in self.recent_files
             if filename and os.path.exists(filename)
         ]
     if not self.recent_files:
         recentAction.setEnabled(False)
     else:
         recentAction.setEnabled(True)
         menu = QMenu(self)
         for i, filename in enumerate(self.recent_files, 1):
             action = QAction(
                 QIcon(":/document-open.svg"),
                 "&{} {}".format(i,
                                 QDir.toNativeSeparators(filename)), menu)
             action.triggered.connect(
                 lambda filename=filename: self.openXix(filename))
             menu.addAction(action)
         recentAction.setMenu(menu)
Exemple #10
0
    def _outputIndex(self, filename, widget):
        monitor = Lib.MonitorFile(filename)
        self.state.outputPath = os.path.dirname(filename)
        nativeFilename = QDir.toNativeSeparators(filename)
        try:
            say("Outputting to “{}”…".format(nativeFilename))
            with Lib.DisableUI(*self.state.window.widgets()):
                config = self.state.model.configs().copy()
                config.Filename = filename
                Output.outputEntries(self.state.model, config, "Outputting",
                                     self.window.reportProgress)

            self._reportOnOutput(
                monitor, "Output to “{}”".format(nativeFilename),
                "Output Failed",
                "Failed to output to “{}”".format(nativeFilename))
        except Output.Error as err:
            self._reportOnOutput(
                monitor, "Output to “{}”".format(nativeFilename),
                "Output Failed",
                "Failed to output to “{}”: {}".format(nativeFilename, err))
        Lib.restoreFocus(widget)
Exemple #11
0
    def initialize(self):
        locale = QLocale()
        model = self.state.model
        if not bool(model):
            self.browser.setHtml("<font color=red>Information can only "
                                 "be shown if an index is open</font>")
            return

        top, total, _ = self.state.indicatorCounts()
        fullname = QDir.toNativeSeparators(os.path.abspath(model.filename))
        creator = model.config(Gconf.Key.Creator)
        created = model.config("Created")
        created = locale.toString(
            QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss"))
        updated = locale.toString(QFileInfo(model.filename).lastModified())
        size = os.path.getsize(model.filename)
        KB = 1024
        MB = KB * KB
        if size < MB:
            size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size)
        else:
            size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size)
        filename = re.sub(r"\.xix$", "", os.path.basename(fullname),
                          re.IGNORECASE)
        version = str(model.version())
        secs = self.state.workTime + int(time.monotonic() -
                                         self.state.startTime)
        hours, secs = divmod(secs, 3600)
        if hours:
            worktime = "{:,}h{}'".format(hours, secs // 60)
        else:
            worktime = "{}'".format(secs // 60)
        uuid = model.config(UUID)
        LEFT_STYLE = """ style="
margin-right: 0;
padding-right: 0;
spacing-right: 0;
border-right: 0;
"
"""
        RIGHT_STYLE = """ style="
margin-left: 0;
padding-left: 0;
spacing-left: 0;
border-left: 0;
"
"""
        color1 = "#DDDDFF"
        color2 = "#EEEEFF"
        STYLE = ' style="background-color: {};"'
        texts = [
            """<html><table border=0 style="
background-color: {};
">""".format(color1)
        ]
        for i, (name, value, right, debug) in enumerate((
            ("Index", filename, False, False),
            ("Creator", creator, False, False),
            ("Filename", fullname, False, False),
            ("Size", size, False, False),
            ("Created", created, False, False),
            ("Updated", updated, False, False),
            ("Total Entries", "{:,}".format(total), True, False),
            ("Main Entries", "{:,}".format(top), True, False),
            ("Subentries", "{:,}".format(total - top), True, False),
            ("Worktime", worktime, True, False),
            (None, None, False, False),
            ("Index Format", version, True, False),
            ("Index UUID", uuid, True, True),
        )):
            if debug and not self.state.window.debug:
                continue
            if name is None:
                color1 = "#EEEEEE"
                color2 = "#DDDDDD"
                continue
            style = STYLE.format(color1 if i % 2 == 0 else color2)
            align = " align=right" if right else ""
            texts.append("""<tr{}><td{}>{}&nbsp;&nbsp;</td>
<td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align,
                               RIGHT_STYLE, html.escape(value)))
        texts.append("</table></html>")
        self.browser.setHtml("".join(texts))