Exemplo n.º 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)
Exemplo n.º 2
0
 def addToLinkedGroup(self):
     self.state.maybeSave()
     eid = self.state.viewAllPanel.view.selectedEid
     groups = set(self.state.model.linkedGroups())
     inGroups = set(self.state.model.groupsForEid(eid))
     groups = sorted(groups - inGroups, key=lambda g: g[1].casefold())
     names = [
         g[1] for g in groups
         if self.state.model.safeToAddToGroup(eid, g[0])
     ]
     if not names:
         if self.state.model.linkedGroup(eid) is not None:
             message = "This entry is already in a linked group."
         else:
             message = ("There are no linked groups for this entry "
                        "to be added to.")
         QMessageBox.information(
             self.window,
             "Can't Link — {}".format(QApplication.applicationName()),
             message)
     else:
         name, ok = QInputDialog.getItem(
             self.window, "Add to Linked Group — {}".format(
                 QApplication.applicationName()), "Linked Group", names, 0,
             False)
         if ok:
             for gid, gname in groups:
                 if gname == name:
                     self.state.model.addToGroup(eid, gid)
                     self.state.viewAllPanel.view.gotoEid(eid)
                     break
Exemplo n.º 3
0
 def importIndex(self):  # No need to restore focus widget
     extensions = []
     for extension, desc in IMPORT_EXTENSIONS.items():
         extensions.append("{} (*{})".format(desc, extension))
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         inFilename, _ = QFileDialog.getOpenFileName(
             self.window,
             "Import Index — {}".format(QApplication.applicationName()),
             self.state.importPath, ";;".join(extensions))
     if inFilename:
         for extension in IMPORT_EXTENSIONS:
             break  # Just want the first (i.e., .ximl)
         if not inFilename.casefold().endswith(
                 tuple(EXPORT_EXTENSIONS.keys())):
             inFilename += extension
         with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
             filename, _ = QFileDialog.getSaveFileName(
                 self.window, "Save Imported Index As — {}".format(
                     QApplication.applicationName()), self.state.indexPath,
                 "{} index (*{})".format(QApplication.applicationName(),
                                         EXTENSION))
         if filename and not filename.casefold().endswith(EXTENSION):
             filename += EXTENSION
         if inFilename and filename:
             self.state.importPath = os.path.dirname(inFilename)
             self.state.indexPath = os.path.dirname(filename)
             self.window.importIndex(filename, inFilename)
Exemplo n.º 4
0
    def about(self):
        widget = QApplication.focusWidget()
        year = datetime.date.today().year
        year = "2015-{}".format(str(year)[-2:]) if year != 2015 else "2015"
        w = self.window.frameGeometry().width()
        h = self.window.frameGeometry().height()
        with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
            app = QApplication.applicationName()
            version = QApplication.applicationVersion()
            bits = 64 if IS64BIT else 32
            QMessageBox.about(
                self.window,
                "About — {}".format(QApplication.applicationName()), f"""
<p><b><font color=navy>{app} {version}</font></b></p>
<p><font color=navy>{app} is an easy to learn and use application
for creating, editing, and outputting indexes (e.g., for
books).</font>
</p>
<p>Copyright © Qtrac Ltd {year}. All Rights Reserved.</p>
<p>License:&nbsp;GPLv3.</p>
<hr>
<p>Window size: {w:,}x{h:,}</p>
<p>
Python
{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}/{
bits}-bit<br>
PySide {PySide.__version__}<br>
Qt {qVersion()}<br>
APSW {apsw.apswversion()}<br>
SQLite {apsw.sqlitelibversion()}<br>
{platform.platform()}</p>""")
        Lib.restoreFocus(widget)
Exemplo n.º 5
0
 def addToNormalGroup(self):
     self.state.maybeSave()
     eid = self.state.viewAllPanel.view.selectedEid
     groups = set(self.state.model.normalGroups())
     inGroups = set(self.state.model.groupsForEid(eid))
     groups = sorted(groups - inGroups, key=lambda g: g[1].casefold())
     names = [g[1] for g in groups]
     if not names:  # Could happen if already in all the groups
         message = ("There are no other groups for this entry "
                    "to be added to.")
         QMessageBox.information(
             self.window,
             "Can't Link — {}".format(QApplication.applicationName()),
             message)
         return
     name, ok = QInputDialog.getItem(
         self.window,
         "Add to Normal Group — {}".format(QApplication.applicationName()),
         "Normal Group", names, 0, False)
     if ok:
         for gid, gname in groups:
             if gname == name:
                 self.state.model.addToGroup(eid, gid)
                 self.state.viewAllPanel.view.gotoEid(eid)
                 break
Exemplo n.º 6
0
 def updateTitle(self):
     if self.filename is None:
         self.setWindowTitle(QApplication.applicationName())
         say("Click File→New or File→Open to create or open an index")
     else:
         filename = os.path.basename(self.filename)
         dirname = os.path.abspath(os.path.dirname(self.filename))
         dirname = (" [{}]".format(os.path.normcase(dirname))
                    if dirname != os.getcwd() else "")
         self.setWindowTitle("{}{} — {}".format(
             filename, dirname, QApplication.applicationName()))
