Example #1
0
 def __init__(self, mw, note, ord=0, parent=None, addMode=False):
     QDialog.__init__(self, parent or mw, Qt.Window)
     self.mw = aqt.mw
     self.parent = parent or mw
     self.note = note
     self.ord = ord
     self.col = self.mw.col
     self.mm = self.mw.col.models
     self.model = note.model()
     self.mw.checkpoint(_("Card Types"))
     self.addMode = addMode
     if addMode:
         # save it to DB temporarily
         self.emptyFields = []
         for name, val in note.items():
             if val.strip():
                 continue
             self.emptyFields.append(name)
             note[name] = "(%s)" % name
         note.flush()
     self.setupTabs()
     self.setupButtons()
     self.setWindowTitle(_("Card Types for %s") % self.model["name"])
     v1 = QVBoxLayout()
     v1.addWidget(self.tabs)
     v1.addLayout(self.buttons)
     self.setLayout(v1)
     self.redraw()
     restoreGeom(self, "CardLayout")
     self.exec_()
Example #2
0
 def __init__(self, mw):
     QDialog.__init__(self, mw, Qt.Window)
     self.mw = mw
     self.name = "deckStats"
     self.period = 0
     self.form = aqt.forms.stats.Ui_Dialog()
     self.oldPos = None
     self.wholeCollection = False
     self.setMinimumWidth(700)
     f = self.form
     f.setupUi(self)
     restoreGeom(self, self.name)
     b = f.buttonBox.addButton(_("Save Image"),
                                       QDialogButtonBox.ActionRole)
     b.connect(b, SIGNAL("clicked()"), self.browser)
     b.setAutoDefault(False)
     c = self.connect
     s = SIGNAL("clicked()")
     c(f.groups, s, lambda: self.changeScope("deck"))
     f.groups.setShortcut("g")
     c(f.all, s, lambda: self.changeScope("collection"))
     c(f.month, s, lambda: self.changePeriod(0))
     c(f.year, s, lambda: self.changePeriod(1))
     c(f.life, s, lambda: self.changePeriod(2))
     c(f.web, SIGNAL("loadFinished(bool)"), self.loadFin)
     maybeHideClose(self.form.buttonBox)
     addCloseShortcut(self)
     self.refresh()
     self.exec_()
Example #3
0
def getAudio(parent, encode=True):
    "Record and return filename"
    # record first
    r = Recorder()
    mb = QMessageBox(parent)
    restoreGeom(mb, "audioRecorder")
    mb.setWindowTitle("Anki")
    mb.setIconPixmap(QPixmap(":/icons/media-record.png"))
    but = QPushButton(_("Save"))
    mb.addButton(but, QMessageBox.AcceptRole)
    but = QPushButton(_("Cancel"))
    mb.addButton(but, QMessageBox.RejectRole)
    mb.setEscapeButton(but)
    t = time.time()
    r.start()
    time.sleep(r.startupDelay)
    QApplication.instance().processEvents()
    while not mb.clickedButton():
        txt =_("Recording...<br>Time: %0.1f")
        mb.setText(txt % (time.time() - t))
        mb.show()
        QApplication.instance().processEvents()
    if mb.clickedButton() == mb.escapeButton():
        r.stop()
        return
    saveGeom(mb, "audioRecorder")
    # ensure at least a second captured
    while time.time() - t < 1:
        time.sleep(0.1)
    r.stop()
    # process
    r.postprocess(encode)
    return r.file()
Example #4
0
 def __init__(self, mw):
     QMainWindow.__init__(self, mw)
     applyStyles(self)
     self.mw = mw
     self.col = self.mw.col
     self.currentRow = None
     self.lastFilter = ""
     self.form = aqt.forms.browser.Ui_Dialog()
     self.form.setupUi(self)
     restoreGeom(self, "editor", 0)
     restoreState(self, "editor")
     restoreSplitter(self.form.splitter_2, "editor2")
     restoreSplitter(self.form.splitter, "editor3")
     self.form.splitter_2.setChildrenCollapsible(False)
     self.form.splitter.setChildrenCollapsible(False)
     self.card = None
     self.setupToolbar()
     self.setupColumns()
     self.setupTable()
     self.setupMenus()
     self.setupSearch()
     self.setupTree()
     self.setupHeaders()
     self.setupHooks()
     self.setupEditor()
     self.updateFont()
     self.onUndoState(self.mw.form.actionUndo.isEnabled())
     self.form.searchEdit.setFocus()
     self.show()
     self.form.searchEdit.setText("deck:current is:recent")
     self.form.searchEdit.selectAll()
     self.onSearch()
Example #5
0
File: main.py Project: mstange/anki
    def loadProfile(self):
        # show main window
        if self.pm.profile['mainWindowState']:
            restoreGeom(self, "mainWindow")
            restoreState(self, "mainWindow")
        else:
            self.resize(500, 400)
        # toolbar needs to be retranslated
        self.toolbar.draw()
        # show and raise window for osx
        self.show()
        self.activateWindow()
        self.raise_()
        # maybe sync (will load DB)
        self.onSync(auto=True)
        # import pending?
        if self.pendingImport:
            if self.pm.profile['key']:
                showInfo(_("""\
To import into a password protected profile, please open the profile before attempting to import."""))
            else:
                import aqt.importing
                aqt.importing.importFile(self, self.pendingImport)
            self.pendingImport = None
        runHook("profileLoaded")
Example #6
0
 def __init__(self, mw, first=False, search="", deck=None):
     QDialog.__init__(self, mw)
     self.mw = mw
     self.deck = deck or self.mw.col.decks.current()
     self.search = search
     self.form = aqt.forms.dyndconf.Ui_Dialog()
     self.form.setupUi(self)
     if first:
         label = _("Build")
     else:
         label = _("Rebuild")
     self.ok = self.form.buttonBox.addButton(
         label, QDialogButtonBox.AcceptRole)
     self.mw.checkpoint(_("Options"))
     self.setWindowModality(Qt.WindowModal)
     self.form.buttonBox.helpRequested.connect(lambda: openHelp("filtered"))
     self.setWindowTitle(_("Options for %s") % self.deck['name'])
     restoreGeom(self, "dyndeckconf")
     self.setupOrder()
     self.loadConf()
     if search:
         self.form.search.setText(search)
     self.form.search.selectAll()
     self.show()
     self.exec_()
     saveGeom(self, "dyndeckconf")
def getField(browser, fields):
    """Invoke field selection dialog and return field"""
    d = QDialog(browser)
    l = QVBoxLayout(d)
    d.label = QLabel(
        "Please select the field you would like to convert to tags", d)
    d.fieldSel = QComboBox(d)
    d.fieldSel.addItems(fields)
    d.buttonBox = QDialogButtonBox(d)
    d.buttonBox.setOrientation(Qt.Horizontal)
    d.buttonBox.setStandardButtons(
        QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
    d.buttonBox.accepted.connect(d.accept)
    d.buttonBox.rejected.connect(d.reject)
    l.addWidget(d.label)
    l.addWidget(d.fieldSel)
    l.addWidget(d.buttonBox)
    d.setWindowModality(Qt.WindowModal)
    d.setWindowTitle("Field to Tags")
    restoreGeom(d, "fieldtotags")
    r = d.exec_()
    saveGeom(d, "fieldtotags")
    if not r:
        return None

    idx = d.fieldSel.currentIndex()
    field = fields[idx]

    return field
Example #8
0
 def __init__(self, mw):
     if isMac:
         # use a separate window on os x so we can a clean menu
         QDialog.__init__(self, None, Qt.Window)
     else:
         QDialog.__init__(self, mw)
     QDialog.__init__(self, None, Qt.Window)
     self.mw = mw
     self.form = aqt.forms.editcurrent.Ui_Dialog()
     self.form.setupUi(self)
     self.setWindowTitle(_("Edit Current"))
     self.setMinimumHeight(400)
     self.setMinimumWidth(500)
     self.connect(self,
                  SIGNAL("rejected()"),
                  self.onSave)
     self.form.buttonBox.button(QDialogButtonBox.Close).setShortcut(
             QKeySequence("Ctrl+Return"))
     self.editor = aqt.editor.Editor(self.mw, self.form.fieldsArea, self)
     self.editor.setNote(self.mw.reviewer.card.note())
     restoreGeom(self, "editcurrent")
     addHook("reset", self.onReset)
     self.mw.requireReset()
     self.show()
     # reset focus after open
     self.editor.web.setFocus()
Example #9
0
    def loadProfile(self):
        # show main window
        if self.pm.profile['mainWindowState']:
            restoreGeom(self, "mainWindow")
            restoreState(self, "mainWindow")
        # toolbar needs to be retranslated
        self.toolbar.draw()
        # titlebar
        self.setWindowTitle("Anki - " + self.pm.name)
        # show and raise window for osx
        self.show()
        self.activateWindow()
        self.raise_()
        # maybe sync (will load DB)
        if self.pendingImport and os.path.basename(
                self.pendingImport).startswith("backup-"):
            # skip sync when importing a backup
            self.loadCollection()
        else:
            self.onSync(auto=True)
        # import pending?
        if self.pendingImport:
            if self.pm.profile['key']:
                showInfo(_("""\
To import into a password protected profile, please open the profile before attempting to import."""))
            else:
                self.handleImport(self.pendingImport)

            self.pendingImport = None
        runHook("profileLoaded")
Example #10
0
def showLastSentence(html):
	m = QMainWindow(mw)
	d = QDialog(m)
	m = QHBoxLayout()
	l = QVBoxLayout()
	r = QVBoxLayout()
	w = QLabel()
	w.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard)
	l.addWidget(w)
	ss = QPushButton(u'Say')
	bb = QDialogButtonBox(QDialogButtonBox.Close)
	bb.addButton(ss, QDialogButtonBox.ActionRole)
	bb.setOrientation(Qt.Vertical)
#	r.addWidget(ss)
	r.addWidget(bb)
	
	ss.connect(ss, SIGNAL("clicked()"), actionReadSentence)
	
	bb.connect(bb, SIGNAL("rejected()"), d, SLOT("reject()"))
	m.addLayout(l)
	m.addLayout(r)
	d.setLayout(m)
	d.setWindowModality(Qt.WindowModal)
	d.resize(649, 145) 
	restoreGeom(d, "LastSentence")
	html = "<html><body><h3>" + html + "</h3></body></html>"
	w.setText(html)
	d.exec_()
	saveGeom(d, "LastSentence")
Example #11
0
File: sound.py Project: ChYi/ankiqt
def getAudio(parent, string="", encode=True):
    "Record and return filename"
    # record first
    r = Recorder()
    mb = QMessageBox(parent)
    restoreGeom(mb, "audioRecorder")
    mb.setWindowTitle("Anki")
    mb.setIconPixmap(QPixmap(":/icons/media-record.png"))
    but = QPushButton(_("  Stop"))
    but.setIcon(QIcon(":/icons/media-playback-stop.png"))
    #but.setIconSize(QSize(32, 32))
    mb.addButton(but, QMessageBox.RejectRole)
    t = time.time()
    r.start()
    QApplication.instance().processEvents()
    while not mb.clickedButton():
        txt =_("Recording...<br>Time: %0.1f")
        mb.setText(txt % (time.time() - t))
        mb.show()
        QApplication.instance().processEvents()
    # ensure at least a second captured
    saveGeom(mb, "audioRecorder")
    while time.time() - t < 1:
        time.sleep(0.1)
    r.stop()
    # process
    r.postprocess(encode)
    return r.file()
Example #12
0
 def __init__(self, mw, deck):
     QDialog.__init__(self, mw)
     self.mw = mw
     self.deck = deck
     self.childDids = [
         d[1] for d in self.mw.col.decks.children(self.deck['id'])]
     self._origNewOrder = None
     self.form = aqt.forms.dconf.Ui_Dialog()
     self.form.setupUi(self)
     self.mw.checkpoint(_("Options"))
     self.setupCombos()
     self.setupConfs()
     self.setWindowModality(Qt.WindowModal)
     self.connect(self.form.buttonBox,
                  SIGNAL("helpRequested()"),
                  lambda: openHelp("deckoptions"))
     self.connect(self.form.confOpts, SIGNAL("clicked()"), self.confOpts)
     self.form.confOpts.setText(downArrow())
     self.connect(self.form.buttonBox.button(QDialogButtonBox.RestoreDefaults),
                  SIGNAL("clicked()"),
                  self.onRestore)
     self.setWindowTitle(_("Options for %s") % self.deck['name'])
     # qt doesn't size properly with altered fonts otherwise
     restoreGeom(self, "deckconf", adjustSize=True)
     self.show()
     self.exec_()
     saveGeom(self, "deckconf")
Example #13
0
 def __init__(self, mw, fact, type=0, ord=0, parent=None):
     QDialog.__init__(self, parent or mw, Qt.Window)
     self.mw = aqt.mw
     self.parent = parent or mw
     self.fact = fact
     self.type = type
     self.ord = ord
     self.deck = self.mw.deck
     self.model = fact.model()
     self.form = aqt.forms.clayout.Ui_Dialog()
     self.form.setupUi(self)
     self.setWindowTitle(_("%s Layout") % self.model.name)
     self.plastiqueStyle = None
     if isMac or isWin:
         self.plastiqueStyle = QStyleFactory.create("plastique")
     self.connect(self.form.buttonBox, SIGNAL("helpRequested()"),
                  self.onHelp)
     self.setupCards()
     self.setupFields()
     self.form.buttonBox.button(QDialogButtonBox.Help).setAutoDefault(False)
     self.form.buttonBox.button(QDialogButtonBox.Close).setAutoDefault(False)
     restoreSplitter(self.form.splitter, "clayout")
     restoreGeom(self, "CardLayout")
     if not self.reload(first=True):
         return
     self.exec_()
Example #14
0
 def __init__(self, mw):
     QDialog.__init__(self, mw, Qt.Window)
     mw.setupDialogGC(self)
     self.mw = mw
     self.name = "deckStats"
     self.period = 0
     self.form = aqt.forms.stats.Ui_Dialog()
     self.oldPos = None
     self.wholeCollection = False
     self.setMinimumWidth(700)
     f = self.form
     f.setupUi(self)
     restoreGeom(self, self.name)
     b = f.buttonBox.addButton(_("Save PDF"),
                                       QDialogButtonBox.ActionRole)
     b.clicked.connect(self.saveImage)
     b.setAutoDefault(False)
     f.groups.clicked.connect(lambda: self.changeScope("deck"))
     f.groups.setShortcut("g")
     f.all.clicked.connect(lambda: self.changeScope("collection"))
     f.month.clicked.connect(lambda: self.changePeriod(0))
     f.year.clicked.connect(lambda: self.changePeriod(1))
     f.life.clicked.connect(lambda: self.changePeriod(2))
     maybeHideClose(self.form.buttonBox)
     addCloseShortcut(self)
     self.refresh()
     self.show()
     self.activateWindow()
def myInit(self, mw):
    curDialogs = dialogs._dialogs
    self.dialogName = "AddCards"
    # existing instance → open second instance
    if curDialogs[self.dialogName][1] != None:
        self.dialogName = "AddCards2"
        self.setWindowTitle(_("Add") + " 2")
        restoreGeom(self, "add2")