Exemplo n.º 7
0
    def _reportOnOutput(self, monitor, goodMessage, badTitle, badMessage):
        if monitor.changed:
            say(goodMessage)
        else:
            QMessageBox.warning(
                self.window, "{} — {}".format(badTitle,
                                              QApplication.applicationName()),
                """\
<p>{}</p><p>{} cannot write a file if the file is open in another
application or if you don't have access permission to write the file (or
to write in the file's folder).</p>
<p><b>Try using a different filename and/or folder.</b></p>""".format(
                    badMessage, QApplication.applicationName()))
Exemplo n.º 8
0
 def _new_or_open(self, word, getter):  # No need to restore focus widget
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         filename, _ = getter(
             self.window,
             "{} Index — {}".format(word, QApplication.applicationName()),
             self.state.indexPath,
             "{} index (*{})".format(QApplication.applicationName(),
                                     EXTENSION))
     if filename and not filename.casefold().endswith(EXTENSION):
         filename += EXTENSION
     if filename:
         self.state.indexPath = os.path.dirname(filename)
     return filename
Exemplo n.º 9
0
 def setFilename(self):  # No need to restore focus widget
     with Lib.Qt.DisableUI(self, forModalDialog=True):
         filename, _ = QFileDialog.getSaveFileName(
             self,
             "New Empty Index — {}".format(QApplication.applicationName()),
             self.state.indexPath,
             "{} index (*{})".format(QApplication.applicationName(),
                                     EXTENSION))
     if filename and not filename.casefold().endswith(EXTENSION):
         filename += EXTENSION
     if filename:
         self.state.indexPath = os.path.dirname(filename)
         self.filenameLabel.setText(os.path.normpath(filename))
         self.updateUi()