Example #16
0
 def __init__(self, mw, parent):
     QDialog.__init__(self, parent, Qt.Window)
     self.mw = mw
     self.parent = parent
     self.deck = self.parent.deck
     self.dialog = aqt.forms.taglimit.Ui_Dialog()
     self.dialog.setupUi(self)
     self.rebuildTagList()
     restoreGeom(self, "tagLimit")
     self.exec_()
Example #17
0
 def __init__(self, mw):
     QDialog.__init__(self, mw)
     self.mw = mw
     self.form = aqt.forms.getaddons.Ui_Dialog()
     self.form.setupUi(self)
     b = self.form.buttonBox.addButton(
         _("Browse"), QDialogButtonBox.ActionRole)
     self.connect(b, SIGNAL("clicked()"), self.onBrowse)
     restoreGeom(self, "getaddons", adjustSize=True)
     self.exec_()
     saveGeom(self, "getaddons")
Example #18
0
 def onAdvanced(self):
     d = QDialog(self)
     frm = aqt.forms.modelopts.Ui_Dialog()
     frm.setupUi(d)
     frm.latexHeader.setText(self.model['latexPre'])
     frm.latexFooter.setText(self.model['latexPost'])
     d.setWindowTitle(_("Options for %s") % self.model['name'])
     frm.buttonBox.helpRequested.connect(lambda: openHelp("latex"))
     restoreGeom(d, "modelopts")
     d.exec_()
     saveGeom(d, "modelopts")
     self.model['latexPre'] = unicode(frm.latexHeader.toPlainText())
     self.model['latexPost'] = unicode(frm.latexFooter.toPlainText())
Example #19
0
 def __init__(self, mw, parent=None):
     self.mw = mw
     self.parent = parent or mw
     QDialog.__init__(self, self.parent, Qt.Window)
     self.col = mw.col
     self.mm = self.col.models
     self.mw.checkpoint(_("Note Types"))
     self.form = aqt.forms.models.Ui_Dialog()
     self.form.setupUi(self)
     self.connect(self.form.buttonBox, SIGNAL("helpRequested()"), lambda: openHelp("notetypes"))
     self.setupModels()
     restoreGeom(self, "models")
     self.exec_()
Example #20
0
 def __init__(self, dlg):
     QDialog.__init__(self, dlg)
     self.addonsDlg = dlg
     self.mgr = dlg.mgr
     self.mw = self.mgr.mw
     self.form = aqt.forms.getaddons.Ui_Dialog()
     self.form.setupUi(self)
     b = self.form.buttonBox.addButton(
         _("Browse Add-ons"), QDialogButtonBox.ActionRole)
     b.clicked.connect(self.onBrowse)
     restoreGeom(self, "getaddons", adjustSize=True)
     self.exec_()
     saveGeom(self, "getaddons")
Example #21
0
 def __init__(self, browser, nids):
     QDialog.__init__(self, browser)
     self.browser = browser
     self.nids = nids
     self.oldModel = browser.card.note().model()
     self.form = aqt.forms.changemodel.Ui_Dialog()
     self.form.setupUi(self)
     self.setWindowModality(Qt.WindowModal)
     self.setup()
     restoreGeom(self, "changeModel")
     addHook("reset", self.onReset)
     addHook("currentModelChanged", self.onReset)
     self.exec_()
Example #22
0
 def __init__(self, mw, names=None, accept=None, title=None,
              help="studydeck", current=None, cancel=True,
              parent=None, dyn=False, buttons=[], geomKey="default"):
     QDialog.__init__(self, parent or mw)
     self.mw = mw
     self.form = aqt.forms.studydeck.Ui_Dialog()
     self.form.setupUi(self)
     self.form.filter.installEventFilter(self)
     self.cancel = cancel
     addHook('reset', self.onReset)
     self.geomKey = "studyDeck-"+geomKey
     restoreGeom(self, self.geomKey)
     if not cancel:
         self.form.buttonBox.removeButton(
             self.form.buttonBox.button(QDialogButtonBox.Cancel))
     if buttons:
         for b in buttons:
             self.form.buttonBox.addButton(b, QDialogButtonBox.ActionRole)
     else:
         b = QPushButton(_("Add"))
         b.setShortcut(QKeySequence("Ctrl+N"))
         b.setToolTip(shortcut(_("Add New Deck (Ctrl+N)")))
         self.form.buttonBox.addButton(b, QDialogButtonBox.ActionRole)
         b.connect(b, SIGNAL("clicked()"), self.onAddDeck)
     if title:
         self.setWindowTitle(title)
     if not names:
         names = sorted(self.mw.col.decks.allNames(dyn=dyn))
         self.nameFunc = None
         self.origNames = names
     else:
         self.nameFunc = names
         self.origNames = names()
     self.name = None
     self.ok = self.form.buttonBox.addButton(
         accept or _("Study"), QDialogButtonBox.AcceptRole)
     self.setWindowModality(Qt.WindowModal)
     self.connect(self.form.buttonBox,
                  SIGNAL("helpRequested()"),
                  lambda: openHelp(help))
     self.connect(self.form.filter,
                  SIGNAL("textEdited(QString)"),
                  self.redraw)
     self.connect(self.form.list,
                  SIGNAL("itemDoubleClicked(QListWidgetItem*)"),
                  self.accept)
     self.show()
     # redraw after show so position at center correct
     self.redraw("", current)
     self.exec_()
 def __init__(self, parent=None):
     QDialog.__init__(self, parent=None)
     self.ui = svg_edit_dialog.Ui_SimplePicOccQDialog()
     self.ui.setupUi(self)
     self.web_view_widget = QWebView()
     l = QVBoxLayout()
     l.setMargin(0)
     l.addWidget(self.web_view_widget)
     # self.setLayout(l)
     self.ui.centralWidget.setLayout(l)
     self.connect(self.ui.singleCardButton, SIGNAL("clicked()"), self.add_notes_single_mask)
     self.connect(self.ui.multiButton, SIGNAL("clicked()"), self.add_notes_multiple_masks)
     self.connect(self.ui.multiMaskedButton, SIGNAL("clicked()"), self.add_notes_multiple_hiding_masks)
     restoreGeom(self, "PicOccSVGEditDialog")
Example #24
0
    def onFindDupes(self):
        return showInfo("not yet implemented")
        win = QDialog(self)
        aqt = ankiqt.forms.finddupes.Ui_Dialog()
        dialog.setupUi(win)
        restoreGeom(win, "findDupes")
        fields = sorted(self.card.note.model.fieldModels, key=attrgetter("name"))
        # per-model data
        data = self.col.db.all("""
select fm.id, m.name || '>' || fm.name from fieldmodels fm, models m
where fm.modelId = m.id""")
        data.sort(key=itemgetter(1))
        # all-model data
        data2 = self.col.db.all("""
select fm.id, fm.name from fieldmodels fm""")
        byName = {}
        for d in data2:
            if d[1] in byName:
                byName[d[1]].append(d[0])
            else:
                byName[d[1]] = [d[0]]
        names = byName.keys()
        names.sort()
        alldata = [(byName[n], n) for n in names] + data
        dialog.searchArea.addItems([d[1] for d in alldata])
        # links
        dialog.webView.page().setLinkDelegationPolicy(
            QWebPage.DelegateAllLinks)
        self.connect(dialog.webView,
                     SIGNAL("linkClicked(QUrl)"),
                     self.dupeLinkClicked)

        def onFin(code):
            saveGeom(win, "findDupes")
        self.connect(win, SIGNAL("finished(int)"), onFin)

        def onClick():
            idx = dialog.searchArea.currentIndex()
            data = alldata[idx]
            if isinstance(data[0], list):
                # all models
                fmids = data[0]
            else:
                # single model
                fmids = [data[0]]
            self.duplicatesReport(dialog.webView, fmids)

        self.connect(dialog.searchButton, SIGNAL("clicked()"),
                     onClick)
        win.show()
Example #25
0
 def __init__(self, mw, parent):
     QDialog.__init__(self, parent, Qt.Window)
     self.mw = mw
     self.parent = parent
     self.deck = self.parent.deck
     self.dialog = aqt.forms.taglimit.Ui_Dialog()
     self.dialog.setupUi(self)
     s = QShortcut(QKeySequence("ctrl+d"), self.dialog.activeList, context=Qt.WidgetShortcut)
     s.activated.connect(self.dialog.activeList.clearSelection)
     s = QShortcut(QKeySequence("ctrl+d"), self.dialog.inactiveList, context=Qt.WidgetShortcut)
     s.activated.connect(self.dialog.inactiveList.clearSelection)
     self.rebuildTagList()
     restoreGeom(self, "tagLimit")
     self.exec_()
Example #26
0
def onhanziStats():
    mw.progress.start(immediate=True)
    rep = genhanziStats()
    d = QDialog(mw)
    l = QVBoxLayout()
    w = AnkiWebView()
    l.addWidget(w)
    css = "font{word-wrap:break-word;} div{display:none;}"
    w.stdHtml(rep, css)
    d.setLayout(l)
    d.resize(500, 400)
    restoreGeom(d, "hanzistats")
    mw.progress.finish()
    d.exec_()
    saveGeom(d, "hanzistats")
Example #27
0
 def __init__(self, dlg, addon, conf):
     super().__init__(dlg)
     self.addon = addon
     self.conf = conf
     self.mgr = dlg.mgr
     self.form = aqt.forms.addonconf.Ui_Dialog()
     self.form.setupUi(self)
     restore = self.form.buttonBox.button(QDialogButtonBox.RestoreDefaults)
     restore.clicked.connect(self.onRestoreDefaults)
     self.setupFonts()
     self.updateHelp()
     self.updateText(self.conf)
     restoreGeom(self, "addonconf")
     restoreSplitter(self.form.splitter, "addonconf")
     self.show()
Example #28
0
    def onCheckMediaDB(self):
        self.progress.start(immediate=True)
        (nohave, unused, warnings) = self.col.media.check()
        self.progress.finish()
        # generate report
        report = ""
        if warnings:
            report += "\n".join(warnings) + "\n"
        if unused:
            if report:
                report += "\n\n\n"
            report += _(
                "In media folder but not used by any cards:")
            report += "\n" + "\n".join(unused)
        if nohave:
            if report:
                report += "\n\n\n"
            report += _(
                "Used on cards but missing from media folder:")
            report += "\n" + "\n".join(nohave)
        if not report:
            tooltip(_("No unused or missing files found."))
            return
        # show report and offer to delete
        diag = QDialog(self)
        diag.setWindowTitle("Anki")
        layout = QVBoxLayout(diag)
        diag.setLayout(layout)
        text = QTextEdit()
        text.setReadOnly(True)
        text.setPlainText(report)
        layout.addWidget(text)
        box = QDialogButtonBox(QDialogButtonBox.Close)
        layout.addWidget(box)
        if unused:
            b = QPushButton(_("Delete Unused Files"))
            b.setAutoDefault(False)
            box.addButton(b, QDialogButtonBox.ActionRole)
            b.clicked.connect(
                lambda c, u=unused, d=diag: self.deleteUnused(u, d))

        box.rejected.connect(diag.reject)
        diag.setMinimumHeight(400)
        diag.setMinimumWidth(500)
        restoreGeom(diag, "checkmediadb")
        diag.exec_()
        saveGeom(diag, "checkmediadb")
Example #29
0
 def onRevlog(self):
     data = self._revlogData()
     d = QDialog(self)
     l = QVBoxLayout()
     l.setMargin(0)
     w = AnkiWebView()
     l.addWidget(w)
     w.stdHtml(data)
     bb = QDialogButtonBox(QDialogButtonBox.Close)
     l.addWidget(bb)
     bb.connect(bb, SIGNAL("rejected()"), d, SLOT("reject()"))
     d.setLayout(l)
     d.setWindowModality(Qt.WindowModal)
     d.resize(500, 400)
     restoreGeom(d, "revlog")
     d.exec_()
     saveGeom(d, "revlog")
Example #30
0
 def onAdvanced(self):
     d = QDialog(self)
     frm = aqt.forms.modelopts.Ui_Dialog()
     frm.setupUi(d)
     frm.latexsvg.setChecked(self.model.get("latexsvg", False))
     frm.latexHeader.setText(self.model['latexPre'])
     frm.latexFooter.setText(self.model['latexPost'])
     frm.newStyleWhitespace.setChecked(self.model.get("prewrap", False))
     d.setWindowTitle(_("Options for %s") % self.model['name'])
     frm.buttonBox.helpRequested.connect(lambda: openHelp("latex"))
     restoreGeom(d, "modelopts")
     d.exec_()
     saveGeom(d, "modelopts")
     self.model['latexsvg'] = frm.latexsvg.isChecked()
     self.model['latexPre'] = str(frm.latexHeader.toPlainText())
     self.model['latexPost'] = str(frm.latexFooter.toPlainText())
     self.model['prewrap'] = frm.newStyleWhitespace.isChecked()
Example #31
0
    def __init__(self, mw: aqt.main.AnkiQt, report: EmptyCardsReport) -> None:
        super().__init__(mw)
        self.mw = mw.weakref()
        self.mw.garbage_collect_on_dialog_finish(self)
        self.report = report
        self.form = aqt.forms.emptycards.Ui_Dialog()
        self.form.setupUi(self)
        restoreGeom(self, "emptycards")
        self.setWindowTitle(tr.empty_cards_window_title())
        disable_help_button(self)
        self.form.keep_notes.setText(tr.empty_cards_preserve_notes_checkbox())
        self.form.webview.set_title("empty cards")
        self.form.webview.set_bridge_command(self._on_note_link_clicked, self)

        gui_hooks.empty_cards_will_show(self)

        # make the note ids clickable
        html = re.sub(
            r"\[anki:nid:(\d+)\]",
            "<a href=# onclick=\"pycmd('nid:\\1'); return false\">\\1</a>: ",
            report.report,
        )
        style = "<style>.allempty { color: red; }</style>"
        self.form.webview.stdHtml(style + html, context=self)

        def on_finished(code: Any) -> None:
            self.form.webview.cleanup()
            self.form.webview = None
            saveGeom(self, "emptycards")

        qconnect(self.finished, on_finished)

        self._delete_button = self.form.buttonBox.addButton(
            tr.empty_cards_delete_button(),
            QDialogButtonBox.ButtonRole.ActionRole)
        self._delete_button.setAutoDefault(False)
        qconnect(self._delete_button.clicked, self._on_delete)
Example #32
0
 def __init__(self, dlg: QDialog, addon: str, conf: Dict) -> None:
     super().__init__(dlg)
     self.addon = addon
     self.conf = conf
     self.mgr = dlg.mgr
     self.form = aqt.forms.addonconf.Ui_Dialog()
     self.form.setupUi(self)
     restore = self.form.buttonBox.button(QDialogButtonBox.RestoreDefaults)
     qconnect(restore.clicked, self.onRestoreDefaults)
     self.setupFonts()
     self.updateHelp()
     self.updateText(self.conf)
     restoreGeom(self, "addonconf")
     restoreSplitter(self.form.splitter, "addonconf")
     self.setWindowTitle(
         without_unicode_isolation(
             tr(
                 TR.ADDONS_CONFIG_WINDOW_TITLE,
                 name=self.mgr.addon_meta(addon).human_name(),
             )
         )
     )
     disable_help_button(self)
     self.show()