Exemplo n.º 10
0
    def createWidgets(self):
        self.filenameLabelLabel = QLabel("New Filename")
        self.filenameLabel = QLabel()
        self.filenameLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.filenameButton = QPushButton("C&hoose...")
        self.tooltips.append((self.filenameButton, """\
<p><b>Choose</b></p>
<p>Choose the {} <tt>.xix</tt> file to copy the current index's options,
spelling words, etc., to.</p>""".format(QApplication.applicationName())))
        self.copyGroupBox = QGroupBox("Copy")
        self.configCheckBox = QCheckBox("&Options")
        self.tooltips.append((self.configCheckBox, """\
<p><b>Options</b></p>
<p>If checked, copy all the current index's option and output option
settings (language, sort as and page range rules, display preferences,
fonts, output style, etc.) to the new empty copy.</p>"""))
        self.spellWordsCheckBox = QCheckBox("&Spelling Words")
        self.tooltips.append((self.spellWordsCheckBox, """\
<p><b>Spelling Words</b></p>
<p>If checked, copy all the current index's spelling words to the new
empty copy.</p>"""))
        self.ignoredFirstWordsCheckBox = QCheckBox(
            "&Ignored Subentry Function Words")
        self.tooltips.append((self.ignoredFirstWordsCheckBox, """\
<p><b>Ignored Subentry Function Words</b></p>
<p>If checked, copy all the current index's ignored subentry function
words words to the new empty copy.</p>"""))
        self.customMarkupCheckBox = QCheckBox("Custom &Markup")
        self.tooltips.append((self.customMarkupCheckBox, """\
<p><b>Custom Markup</b></p>
<p>If checked, copy all the current index's custom markup to the new
empty copy.</p>"""))
        self.groupsCheckBox = QCheckBox("&Groups")
        self.tooltips.append((self.groupsCheckBox, """\
<p><b>Groups</b></p>
<p>If checked, copy all the current index's groups to the new empty
copy.</p>"""))
        self.autoReplaceCheckBox = QCheckBox("&Auto Replacements")
        self.tooltips.append((self.autoReplaceCheckBox, """\
<p><b>Auto Replacements</b></p>
<p>If checked, copy all the current index's auto replacements to the new
empty copy.</p>"""))
        for checkbox in (self.configCheckBox, self.spellWordsCheckBox,
                         self.ignoredFirstWordsCheckBox,
                         self.customMarkupCheckBox, self.groupsCheckBox,
                         self.autoReplaceCheckBox):
            checkbox.setChecked(True)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the New Empty Copy dialog"))
        self.newCopyButton = QPushButton(QIcon(":/document-new.svg"),
                                         "&New Empty Copy")
        self.tooltips.append((self.newCopyButton, """\
<p><b>New Empty Copy</b></p>
<p>Create a new empty index and copy the options, spelling words,
etc.&mdash;providing they have been checked&mdash;into the new
index.</p>"""))
        self.cancelButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.cancelButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making a new empty copy.</p>"""))
Exemplo n.º 11
0
 def deleteXRef(self):
     widget = QApplication.focusWidget()
     self.state.maybeSave()
     item = self.state.entryPanel.xrefList.currentItem()
     if item is not None:
         xref = Xix.Util.xref_for_data(item.data(Qt.UserRole))
         from_term = self.state.model.term(xref.from_eid)
         kind = "see" if xref.kind is XrefKind.SEE else "see also"
         if xref.kind in {XrefKind.SEE, XrefKind.SEE_ALSO}:
             term = self.state.model.term(xref.to_eid)
         elif xref.kind in {
                 XrefKind.SEE_GENERIC, XrefKind.SEE_ALSO_GENERIC
         }:
             term = xref.term
             kind += " (generic)"
         with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
             reply = QMessageBox.question(
                 self.window, "Delete Cross-reference — {}".format(
                     QApplication.applicationName()),
                 "<p>Delete cross-reference from<br>“{}” to {} “{}”?".
                 format(from_term, kind, term),
                 QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
         if reply == QMessageBox.Yes:
             if xref.kind in {XrefKind.SEE, XrefKind.SEE_ALSO}:
                 self.state.model.deleteXRef(xref.from_eid, xref.to_eid,
                                             xref.kind)
             elif xref.kind in {
                     XrefKind.SEE_GENERIC, XrefKind.SEE_ALSO_GENERIC
             }:
                 self.state.model.deleteGenericXRef(xref.from_eid,
                                                    xref.term, xref.kind)
     Lib.restoreFocus(widget)
Exemplo n.º 12
0
 def outputIndexAs(self):
     widget = QApplication.focusWidget()
     extensions = []
     for extension, desc in EXPORT_EXTENSIONS.items():
         extensions.append("{} (*{})".format(desc, extension))
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         form = QFileDialog(
             self.window,
             "Output As — {}".format(QApplication.applicationName()))
         form.setNameFilters(extensions)
         form.setAcceptMode(QFileDialog.AcceptSave)
         form.setDirectory(self.state.outputPath)
         form.selectFile(str(pathlib.Path(self.state.model.filename).stem))
         if form.exec_():
             filename = form.selectedFiles()[0]
             extension = form.selectedNameFilter()
             if filename:  # Must have some extension
                 if not re.match(r"^.*[.].+$", filename):
                     if extension:
                         filename += EXTENSION_EXTRACT_RX.sub(
                             r"\1", extension)
                     else:
                         filename += ".rtf"
                 self._outputIndex(filename, widget)
     Lib.restoreFocus(widget)
Exemplo n.º 13
0
 def __init__(self, home, parent=None, *, stayOnTop=False, debug=False):
     super().__init__(parent)
     if stayOnTop:
         flags = self.windowFlags()
         flags |= Qt.WindowStaysOnTopHint
         self.setWindowFlags(flags)
     self.home = home
     self.debug = debug
     self.filenamesForWord = {}
     self.titleForFilename = {}
     self.createWidgets()
     self.createLayout()
     self.createConnections()
     self.createShortcuts()
     self.changePage(self.home)
     self.updateUi()
     if self.debug:
         self.mtime = 0
         self.timer = QTimer(self)
         self.timer.start(250)
         self.timer.timeout.connect(self.timeout)
     self.loadSettings()
     with open(Lib.get_path("doc/xix_style.css"), "r",
               encoding=UTF8) as file:
         self.css = file.read()
     self.browser.setFocus()
     self.setWindowTitle("Help — {}".format(
         QApplication.applicationName()))
Exemplo n.º 14
0
 def delete(self):  # No need to restore focus widget
     row = self.listWidget.currentRow()
     item = self.listWidget.item(row)
     if item is None:
         return
     gid = item.data(Qt.UserRole)
     for button in self.buttons:
         button.setEnabled(False)
     deleteItem = False
     if (not self.state.model.isLinkedGroup(gid)
             or not self.state.model.groupMemberCount(gid)):
         with Lib.Qt.DisableUI(self, forModalDialog=True):
             reply = QMessageBox.question(
                 self,
                 "Delete Group — {}".format(QApplication.applicationName()),
                 "<p>Delete Group “{}”?</p>".format(item.text()),
                 QMessageBox.Yes | QMessageBox.No)
         if reply == QMessageBox.Yes:
             self.state.model.deleteGroup(gid)
             deleteItem = True
     else:
         with Lib.Qt.DisableUI(self, forModalDialog=True):
             form = Forms.DeleteOrUnlink.Form("Delete", gid, self.state,
                                              self)
             deleteItem = form.exec_()
     if deleteItem:
         item = self.listWidget.takeItem(row)
         del item
     self.updateUi()
Exemplo n.º 15
0
 def initialize(self):
     self.setWindowTitle("{}".format(QApplication.applicationName()))
     self.state.updateDisplayFonts()
     self.filename = None
     if len(sys.argv) > 1:
         filename = sys.argv[1]
         if (filename.lower().endswith(EXTENSION)
                 and os.path.exists(filename)):
             self.filename = filename
     if self.filename is None:
         settings = QSettings()
         filename = settings.value(Gopt.Key.MainForm_Filename,
                                   Gopt.Default.MainForm_Filename)
         if (filename and filename.lower().endswith(EXTENSION)
                 and os.path.exists(filename)):
             self.filename = filename
     if self.filename is None:
         say("Click File→New or File→Open to create or open an index")
         self.updateWorkTime()
         self.state.updateUi()
     else:
         say("Opening {}".format(os.path.normpath(self.filename)))
         QTimer.singleShot(5, self.openXix)
     self.updateRecentFilesMenu()
     self.updateToolTips()
     Lib.maybe_register_filetype(self.debug)
Exemplo n.º 16
0
 def _getSaveAsFilename(self, title="Save As"):
     model = self.state.model
     if not model:
         return
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         filename, _ = QFileDialog.getSaveFileName(
             self.window, "{} — {}".format(title,
                                           QApplication.applicationName()),
             self.state.indexPath,
             "{} index (*{})".format(QApplication.applicationName(),
                                     EXTENSION))
     if filename:
         self.state.maybeSave()
         if not filename.endswith(EXTENSION):
             filename += EXTENSION
         if filename != model.filename:
             self.state.indexPath = os.path.dirname(filename)
         return filename
Exemplo n.º 17
0
    def isReadOnly(self, filename):
        if (os.access(filename, os.R_OK) and not os.access(filename, os.W_OK)):
            QMessageBox.information(
                self, "Can't Open Read-Only Index — {}".format(
                    QApplication.applicationName()),
                """<p>Cannot open index<br>“{}”<br>