Example #33
0
def on_gui(self):
    addon = self.onlyOneSelected()
    if not addon:
        return

    # does add-on manage its own config?
    act = self.mgr.configAction(addon)
    if act:
        ret = act()
        if ret is not False:
            return

    schema = _addonSchema(mw.addonManager, addon)
    if schema is None:
        return
    conf = self.mgr.getConfig(addon)
    if conf is None:
        showInfo(_("Add-on has no configuration."))
        return

    builder = WidgetBuilder()
    form = builder.create_form(schema, palette=mw.palette())
    form.widget.state = conf

    restoreGeom(form, "gui_window")
    form.buttonBox = QtWidgets.QDialogButtonBox(form)
    form.buttonBox.setOrientation(QtCore.Qt.Horizontal)
    form.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel
                                      | QtWidgets.QDialogButtonBox.Ok)
    form.buttonBox.setObjectName("buttonBox")
    form.buttonBox.accepted.connect(form.accept)
    form.buttonBox.rejected.connect(form.reject)
    form.layout.addWidget(form.buttonBox)
    res = form.exec()
    if res == QtWidgets.QDialog.Accepted:
        self.mgr.writeConfig(addon, form.widget.state)
Example #34
0
File: stats.py Project: sinpat/anki
 def __init__(self, mw: aqt.main.AnkiQt):
     QDialog.__init__(self, mw, Qt.Window)
     mw.setupDialogGC(self)
     self.mw = mw
     self.name = "deckStats"
     self.period = 0
     self.form = aqt.forms.stats.Ui_Dialog()
     self.oldPos = None
     self.wholeCollection = False
     self.setMinimumWidth(700)
     f = self.form
     f.setupUi(self)
     f.groupBox.setVisible(False)
     f.groupBox_2.setVisible(False)
     restoreGeom(self, self.name)
     b = f.buttonBox.addButton(_("Save PDF"), QDialogButtonBox.ActionRole)
     qconnect(b.clicked, self.saveImage)
     b.setAutoDefault(False)
     maybeHideClose(self.form.buttonBox)
     addCloseShortcut(self)
     gui_hooks.stats_dialog_will_show(self)
     self.show()
     self.refresh()
     self.activateWindow()
Example #35
0
    def _create_gui(self) -> None:
        self.setWindowTitle(tr.actions_preview())

        self.close_shortcut = QShortcut(QKeySequence("Ctrl+Shift+P"), self)
        qconnect(self.close_shortcut.activated, self.close)

        qconnect(self.finished, self._on_finished)
        self.silentlyClose = True
        self.vbox = QVBoxLayout()
        self.vbox.setContentsMargins(0, 0, 0, 0)
        self._web = AnkiWebView(title="previewer")
        self.vbox.addWidget(self._web)
        self.bbox = QDialogButtonBox()
        self.bbox.setLayoutDirection(Qt.LayoutDirection.LeftToRight)

        self._replay = self.bbox.addButton(
            tr.actions_replay_audio(), QDialogButtonBox.ButtonRole.ActionRole
        )
        self._replay.setAutoDefault(False)
        self._replay.setShortcut(QKeySequence("R"))
        self._replay.setToolTip(tr.actions_shortcut_key(val="R"))
        qconnect(self._replay.clicked, self._on_replay_audio)

        both_sides_button = QCheckBox(tr.qt_misc_back_side_only())
        both_sides_button.setShortcut(QKeySequence("B"))
        both_sides_button.setToolTip(tr.actions_shortcut_key(val="B"))
        self.bbox.addButton(both_sides_button, QDialogButtonBox.ButtonRole.ActionRole)
        self._show_both_sides = self.mw.col.get_config_bool(
            Config.Bool.PREVIEW_BOTH_SIDES
        )
        both_sides_button.setChecked(self._show_both_sides)
        qconnect(both_sides_button.toggled, self._on_show_both_sides)

        self.vbox.addWidget(self.bbox)
        self.setLayout(self.vbox)
        restoreGeom(self, "preview")
Example #36
0
 def __init__(self, mw):
     if isMac:
         # use a separate window on os x so we can a clean menu
         QDialog.__init__(self, None, Qt.Window)
     else:
         QDialog.__init__(self, mw)
     QDialog.__init__(self, None, Qt.Window)
     self.mw = mw
     self.form = aqt.forms.editcurrent.Ui_Dialog()
     self.form.setupUi(self)
     self.setWindowTitle(_("Edit Current"))
     self.setMinimumHeight(400)
     self.setMinimumWidth(500)
     self.rejected.connect(self.onSave)
     self.form.buttonBox.button(QDialogButtonBox.Close).setShortcut(
         QKeySequence("Ctrl+Return"))
     self.editor = aqt.editor.Editor(self.mw, self.form.fieldsArea, self)
     self.editor.setNote(self.mw.reviewer.card.note())
     restoreGeom(self, "editcurrent")
     addHook("reset", self.onReset)
     self.mw.requireReset()
     self.show()
     # reset focus after open
     self.editor.web.setFocus()
Example #37
0
 def __init__(self, parent, content, mode, win_title):
     super(CmDialogBase, self).__init__(parent)
     self.parent = parent
     self.js_save_cmd = "editor.getValue()"
     self.setWindowTitle(win_title)
     self.dialog = edit_window.Ui_Dialog()
     self.dialog.setupUi(self)
     self.dialog.outer.setContentsMargins(0, 0, 0, 0)
     self.dialog.outer.setSpacing(0)
     self.web = MyWebView(self.parent)
     self.dialog.outer.addWidget(self.web)
     qsp = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     qsp.setVerticalStretch(2)
     self.web.setSizePolicy(qsp)
     acceptShortcut = QShortcut(QKeySequence("Ctrl+Return"), self)
     acceptShortcut.activated.connect(self.accept)
     self.web.title = "html source with codemirror"
     self.web.contextMenuEvent = self.contextMenuEvent
     tmpl_content = readfile("codemirror.html")
     # the following seems to break cm so I just remove it <!--StartFragment--><!--EndFragment-->
     self.content = content.replace("<!--StartFragment-->",
                                    "").replace("<!--EndFragment-->", "")
     bodyhtml = tmpl_content.format(
         autoformat_function="html_beautify"
         if mode == "htmlmixed" else "css_beautify",
         content="",
         isvim=keymap[1],
         keymap=keymap[0],
         mode=mode,
         theme=selectedtheme,
         unique_string=unique_string,
         lint="true",
     )
     self.web.stdHtml(bodyhtml, cssfiles, jsfiles)
     restoreGeom(self, "1043915942_CmDialog")
     self.web.loadFinished.connect(self.load_finished)
Example #38
0
 def __init__(self, mw):
     QDialog.__init__(self, mw, Qt.Window)
     mw.setupDialogGC(self)
     self.mw = mw
     self.name = "deckStats"
     self.period = 0
     self.form = aqt.forms.stats.Ui_Dialog()
     self.oldPos = None
     self.wholeCollection = False
     self.setMinimumWidth(700)
     f = self.form
     if theme_manager.night_mode and not theme_manager.macos_dark_mode():
         # the grouping box renders incorrectly in the fusion theme. 5.9+
         # 5.13 behave differently to 5.14, but it looks bad in either case,
         # and adjusting the top margin makes the 'save PDF' button show in
         # the wrong place, so for now we just disable the border instead
         self.setStyleSheet("QGroupBox { border: 0; }")
     f.setupUi(self)
     restoreGeom(self, self.name)
     b = f.buttonBox.addButton(
         tr(TR.STATISTICS_SAVE_PDF), QDialogButtonBox.ActionRole
     )
     qconnect(b.clicked, self.saveImage)
     b.setAutoDefault(False)
     qconnect(f.groups.clicked, lambda: self.changeScope("deck"))
     f.groups.setShortcut("g")
     qconnect(f.all.clicked, lambda: self.changeScope("collection"))
     qconnect(f.month.clicked, lambda: self.changePeriod(0))
     qconnect(f.year.clicked, lambda: self.changePeriod(1))
     qconnect(f.life.clicked, lambda: self.changePeriod(2))
     maybeHideClose(self.form.buttonBox)
     addCloseShortcut(self)
     gui_hooks.stats_dialog_old_will_show(self)
     self.show()
     self.refresh()
     self.activateWindow()
Example #39
0
 def __init__(self, mw: aqt.AnkiQt) -> None:
     QDialog.__init__(self, None, Qt.WindowType.Window)
     mw.garbage_collect_on_dialog_finish(self)
     self.mw = mw
     self.form = aqt.forms.editcurrent.Ui_Dialog()
     self.form.setupUi(self)
     self.setWindowTitle(tr.editing_edit_current())
     disable_help_button(self)
     self.setMinimumHeight(400)
     self.setMinimumWidth(250)
     self.form.buttonBox.button(
         QDialogButtonBox.StandardButton.Close).setShortcut(
             QKeySequence("Ctrl+Return"))
     self.editor = aqt.editor.Editor(
         self.mw,
         self.form.fieldsArea,
         self,
         editor_mode=aqt.editor.EditorMode.EDIT_CURRENT,
     )
     self.editor.card = self.mw.reviewer.card
     self.editor.set_note(self.mw.reviewer.card.note(), focusTo=0)
     restoreGeom(self, "editcurrent")
     gui_hooks.operation_did_execute.append(self.on_operation_did_execute)
     self.show()
Example #40
0
    def loadProfile(self, onsuccess=None):
        self.maybeAutoSync()

        if not self.loadCollection():
            return

        # show main window
        if self.pm.profile['mainWindowState']:
            restoreGeom(self, "mainWindow")
            restoreState(self, "mainWindow")
        # titlebar
        self.setWindowTitle(self.pm.name + " - Anki")
        # show and raise window for osx
        self.show()
        self.activateWindow()
        self.raise_()

        # import pending?
        if self.pendingImport:
            self.handleImport(self.pendingImport)
            self.pendingImport = None
        runHook("profileLoaded")
        if onsuccess:
            onsuccess()
Example #41
0
 def _setup_dialog(self) -> None:
     self.setWindowTitle("Anki")
     icon = QLabel()
     icon.setPixmap(QPixmap(":/icons/media-record.png"))
     self.label = QLabel("...")
     hbox = QHBoxLayout()
     hbox.addWidget(icon)
     hbox.addWidget(self.label)
     v = QVBoxLayout()
     v.addLayout(hbox)
     buts = QDialogButtonBox.Save | QDialogButtonBox.Cancel
     b = QDialogButtonBox(buts)  # type: ignore
     v.addWidget(b)
     self.setLayout(v)
     save_button = b.button(QDialogButtonBox.Save)
     save_button.setDefault(True)
     save_button.setAutoDefault(True)
     qconnect(save_button.clicked, self.accept)
     cancel_button = b.button(QDialogButtonBox.Cancel)
     cancel_button.setDefault(False)
     cancel_button.setAutoDefault(False)
     qconnect(cancel_button.clicked, self.reject)
     restoreGeom(self, "audioRecorder2")
     self.show()
Example #42
0
 def __init__(self, mw, deck, parent=None):
     QDialog.__init__(self, parent or mw)
     self.mw = mw
     self.deck = deck
     self.childDids = [
         d[1] for d in self.mw.col.decks.children(self.deck['id'])
     ]
     self._origNewOrder = None
     self.form = aqt.forms.dconf.Ui_Dialog()
     self.form.setupUi(self)
     self.mw.checkpoint(_("Options"))
     self.setupCombos()
     self.setupConfs()
     self.setWindowModality(Qt.WindowModal)
     self.form.confOpts.clicked.connect(self.confOpts)
     self.form.confOpts.setText(downArrow())
     self.form.buttonBox.button(
         QDialogButtonBox.RestoreDefaults).clicked.connect(self.onRestore)
     self.setWindowTitle(_("Options for %s") % self.deck['name'])
     # qt doesn't size properly with altered fonts otherwise
     restoreGeom(self, "deckconf", adjustSize=True)
     self.show()
     self.exec_()
     saveGeom(self, "deckconf")
Example #43
0
File: addons.py Project: zerrs/anki
    def __init__(self, addonsManager: AddonManager):
        self.mgr = addonsManager
        self.mw = addonsManager.mw

        super().__init__(self.mw)

        f = self.form = aqt.forms.addons.Ui_Dialog()
        f.setupUi(self)
        qconnect(f.getAddons.clicked, self.onGetAddons)
        qconnect(f.installFromFile.clicked, self.onInstallFiles)
        qconnect(f.checkForUpdates.clicked, self.check_for_updates)
        qconnect(f.toggleEnabled.clicked, self.onToggleEnabled)
        qconnect(f.viewPage.clicked, self.onViewPage)
        qconnect(f.viewFiles.clicked, self.onViewFiles)
        qconnect(f.delete_2.clicked, self.onDelete)
        qconnect(f.config.clicked, self.onConfig)
        qconnect(self.form.addonList.itemDoubleClicked, self.onConfig)
        qconnect(self.form.addonList.currentRowChanged,
                 self._onAddonItemSelected)
        self.setAcceptDrops(True)
        self.redrawAddons()
        restoreGeom(self, "addons")
        gui_hooks.addons_dialog_will_show(self)
        self.show()
Example #44
0
 def _onHtmlEdit(self, field):
     d = QDialog(self.widget, Qt.Window)
     form = aqt.forms.edithtml.Ui_Dialog()
     form.setupUi(d)
     restoreGeom(d, "htmlEditor")
     qconnect(form.buttonBox.helpRequested, lambda: openHelp("editor"))
     form.textEdit.setPlainText(self.note.fields[field])
     d.show()
     form.textEdit.moveCursor(QTextCursor.End)
     d.exec_()
     html = form.textEdit.toPlainText()
     if html.find(">") > -1:
         # filter html through beautifulsoup so we can strip out things like a
         # leading </div>
         html_escaped = self.mw.col.media.escapeImages(html)
         with warnings.catch_warnings():
             warnings.simplefilter("ignore", UserWarning)
             html_escaped = str(BeautifulSoup(html_escaped, "html.parser"))
             html = self.mw.col.media.escapeImages(html_escaped, unescape=True)
     self.note.fields[field] = html
     if not self.addMode:
         self.note.flush()
     self.loadNote(focusTo=field)
     saveGeom(d, "htmlEditor")
Example #45
0
    def __init__(
        self,
        mw: AnkiQt,
        card: Optional[Card] = None,
        search: Optional[Tuple[Union[str, SearchNode]]] = None,
    ) -> None:
        """
        card -- try to select the provided card after executing "search" or
                "deck:current" (if "search" was None)
        search -- set and perform search; caller must ensure validity
        """

        QMainWindow.__init__(self, None, Qt.Window)
        self.mw = mw
        self.col = self.mw.col
        self.lastFilter = ""
        self.focusTo: Optional[int] = None
        self._previewer: Optional[Previewer] = None
        self._closeEventHasCleanedUp = False
        self.form = aqt.forms.browser.Ui_Dialog()
        self.form.setupUi(self)
        self.setupSidebar()
        restoreGeom(self, "editor", 0)
        restoreState(self, "editor")
        restoreSplitter(self.form.splitter, "editor3")
        self.form.splitter.setChildrenCollapsible(False)
        self.card: Optional[Card] = None
        self.setup_table()
        self.setupMenus()
        self.setupHooks()
        self.setupEditor()
        # disable undo/redo
        self.on_undo_state_change(mw.undo_actions_info())
        gui_hooks.browser_will_show(self)
        self.show()
        self.setupSearch(card, search)