since the file and/or its folder is read-only.</p>""".format(
                    os.path.normpath(filename)))
            return True
        return False
Exemplo n.º 18
0
    def __init__(self, window):
        self.window = window
        self.state = self.window.state

        self.insertQuoteAction = Lib.createAction(window,
                                                  ":/quote.svg",
                                                  "&Single Quote",
                                                  lambda: self.insertChar("'"),
                                                  tooltip="""
<p><b>Insert→Single Quote</b></p>
<p>Insert a single quote ‘'’.</p>""")
        self.insertDoubleQuoteAction = Lib.createAction(
            window,
            ":/doublequote.svg",
            "&Double Quote",
            lambda: self.insertChar('"'),
            tooltip="""
<p><b>Insert→Double Quote</b></p>
<p>Insert a double quote ‘"’.</p>""")
        self.insertEllipsisAction = Lib.createAction(
            window,
            ":/ellipsis.svg",
            "&Ellipsis",
            lambda: self.insertChar("…"),
            tooltip="""
<p><b>Insert→Ellipsis</b></p>
<p>Insert an ellipsis ‘…’.</p>""")
        self.insertEndashAction = Lib.createAction(
            window,
            ":/endash.svg",
            "E&n-dash",
            lambda: self.insertChar("–"),
            tooltip="""
<p><b>Insert→En-dash</b></p>
<p>Insert an en-dash ‘–’.</p>
<p>Using a plain hyphen ‘-’ is fine for page ranges since {}
automatically converts hyphens to en-dashes.""".format(
                QApplication.applicationName()))
        self.insertEmdashAction = Lib.createAction(
            window,
            ":/emdash.svg",
            "E&m-dash",
            lambda: self.insertChar("—"),
            tooltip="""
<p><b>Insert→Em-dash</b></p>
<p>Insert an em-dash ‘—’.</p>""")
        self.insertCharAction = Lib.createAction(
            window,
            ":/accessories-character-map.svg",
            "&Copy Character...",
            self.insertCharacter,
            tooltip="""
<p><b>Insert→Copy Character</b></p>
<p>Pop up the Copy Character dialog from which any available characters
can be chosen and copied to the clipboard.</p>""")
Exemplo n.º 19
0
 def __init__(self, state, eids, uuid, name, parent=None):
     super().__init__(parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
     self.setWindowTitle("Check “{}” — {}".format(
         name, QApplication.applicationName()))
     self.state = state
     self.uuid = uuid
     self.loadSaveSize = False
     self.createWidgets(eids, name)
     self.layoutWidgets()
     self.createConnections()
     self.browser.setFocus()
Exemplo n.º 20
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.groups = set()
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     self.setWindowTitle("Choose Normal Group(s) — {}".format(
                         QApplication.applicationName()))
     settings = QSettings()
     self.updateToolTips(bool(int(settings.value(
         Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 21
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.setWindowTitle("Forget Spelling Words — {}".format(
                         QApplication.applicationName()))
     words = sorted(
         self.state.entryPanel.spellHighlighter.wordsToIgnore |
         set(self.state.model.spellWords()), key=str.casefold)
     if words:
         self.initialize(words)
     else:
         self.nowords()
     settings = QSettings()
     self.updateToolTips(bool(int(settings.value(
         Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 22
0
 def remove(self):  # No need to restore focus widget
     row = self.listWidget.currentRow()
     item = self.listWidget.item(row)
     if item is None:
         return
     with Lib.Qt.DisableUI(self, forModalDialog=True):
         reply = QMessageBox.question(
             self, "Remove {} — {}".format(self.info.name,
                                           QApplication.applicationName()),
             "Remove {} “{}”?".format(self.info.name, item.text()),
             QMessageBox.Yes | QMessageBox.No)
     if reply == QMessageBox.Yes:
         cursor = self.info.db.cursor()
         cursor.execute(self.info.DELETE, (item.text(), ))
         item = self.listWidget.takeItem(row)
         del item
Exemplo n.º 23
0
    def __init__(self, window):
        self.window = window
        self.state = self.window.state
        # self.viewWindow = None
        self.helpAction = Lib.createAction(
            window, ":/help.svg", "&Help", self.state.help,
            QKeySequence.HelpContents, """\
<p><b>Help→Help</b> ({})</p>
<p>Show the online help.</p>""".format(
                QKeySequence(QKeySequence.HelpContents).toString()))
        self.aboutAction = Lib.createAction(window,
                                            ":/xindex.svg",
                                            "&About",
                                            self.about,
                                            tooltip="""\
<p><b>Help→About</b></p>
<p>Show {}'s About box.</p>""".format(QApplication.applicationName()))
Exemplo n.º 24
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.setWindowTitle("Renumber Pages — {}".format(
         QApplication.applicationName()))
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     self.romanStartSpinBox.setFocus()
     self.updateUi()
     settings = QSettings()
     self.updateToolTips(
         bool(
             int(
                 settings.value(Gopt.Key.ShowDialogToolTips,
                                Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 25
0
    def delete(self):  # No need to restore focus widget
        index = self.extensionComboBox.currentIndex()
        if index == -1:
            return
        with Lib.Qt.DisableUI(self, forModalDialog=True):
            extension = self.extensionComboBox.currentText()
            reply = QMessageBox.question(
                self, "Delete Custom Markup — {}".format(
                    QApplication.applicationName()), """<p>Delete “{}”?<p>
<font color=red>Warning: deleting custom markup cannot be undone.</font>""".
                format(extension), QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.extensionComboBox.removeItem(index)
            if index < self.extensionComboBox.count():
                self.extensionComboBox.setCurrentIndex(index)
            else:
                self.extensionComboBox.setCurrentIndex(max(0, index - 1))
            self.state.model.deleteMarkup(extension)
Exemplo n.º 26
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.config = Config()
     if bool(self.state.model):
         self.config = self.state.model.configs()
     self.setWindowTitle("Output Options — {}".format(
         QApplication.applicationName()))
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     settings = QSettings()
     self.updateToolTips(
         bool(
             int(
                 settings.value(Gopt.Key.ShowDialogToolTips,
                                Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 27
0
 def delete(self):
     widget = QApplication.focusWidget()
     item = self.listWidget.currentItem()
     if item:
         eid = item.data(Qt.UserRole)
         if self.state.model.hasDeletedEntry(eid):
             with Lib.Qt.DisableUI(self, forModalDialog=True):
                 reply = QMessageBox.question(
                     self, "Delete Revivable Entry — {}".format(
                         QApplication.applicationName()),
                     "<p>Permanently delete revivable entry<br>“{}”?".
                     format(item.text()), QMessageBox.Yes | QMessageBox.No,
                     QMessageBox.Yes)
             if reply == QMessageBox.Yes:
                 with Lib.DisableUI(self):
                     self.state.model.deleteDeletedEntry(eid)
                     self.populate()
                 self.updateUi()
     Lib.restoreFocus(widget)
Exemplo n.º 28
0
 def delete(self):
     widget = QApplication.focusWidget()
     if self.state.mode in {ModeKind.NO_INDEX, ModeKind.CHANGE}:
         return  # Can't delete if there's no index or big changes
     if self.state.mode in {ModeKind.ADD, ModeKind.EDIT}:
         self.save()  # Save outstanding changes & set to view mode first
     if self.state.entryPanel.entry is None:
         return  # Should never happen
     eid = self.state.entryPanel.entry.eid
     if eid is None:
         return  # Should never happen
     eids = list(self.state.model.deletableEntries(eid))
     if not eids:
         return  # Should never happen
     message = "Delete entry “{}”".format(self.state.model.term(eid))
     if len(eids) == 2:
         message += ", and its subentry"
     elif len(eids) > 2:
         count = Lib.spellNumber(len(eids) - 1, limit=20)
         message += ", and its {} subentries".format(count)
     message += (", and any related cross-references, and also "
                 "remove from any groups")
     with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
         reply = QMessageBox.question(
             self.window,
             "Delete Entry — {}".format(QApplication.applicationName()),
             "<p>{}?".format(message), QMessageBox.Yes | QMessageBox.No,
             QMessageBox.Yes)
     if reply == QMessageBox.Yes:
         self.state.model.deleteEntry(eid, message[0].lower() + message[1:])
         with Lib.BlockSignals(self.state.entryPanel):
             self.state.entryPanel.clearForm()
         self.state.window.refreshBookmarks()
         self.state.viewFilteredPanel.setMatch()
         selectedEid = self.state.viewAllPanel.view.selectedEid
         if len(self.state.model):
             if selectedEid == eid:
                 self.state.viewAllPanel.view.goUp()
             elif selectedEid is None:
                 self.state.viewAllPanel.view.goEnd()
             else:
                 self.state.viewEntry(selectedEid)
     Lib.restoreFocus(widget)
Exemplo n.º 29
0
 def __init__(self, state, info, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     ListWidgetItem.info = info
     ListWidgetItem.refresh = self.refresh
     self.info = info
     self.helpPage = info.help
     self.createWidgets()
     self.layoutWidgets()
     self.setWindowTitle("{} — {}".format(self.info.name,
                                          QApplication.applicationName()))
     self.refresh()
     settings = QSettings()
     self.updateToolTips(
         bool(
             int(
                 settings.value(Gopt.Key.ShowDialogToolTips,
                                Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 30
0
 def __init__(self, state, term, candidates, result, parent=None):
     super().__init__(parent)
     Lib.prepareModalDialog(self)
     self.state = state
     self.term = term
     self.candidates = []
     for candidate in candidates:
         self.candidates.append(humanizedCandidate(
             term, candidate.candidate, candidate.saf))
     self.result = result
     self.setWindowTitle("Sort As — {}".format(
                         QApplication.applicationName()))
     self.createWidgets()
     self.layoutWidgets()
     self.createConnections()
     self.updateUi()
     settings = QSettings()
     self.updateToolTips(bool(int(settings.value(
         Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))
Exemplo n.º 31
0
def createAllActions(self):
    """
    TOWRITE

    .. TODO:: The c++ code is ugly. If you are going to line things up, line everything up the same so everything looks and reads nicely.

    """
    self.actionHash = actionHash = {}
    createAction = self.createAction
    tr = self.tr

    qDebug("Creating All Actions...")
    appName = QApplication.applicationName()  # QString

    actionHash["ACTION_donothing"] = createAction("donothing", tr("&Do Nothing"), tr("Does Nothing"))

    actionHash["ACTION_windowcascade"] = createAction("windowcascade", tr("&Cascade"), tr("Cascade the windows."))
    actionHash["ACTION_windowtile"] = createAction("windowtile", tr("&Tile"), tr("Tile the windows."))
    actionHash["ACTION_windowclose"] = createAction("windowclose", tr("Cl&ose"), tr("Close the active window."))
    actionHash["ACTION_windowcloseall"] = createAction("windowcloseall", tr("Close &All"), tr("Close all the windows."))
    actionHash["ACTION_windownext"] = createAction("windownext", tr("Ne&xt"), tr("Move the focus to the next window."))
    actionHash["ACTION_windowprevious"] = createAction(
        "windowprevious", tr("Pre&vious"), tr("Move the focus to the previous window.")
    )

    actionHash["ACTION_new"] = createAction("new", tr("&New"), tr("Create a new file."))
    actionHash["ACTION_open"] = createAction("open", tr("&Open"), tr("Open an existing file."))
    actionHash["ACTION_save"] = createAction("save", tr("&Save"), tr("Save the design to disk."))
    actionHash["ACTION_saveas"] = createAction("saveas", tr("Save &As"), tr("Save the design under a new name."))
    actionHash["ACTION_print"] = createAction("print", tr("&Print"), tr("Print the design."))
    actionHash["ACTION_designdetails"] = createAction(
        "designdetails", tr("&Details"), tr("Details of the current design.")
    )
    actionHash["ACTION_exit"] = createAction("exit", tr("E&xit"), tr("Exit the application."))

    actionHash["ACTION_cut"] = createAction(
        "cut", tr("Cu&t"), tr("Cut the current selection's contents to the clipboard.")
    )
    actionHash["ACTION_copy"] = createAction(
        "copy", tr("&Copy"), tr("Copy the current selection's contents to the clipboard.")
    )
    actionHash["ACTION_paste"] = createAction(
        "paste", tr("&Paste"), tr("Paste the clipboard's contents into the current selection.")
    )

    actionHash["ACTION_help"] = createAction("help", tr("&Help"), tr("Displays help."))
    actionHash["ACTION_changelog"] = createAction(
        "changelog", tr("&Changelog"), tr("Describes new features in this product.")
    )
    actionHash["ACTION_tipoftheday"] = createAction(
        "tipoftheday", tr("&Tip Of The Day"), tr("Displays a dialog with useful tips")
    )
    actionHash["ACTION_about"] = createAction(
        "about", tr("&About ") + appName, tr("Displays information about this product.")
    )
    actionHash["ACTION_whatsthis"] = createAction("whatsthis", tr("&What's This?"), tr("What's This? Context Help!"))

    actionHash["ACTION_undo"] = createAction("undo", tr("&Undo"), tr("Reverses the most recent action."))
    actionHash["ACTION_redo"] = createAction(
        "redo", tr("&Redo"), tr("Reverses the effects of the previous undo action.")
    )

    actionHash["ACTION_icon16"] = createAction("icon16", tr("Icon&16"), tr("Sets the toolbar icon size to 16x16."))
    actionHash["ACTION_icon24"] = createAction("icon24", tr("Icon&24"), tr("Sets the toolbar icon size to 24x24."))
    actionHash["ACTION_icon32"] = createAction("icon32", tr("Icon&32"), tr("Sets the toolbar icon size to 32x32."))
    actionHash["ACTION_icon48"] = createAction("icon48", tr("Icon&48"), tr("Sets the toolbar icon size to 48x48."))
    actionHash["ACTION_icon64"] = createAction("icon64", tr("Icon&64"), tr("Sets the toolbar icon size to 64x64."))
    actionHash["ACTION_icon128"] = createAction("icon128", tr("Icon12&8"), tr("Sets the toolbar icon size to 128x128."))

    actionHash["ACTION_settingsdialog"] = createAction(
        "settingsdialog", tr("&Settings"), tr("Configure settings specific to this product.")
    )

    actionHash["ACTION_makelayercurrent"] = createAction(
        "makelayercurrent", tr("&Make Layer Active"), tr("Makes the layer of a selected object the active layer")
    )
    actionHash["ACTION_layers"] = createAction(
        "layers", tr("&Layers"), tr("Manages layers and layer properties:  LAYER")
    )
    actionHash["ACTION_layerselector"] = createAction(
        "layerselector", tr("&Layer Selector"), tr("Dropdown selector for changing the current layer")
    )
    actionHash["ACTION_layerprevious"] = createAction(
        "layerprevious", tr("&Layer Previous"), tr("Restores the previous layer settings:  LAYERP")
    )
    actionHash["ACTION_colorselector"] = createAction(
        "colorselector", tr("&Color Selector"), tr("Dropdown selector for changing the current thread color")
    )
    actionHash["ACTION_linetypeselector"] = createAction(
        "linetypeselector", tr("&Stitchtype Selector"), tr("Dropdown selector for changing the current stitch type")
    )
    actionHash["ACTION_lineweightselector"] = createAction(
        "lineweightselector",
        tr("&Threadweight Selector"),
        tr("Dropdown selector for changing the current thread weight"),
    )
    actionHash["ACTION_hidealllayers"] = createAction(
        "hidealllayers",
        tr("&Hide All Layers"),
        tr("Turns the visibility off for all layers in the current drawing:  HIDEALL"),
    )
    actionHash["ACTION_showalllayers"] = createAction(
        "showalllayers",
        tr("&Show All Layers"),
        tr("Turns the visibility on for all layers in the current drawing:  SHOWALL"),
    )
    actionHash["ACTION_freezealllayers"] = createAction(
        "freezealllayers", tr("&Freeze All Layers"), tr("Freezes all layers in the current drawing:  FREEZEALL")
    )
    actionHash["ACTION_thawalllayers"] = createAction(
        "thawalllayers", tr("&Thaw All Layers"), tr("Thaws all layers in the current drawing:  THAWALL")
    )
    actionHash["ACTION_lockalllayers"] = createAction(
        "lockalllayers", tr("&Lock All Layers"), tr("Locks all layers in the current drawing:  LOCKALL")
    )
    actionHash["ACTION_unlockalllayers"] = createAction(
        "unlockalllayers", tr("&Unlock All Layers"), tr("Unlocks all layers in the current drawing:  UNLOCKALL")
    )

    actionHash["ACTION_textbold"] = createAction("textbold", tr("&Bold Text"), tr("Sets text to be bold."))
    actionHash["ACTION_textitalic"] = createAction("textitalic", tr("&Italic Text"), tr("Sets text to be italic."))
    actionHash["ACTION_textunderline"] = createAction(
        "textunderline", tr("&Underline Text"), tr("Sets text to be underlined.")
    )
    actionHash["ACTION_textstrikeout"] = createAction(
        "textstrikeout", tr("&StrikeOut Text"), tr("Sets text to be striked out.")
    )
    actionHash["ACTION_textoverline"] = createAction(
        "textoverline", tr("&Overline Text"), tr("Sets text to be overlined.")
    )

    actionHash["ACTION_zoomrealtime"] = createAction(
        "zoomrealtime",
        tr("Zoom &Realtime"),
        tr("Zooms to increase or decrease the apparent size of objects in the current viewport."),
    )
    actionHash["ACTION_zoomprevious"] = createAction(
        "zoomprevious", tr("Zoom &Previous"), tr("Zooms to display the previous view.")
    )
    actionHash["ACTION_zoomwindow"] = createAction(
        "zoomwindow", tr("Zoom &Window"), tr("Zooms to display an area specified by a rectangular window.")
    )
    actionHash["ACTION_zoomdynamic"] = createAction(
        "zoomdynamic", tr("Zoom &Dynamic"), tr("Zooms to display the generated portion of the drawing.")
    )
    actionHash["ACTION_zoomscale"] = createAction(
        "zoomscale", tr("Zoom &Scale"), tr("Zooms the display using a specified scale factor.")
    )
    actionHash["ACTION_zoomcenter"] = createAction(
        "zoomcenter",
        tr("Zoom &Center"),
        tr("Zooms to display a view specified by a center point and magnification or height."),
    )
    actionHash["ACTION_zoomin"] = createAction(
        "zoomin", tr("Zoom &In"), tr("Zooms to increase the apparent size of objects.")
    )
    actionHash["ACTION_zoomout"] = createAction(
        "zoomout", tr("Zoom &Out"), tr("Zooms to decrease the apparent size of objects.")
    )
    actionHash["ACTION_zoomselected"] = createAction(
        "zoomselected", tr("Zoom Selec&ted"), tr("Zooms to display the selected objects.")
    )
    actionHash["ACTION_zoomall"] = createAction(
        "zoomall", tr("Zoom &All"), tr("Zooms to display the drawing extents or the grid limits.")
    )
    actionHash["ACTION_zoomextents"] = createAction(
        "zoomextents", tr("Zoom &Extents"), tr("Zooms to display the drawing extents.")
    )

    actionHash["ACTION_panrealtime"] = createAction(
        "panrealtime", tr("&Pan Realtime"), tr("Moves the view in the current viewport.")
    )
    actionHash["ACTION_panpoint"] = createAction(
        "panpoint", tr("&Pan Point"), tr("Moves the view by the specified distance.")
    )
    actionHash["ACTION_panleft"] = createAction("panleft", tr("&Pan Left"), tr("Moves the view to the left."))
    actionHash["ACTION_panright"] = createAction("panright", tr("&Pan Right"), tr("Moves the view to the right."))
    actionHash["ACTION_panup"] = createAction("panup", tr("&Pan Up"), tr("Moves the view up."))
    actionHash["ACTION_pandown"] = createAction("pandown", tr("&Pan Down"), tr("Moves the view down."))

    actionHash["ACTION_day"] = createAction(
        "day", tr("&Day"), tr("Updates the current view using day vision settings.")
    )
    actionHash["ACTION_night"] = createAction(
        "night", tr("&Night"), tr("Updates the current view using night vision settings.")
    )

    actionHash["ACTION_windowclose"].setEnabled(self.numOfDocs > 0)
    actionHash["ACTION_designdetails"].setEnabled(self.numOfDocs > 0)
Exemplo n.º 32
0
    def __init__(self):
        super(ConsoleWidget, self).__init__()
        self.setWindowTitle('1c query')

        self._connection = None

        self._home = os.path.expanduser('~/%s' % QApplication.applicationName())
        if not os.path.isdir(self._home):
            os.mkdir(self._home)

        self.queryToolBar = self.addToolBar('Query')
        self.queryAction = self.queryToolBar.addAction('Run', self.executeQuery)
        self.queryAction.setDisabled(True)

        uri_history = list()
        path = os.path.join(self._home, 'uri_history.txt')
        if os.path.isfile(path):
            uri_history = open(path, 'r').read().split('\n')

        self.connectionToolBar = self.addToolBar('Connection')
        self.connectionUriCombo = QComboBox(self)
        self.connectionUriCombo.setEditable(True)
        if not uri_history:
            self.connectionUriCombo.addItem('File="";usr="";pwd="";')
            self.connectionUriCombo.addItem('Srvr="{host}";Ref="{ref}";Usr="******";Pwd="{password}";')
        else:
            self.connectionUriCombo.addItems(uri_history)
            self.connectionUriCombo.setCurrentIndex(len(uri_history) - 1)
        self.connectionUriCombo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
        self.connectionToolBar.addWidget(self.connectionUriCombo)

        self.onesVersionCombo = QComboBox(self)
        self.onesVersionCombo.addItems(['8.3', '8.2', '8.1', '8.0'])
        self.onesVersionCombo.setCurrentIndex(0)
        self.connectionToolBar.addWidget(self.onesVersionCombo)
        self.connectAction = self.connectionToolBar.addAction('Connect', self.connectOneS)
        self.disconnectAction = self.connectionToolBar.addAction('Disconnect', self.disconnectOneS)
        self.disconnectAction.setDisabled(True)

        self.logEdit = QPlainTextEdit(self)
        self.logDock = QDockWidget('Log', self)
        self.logDock.setWidget(self.logEdit)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.logDock, Qt.Horizontal)

        self.splitter = QSplitter(Qt.Vertical, self)
        self.setCentralWidget(self.splitter)

        self.sqlEdit = QTextEdit(self)
        self.sqlEdit.setLineWrapMode(QTextEdit.NoWrap)

        path = os.path.join(self._home, 'last-sql.txt')
        if os.path.isfile(path):
            sql = open(path, 'r').read()
            self.sqlEdit.setText(sql)

        self.model = QStandardItemModel(self)
        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)

        self.splitter.addWidget(self.sqlEdit)
        self.splitter.addWidget(self.tableView)
        self.splitter.setStretchFactor(0, 3)
        self.splitter.setStretchFactor(1, 2)
Exemplo n.º 33
0
def main(argv):
    """
    TOWRITE

    :param `argc`: TOWRITE
    :type `argc`: int
    :param `argv`: TOWRITE
    :type `argv`: char
    :rtype: int
    """

    filesToOpen = []  # QStringList filesToOpen;
    filesToCheck = []

    bindings = defaultBindings
    bindings_flag = False
    for arg in argv[1:]:
        if bindings_flag:
            bindings_flag = False
            if not arg in ("pyside", "pyqt4"):
                usage()
            else:
                bindings = arg
        elif arg == "-d" or arg == "--debug":
            pass
        elif arg == "-h" or arg == "--help":
            usage()
        elif arg == "-v" or arg == "--version":
            version()
        elif arg == "-b" or arg == "--bindings":
            bindings_flag = True
        else:
            filesToCheck.append(arg)

    if exitApp:
        return 1

    # make global to all modules
    if bindings == "pyside":
        builtins.PYSIDE = True
        builtins.PYQT4 = False
    elif bindings == "pyqt4":
        builtins.PYSIDE = False
        builtins.PYQT4 = True

    if PYSIDE:
        from PySide.QtScript import QScriptEngine

        if not hasattr(QScriptEngine, "newFunction"):
            raise ImportError("You need a patched version of PySide.\n" "see: https://codereview.qt-project.org/112333")

    # --PySide Imports.
    if PYSIDE:
        from PySide.QtCore import QObject, SIGNAL, SLOT, QFile
        from PySide.QtGui import QApplication
    elif PYQT4:
        import sip

        sip.setapi("QString", 2)
        sip.setapi("QVariant", 2)
        from PyQt4.QtCore import QObject, SIGNAL, SLOT, QFile
        from PyQt4.QtGui import QApplication

    from mainwindow import MainWindow

    for file_ in filesToCheck:
        if QFile.exists(file_) and MainWindow.validFileFormat(file_):
            filesToOpen.append(file_)
        else:
            usage()
            break

    if exitApp:
        return 1

    app = QApplication(argv)
    app.setApplicationName(_appName_)
    app.setApplicationVersion(_appVer_)

    mainWin = MainWindow()  # MainWindow*

    QObject.connect(app, SIGNAL("lastWindowClosed()"), mainWin, SLOT("quit()"))

    mainWin.setWindowTitle(app.applicationName() + " " + app.applicationVersion())
    mainWin.show()

    # NOTE: If openFilesSelected() is called from within the mainWin constructor, slot commands wont work and the window menu will be screwed
    if filesToOpen:  # if(!filesToOpen.isEmpty())
        mainWin.openFilesSelected(filesToOpen)

    # return app.exec_()
    return app.exec_()