Example #46
0
 def __init__(self, mw, note, ord=0, parent=None, addMode=False):
     QDialog.__init__(self, parent or mw, Qt.Window)
     self.mw = aqt.mw
     self.parent = parent or mw
     self.note = note
     self.ord = ord
     self.col = self.mw.col
     self.mm = self.mw.col.models
     self.model = note.model()
     self.mw.checkpoint(_("Card Layout"))
     self.addMode = addMode
     if addMode:
         # save it to DB temporarily
         note.flush()
     self.setupTabs()
     self.setupButtons()
     self.setWindowTitle(_("%s Layout") % self.model['name'])
     v1 = QVBoxLayout()
     v1.addWidget(self.tabs)
     v1.addLayout(self.buttons)
     self.setLayout(v1)
     self.redraw()
     restoreGeom(self, "CardLayout")
     self.exec_()
Example #47
0
 def __init__(
     self,
     mw: aqt.AnkiQt,
     names: Callable = None,
     accept: str = None,
     title: str = None,
     help: HelpPageArgument = HelpPage.KEYBOARD_SHORTCUTS,
     current: Optional[str] = None,
     cancel: bool = True,
     parent: Optional[QWidget] = None,
     dyn: bool = False,
     buttons: Optional[list[Union[str, QPushButton]]] = None,
     geomKey: str = "default",
 ) -> None:
     QDialog.__init__(self, parent or mw)
     self.mw = mw
     self.form = aqt.forms.studydeck.Ui_Dialog()
     self.form.setupUi(self)
     self.form.filter.installEventFilter(self)
     self.cancel = cancel
     gui_hooks.state_did_reset.append(self.onReset)
     self.geomKey = f"studyDeck-{geomKey}"
     restoreGeom(self, self.geomKey)
     disable_help_button(self)
     if not cancel:
         self.form.buttonBox.removeButton(
             self.form.buttonBox.button(
                 QDialogButtonBox.StandardButton.Cancel))
     if buttons is not None:
         for button_or_label in buttons:
             self.form.buttonBox.addButton(
                 button_or_label, QDialogButtonBox.ButtonRole.ActionRole)
     else:
         b = QPushButton(tr.actions_add())
         b.setShortcut(QKeySequence("Ctrl+N"))
         b.setToolTip(shortcut(tr.decks_add_new_deck_ctrlandn()))
         self.form.buttonBox.addButton(
             b, QDialogButtonBox.ButtonRole.ActionRole)
         qconnect(b.clicked, self.onAddDeck)
     if title:
         self.setWindowTitle(title)
     if not names:
         names_ = [
             d.name for d in self.mw.col.decks.all_names_and_ids(
                 include_filtered=dyn, skip_empty_default=True)
         ]
         self.nameFunc = None
         self.origNames = names_
     else:
         self.nameFunc = names
         self.origNames = names()
     self.name: Optional[str] = None
     self.ok = self.form.buttonBox.addButton(
         accept or tr.decks_study(), QDialogButtonBox.ButtonRole.AcceptRole)
     self.setWindowModality(Qt.WindowModality.WindowModal)
     qconnect(self.form.buttonBox.helpRequested, lambda: openHelp(help))
     qconnect(self.form.filter.textEdited, self.redraw)
     qconnect(self.form.list.itemDoubleClicked, self.accept)
     self.show()
     # redraw after show so position at center correct
     self.redraw("", current)
     self.exec()
Example #48
0
    def __init__(
        self,
        mw: AnkiQt,
        search: Optional[str] = None,
        search_2: Optional[str] = None,
        deck: Optional[Deck] = None,
    ) -> None:
        """If 'deck' is an existing filtered deck, load and modify its settings.
        Otherwise, build a new one and derive settings from the current deck.
        """

        QDialog.__init__(self, mw)
        self.mw = mw
        self.col = self.mw.col
        self.did: Optional[int] = None
        self.form = aqt.forms.dyndconf.Ui_Dialog()
        self.form.setupUi(self)
        self.mw.checkpoint(tr(TR.ACTIONS_OPTIONS))
        self.initialSetup()
        self.old_deck = self.col.decks.current()

        if deck and deck["dyn"]:
            # modify existing dyn deck
            label = tr(TR.ACTIONS_REBUILD)
            self.deck = deck
            self.loadConf()
        elif self.old_deck["dyn"]:
            # create new dyn deck from other dyn deck
            label = tr(TR.DECKS_BUILD)
            self.loadConf(deck=self.old_deck)
            self.new_dyn_deck()
        else:
            # create new dyn deck from regular deck
            label = tr(TR.DECKS_BUILD)
            self.new_dyn_deck()
            self.loadConf()
            self.set_default_searches(self.old_deck["name"])

        self.form.name.setText(self.deck["name"])
        self.form.name.setPlaceholderText(self.deck["name"])
        self.set_custom_searches(search, search_2)
        qconnect(self.form.search_button.clicked, self.on_search_button)
        qconnect(self.form.search_button_2.clicked, self.on_search_button_2)
        qconnect(self.form.hint_button.clicked, self.on_hint_button)
        blue = theme_manager.color(colors.LINK)
        grey = theme_manager.color(colors.DISABLED)
        self.setStyleSheet(f"""QPushButton[label] {{ padding: 0; border: 0 }}
            QPushButton[label]:hover {{ text-decoration: underline }}
            QPushButton[label="search"] {{ color: {blue} }}
            QPushButton[label="hint"] {{ color: {grey} }}""")
        disable_help_button(self)
        self.setWindowModality(Qt.WindowModal)
        qconnect(self.form.buttonBox.helpRequested,
                 lambda: openHelp(HelpPage.FILTERED_DECK))
        self.setWindowTitle(
            without_unicode_isolation(
                tr(TR.ACTIONS_OPTIONS_FOR, val=self.deck["name"])))
        self.form.buttonBox.button(QDialogButtonBox.Ok).setText(label)
        if self.col.schedVer() == 1:
            self.form.secondFilter.setVisible(False)
        restoreGeom(self, "dyndeckconf")

        self.show()
Example #49
0
 def __init__(self, parent, tags, alltags):
     QDialog.__init__(self, parent,
                      Qt.WindowType.Window)  # super().__init__(parent)
     self.basic_mode = gc("dialog type: basic_but_quick")
     self.parent = parent
     self.alltags = alltags
     self.gridLayout = QGridLayout(self)
     self.gridLayout.setObjectName("gridLayout")
     self.label = QLabel("Edit tags:")
     self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
     self.verticalLayout = QVBoxLayout()
     self.verticalLayout.setObjectName("verticalLayout")
     self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1)
     self.buttonBox = QDialogButtonBox(self)
     self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
     self.buttonBox.setStandardButtons(
         QDialogButtonBox.StandardButton.Cancel
         | QDialogButtonBox.StandardButton.Ok)
     self.shortcut = QShortcut(QKeySequence("Ctrl+Return"), self)
     self.shortcut.activated.connect(self.accept)
     self.helpButton = QPushButton(
         "add empty line", clicked=lambda: self.maybe_add_line(force=True))
     self.buttonBox.addButton(self.helpButton,
                              QDialogButtonBox.ButtonRole.HelpRole)
     self.filterbutton = QPushButton("edit tag for current line",
                                     clicked=self.tagselector)
     self.buttonBox.addButton(self.filterbutton,
                              QDialogButtonBox.ButtonRole.ResetRole)
     self.searchButton = QPushButton(
         "search", clicked=lambda: self.do_browser_search(extra_search=""))
     self.buttonBox.addButton(self.searchButton,
                              QDialogButtonBox.ButtonRole.ResetRole)
     self.gridLayout.addWidget(self.buttonBox, 2, 0, 1, 1)
     self.buttonBox.accepted.connect(self.accept)
     self.buttonBox.rejected.connect(self.reject)
     self.setWindowTitle("Anki - Edit Tags")
     originalheight = self.height()
     restoreGeom(self, "TagDialogExtended")
     self.resize(self.width(), originalheight)
     if not tags:
         tags = [
             "",
         ]
     else:
         tags.append("")
     self.line_list = []
     for t in tags:
         self.maybe_add_line(t)
     self.cut = gc("in tag lines dialog: open filterdialog for single tag")
     if self.cut:
         self.filterbutton.setToolTip('shortcut: {}'.format(self.cut))
         self.selkey = QShortcut(QKeySequence(self.cut), self)
         self.selkey.activated.connect(self.tagselector)
     self.browser_scut = gc("in tag lines dialog: search browser for tag")
     if self.browser_scut:
         self.searchButton.setToolTip('shortcut: {}'.format(
             self.browser_scut))
         self.browser_scut_key = QShortcut(QKeySequence(self.browser_scut),
                                           self)
         self.browser_scut_key.activated.connect(
             lambda: self.do_browser_search(extra_search=""))
     # don't also set Ctrl+t,a/gc("editor: show filterdialog to add single tag") for
     # self.tagselector: What if the user has already set them to the same etc. I'd have
     # to do a lot of checking
     self.addnl = gc("in tag lines dialog: insert additional line")
     if self.addnl:
         self.helpButton.setToolTip('shortcut: {}'.format(self.addnl))
         self.addnlscut = QShortcut(QKeySequence(self.addnl), self)
         self.addnlscut.activated.connect(
             lambda: self.maybe_add_line(force=True))
Example #50
0
 def __init__(
     self,
     mw,
     names=None,
     accept=None,
     title=None,
     help: HelpPageArgument = HelpPage.KEYBOARD_SHORTCUTS,
     current=None,
     cancel=True,
     parent=None,
     dyn=False,
     buttons=None,
     geomKey="default",
 ) -> None:
     QDialog.__init__(self, parent or mw)
     if buttons is None:
         buttons = []
     self.mw = mw
     self.form = aqt.forms.studydeck.Ui_Dialog()
     self.form.setupUi(self)
     self.form.filter.installEventFilter(self)
     self.cancel = cancel
     gui_hooks.state_did_reset.append(self.onReset)
     self.geomKey = "studyDeck-" + geomKey
     restoreGeom(self, self.geomKey)
     disable_help_button(self)
     if not cancel:
         self.form.buttonBox.removeButton(
             self.form.buttonBox.button(QDialogButtonBox.Cancel))
     if buttons:
         for b in buttons:
             self.form.buttonBox.addButton(b, QDialogButtonBox.ActionRole)
     else:
         b = QPushButton(tr(TR.ACTIONS_ADD))
         b.setShortcut(QKeySequence("Ctrl+N"))
         b.setToolTip(shortcut(tr(TR.DECKS_ADD_NEW_DECK_CTRLANDN)))
         self.form.buttonBox.addButton(b, QDialogButtonBox.ActionRole)
         qconnect(b.clicked, self.onAddDeck)
     if title:
         self.setWindowTitle(title)
     if not names:
         names = [
             d.name for d in self.mw.col.decks.all_names_and_ids(
                 include_filtered=dyn, skip_empty_default=True)
         ]
         self.nameFunc = None
         self.origNames = names
     else:
         self.nameFunc = names
         self.origNames = names()
     self.name = None
     self.ok = self.form.buttonBox.addButton(accept or tr(TR.DECKS_STUDY),
                                             QDialogButtonBox.AcceptRole)
     self.setWindowModality(Qt.WindowModal)
     qconnect(self.form.buttonBox.helpRequested, lambda: openHelp(help))
     qconnect(self.form.filter.textEdited, self.redraw)
     qconnect(self.form.list.itemDoubleClicked, self.accept)
     self.show()
     # redraw after show so position at center correct
     self.redraw("", current)
     self.exec_()
Example #51
0
 def restoreState(self):
     self.form.cmbMode.setCurrentIndex( self.mw.pm.profile.get('mcd.mode', 0) )
     #self.deck.setText( self.mw.pm.profile.get('mcd.deck') )
     self.tags.setText( self.mw.pm.profile.get('mcd.tags') )
     self.form.tbtWholeWords.setChecked( self.mw.pm.profile.get('mcd.whole_words', False) )
     restoreGeom(self, 'mcd.addMcds')
    def initUI(self):
        self.vlay = QVBoxLayout()
        self.input_line = PanelInputLine(self)
        self.list_box = QListWidget()
        for i in range(self.max_items):
            self.list_box.insertItem(i, '')
        self.vlay.addWidget(self.input_line)
        self.vlay.addWidget(self.list_box)

        self.button_del = QPushButton("Delete", self)
        self.button_del.clicked.connect(self.on_delete)
        delcut = gc("fuzzy_panel: shortcut delete")
        if delcut:
            self.button_del.setShortcut(QKeySequence(delcut))
            self.button_del.setToolTip(delcut)

        self.button_edit = QPushButton("Edit", self)
        self.button_edit.clicked.connect(self.on_edit)
        editcut = gc("fuzzy_panel: shortcut edit")
        if editcut:
            self.button_edit.setShortcut(QKeySequence(editcut))
            self.button_edit.setToolTip(editcut)

        self.button_ok = QPushButton("Overwrite", self)
        self.button_ok.clicked.connect(self.accept)
        self.button_ok.setToolTip("Ctrl+Return")
        self.button_ok.setShortcut(QKeySequence("Ctrl+Return"))
        # self.button_ok.setAutoDefault(True)

        self.append = False
        self.button_append = QPushButton("Append (default)", self)
        self.button_append.clicked.connect(self.set_append_and_accept)
        self.button_append.setToolTip("Return")

        self.button_cancel = QPushButton("Cancel", self)
        self.button_cancel.clicked.connect(self.reject)
        self.button_cancel.setToolTip("Esc")

        self.bottombar = QHBoxLayout()
        self.bottombar.addWidget(self.button_del)
        self.bottombar.addWidget(self.button_edit)
        self.bottombar.addStretch(1)
        self.bottombar.addWidget(self.button_ok)
        self.bottombar.addWidget(self.button_append)
        self.bottombar.addWidget(self.button_cancel)

        self.vlay.addLayout(self.bottombar)

        self.update_listbox()
        self.setLayout(self.vlay)
        self.resize(800, 350)
        restoreGeom(self, "debug_history")
        self.list_box.setAlternatingRowColors(True)

        # connections
        self.input_line.textChanged.connect(self.text_changed)
        self.input_line.returnPressed.connect(self.return_pressed)
        self.input_line.down_pressed.connect(self.down_pressed)
        self.input_line.up_pressed.connect(self.up_pressed)
        self.list_box.itemDoubleClicked.connect(self.item_doubleclicked)
        self.list_box.installEventFilter(self)
        self.input_line.setFocus()
Example #53
0
 def on_open(self) -> None:
     self.update_widgets()
     restoreGeom(self, self.geom_key)