Python aqt.mw() Examples

The following are 30 code examples of aqt.mw(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aqt , or try the search function .
Example #1
Source File: options_global.py    From cloze-overlapper with GNU Affero General Public License v3.0 6 votes vote down vote up
def renameFields(self):
        """Check for modified names and rename fields accordingly"""
        modified = False
        model = mw.col.models.byName(OLC_MODEL)
        flds = model['flds']
        for key, fnedit in self.fndict:
            if not fnedit.isModified():
                continue
            name = fnedit.text()
            oldname = config["synced"]['flds'][key]
            if name is None or not name.strip() or name == oldname:
                continue
            idx = mw.col.models.fieldNames(model).index(oldname)
            fld = flds[idx]
            if fld:
                # rename note type fields
                mw.col.models.renameField(model, fld, name)
                # update olcloze field-id <-> field-name assignment
                config["synced"]['flds'][key] = name
                modified = True
        return modified 
Example #2
Source File: gui.py    From MIA-Japanese-Add-on with GNU General Public License v3.0 6 votes vote down vote up
def saveConfiguration(self):
        sc, wc = self.saveSentenceWordConfig()
        ffs, la = self.saveNumberConfigOptions()
        ac, gc = self.saveAudioGraphsConfig()
        colors = self.saveHANOK()
        addmia, bo, autocss, ds, goh, gohb, kc, poc = self.saveBinaryOptions()
        newConf = {"ActiveFields" : self.saveActiveFields(), "Individual:Kana;DictForm;Pitch;Audio;Graphs" : wc, "Group:Kana;DictForm;Pitch;Audio;Graphs": sc,
         "FuriganaFontSize" : ffs, "LookAhead" : la, "Profiles" : self.saveProfilesConfig(),
         "AudioFields" : ac, "PitchGraphFields" :  gc, "ColorsHANOK" : colors, "AddMIAJapaneseTemplate": addmia, "BufferedOutput" :  bo,
         "AutoCssJsGeneration" : autocss, "DisplayShapes" : ds, "GraphOnHover" : goh, "GraphOnHoverBack" : gohb, "KatakanaConversion" : kc, "PlayAudioOnClick" : poc,
         "HistoricalConversion" : self.saveHistoricalConversion()

         }
        if self.addMIANoteTypeOnApply:
            self.MIAModel.addModels() 
        self.mw.addonManager.writeConfig(__name__, newConf)
        self.CSSJSHandler.injectWrapperElements()
        self.hide() 
Example #3
Source File: options.py    From FastWordQuery with GNU General Public License v3.0 6 votes vote down vote up
def show_models(self):
        '''
        show choose note type window
        '''
        edit = QPushButton(
            anki.lang._("Manage"), clicked=lambda: aqt.models.Models(mw, self))
        ret = StudyDeck(
            mw,
            names=lambda: sorted(mw.col.models.allNames()),
            accept=anki.lang._("Choose"),
            title=anki.lang._("Choose Note Type"),
            help="_notes",
            parent=self,
            buttons=[edit],
            cancel=True,
            geomKey="selectModel")
        if ret.name:
            model = mw.col.models.byName(ret.name)
            self.models_button.setText(
                u'%s [%s]' % (_('CHOOSE_NOTE_TYPES'), ret.name))
            return model 
Example #4
Source File: prepare.py    From WordQuery with GNU General Public License v3.0 6 votes vote down vote up
def setup_options_menu():
    # add options submenu to Tools menu
    action = QAction(app_icon, "WordQuery...", mw)
    action.triggered.connect(show_options)
    mw.form.menuTools.addAction(action)
    global have_setup
    have_setup = True


# def start_here():
#     # config.read()
#     if not have_setup:
#         setup_options_menu()
#         customize_addcards()
#         setup_browser_menu()
#         setup_context_menu()
#     # wquery.start_services()


# addHook("profileLoaded", start_here) 
Example #5
Source File: common.py    From FastWordQuery with GNU General Public License v3.0 6 votes vote down vote up
def show_options(browser=None, model_id=-1, callback=None, *args, **kwargs):
    '''open options window'''
    parent = mw if browser is None else browser
    config.read()
    opt_dialog = OptionsDialog(parent, u'Options', model_id)
    opt_dialog.activateWindow()
    opt_dialog.raise_()
    result = opt_dialog.exec_()
    opt_dialog.destroy()
    if result == QDialog.Accepted:
        if isinstance(callback, types.FunctionType):
            callback(*args, **kwargs)
    elif result == 1001:
        show_fm_dialog(parent)
    elif result == 1002:
        show_dm_dialog(parent) 
Example #6
Source File: miutils.py    From MIA-Japanese-Add-on with GNU General Public License v3.0 6 votes vote down vote up
def miInfo(text, parent=False, level = 'msg'):
    if level == 'wrn':
        title = "Japanese - Warning"
    elif level == 'not':
        title = "Japanese - Notice"
    elif level == 'err':
        title = "Japanese - Error"
    else:
        title = "Japanese"
    if parent is False:
        parent = aqt.mw.app.activeWindow() or aqt.mw
    icon = QIcon(join(addon_path, 'icons', 'mia.png'))
    mb = QMessageBox(parent)
    mb.setText(text)
    mb.setWindowIcon(icon)
    mb.setWindowTitle(title)
    b = mb.addButton(QMessageBox.Ok)
    b.setDefault(True)

    return mb.exec_() 
Example #7
Source File: overview_deck_tooltip.py    From anki-addons-misc with GNU Affero General Public License v3.0 6 votes vote down vote up
def build_html(self):

        self.add_row("Name:", self.deck["name"])
        self.add_row("Options", self.col.decks.confForDid(self.did)["name"])

        (card_count, note_count) = mw.col.db.first("""
select count(id), count(distinct nid) from cards
where did in %s """ % self.deck_limit)
        self.add_row("Total notes:", note_count)
        self.add_row("Total cards:", card_count)

        suspended_count = mw.col.db.scalar("""
select count(id)from cards
where queue = -1 and did in %s """ % self.deck_limit)
        self.add_row("Suspended:", suspended_count)
        self.add_row("Did:", self.did)
        self.add_row("Today:", self.todayStats())

        #todo
        """
        Due tomorrow,next etc
        If you studied every day:	6.1 minutes/day
Average answer time:	17.5s (3 cards/minute)
        """ 
Example #8
Source File: stats.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 6 votes vote down vote up
def getSortedByInterval(decks, limit, pinned, sortOrder):
    if not "-1" in decks:
        deckQ = "(%s)" % ",".join(decks)
    else:
        deckQ = ""
    if deckQ:
        res = mw.col.db.all("select notes.id, flds, tags, did, cards.nid, notes.mid FROM cards left join notes on cards.nid = notes.id where did in %s and reps > 0 group by cards.nid order by ivl %s limit %s" % (
            deckQ, sortOrder, limit))
    else:
        res = mw.col.db.all("select notes.id, flds, tags, did, cards.nid, notes.mid FROM cards left join notes on cards.nid = notes.id where reps > 0 group by cards.nid order by ivl %s limit %s" % (
        sortOrder, limit))
    rList = []
    for r in res:
        if not str(r[0]) in pinned:
           #. rList.append((r[1], r[2], r[3], r[0], 1, r[5]))
           rList.append(IndexNote((r[0], r[1], r[2], r[3], r[1], -1, r[4], "")))
    return rList 
Example #9
Source File: overview_deck_tooltip.py    From anki-addons-misc with GNU Affero General Public License v3.0 6 votes vote down vote up
def _generate_jquery_scripts():
    """
    This generates a js function for each deck's row based on did
    I am guessing that only one function is needed, but I couldn't figure out how to do it
    Somehow the render function needs to keep a reference to the outer context this.id
    I don't know js or jquery well enough to do that.
    If you know, please let me know.
    """
    tip_script = "    $(function(){"
    template = """
    $('tr#%(id)s a').miniTip({
        content: 'Loading...', offset: 1, delay: 500, maxW: '500px',
		render: function(tt) {
        $('#miniTip_c').html(py_deck_inf.deck_information_for(%(id)s) );}});
        """
    for did in mw.col.decks.allIds():
        tip_script += (template % dict(id=did))
    tip_script += """
        });
        """
    return tip_script 
Example #10
Source File: options.py    From review-heatmap with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, config, mw, parent=None, **kwargs):
        # Mediator methods defined in mapped_widgets might need access to
        # certain instance attributes. As super().__init__ calls these
        # mediator methods it is important that we set the attributes
        # beforehand:
        self.parent = parent or mw
        self.mw = mw
        super(RevHmOptions, self).__init__(
            self._mapped_widgets,
            config,
            form_module=qtform_options,
            parent=self.parent,
            **kwargs
        )
        # Instance methods that modify the initialized UI should either be
        # called from self._setupUI or from here

    # UI adjustments 
Example #11
Source File: common.py    From FastWordQuery with GNU General Public License v3.0 6 votes vote down vote up
def show_options(browser = None, model_id = -1, callback = None, *args, **kwargs):
    '''open options window'''
    parent = mw if browser is None else browser
    config.read()
    opt_dialog = OptionsDialog(parent, u'Options', model_id)
    opt_dialog.activateWindow()
    opt_dialog.raise_()
    result = opt_dialog.exec_()
    opt_dialog.destroy()
    if result == QDialog.Accepted:
        if isinstance(callback, types.FunctionType):
            callback(*args, **kwargs)
    elif result == 1001:
        show_fm_dialog(parent)
    elif result == 1002:
        show_dm_dialog(parent) 
Example #12
Source File: __init__.py    From awesometts-anki-addon with GNU General Public License v3.0 6 votes vote down vote up
def window_shortcuts():
    """Enables shortcuts to launch windows."""

    def on_sequence_change(new_config):
        """Update sequences on configuration changes."""
        for key, sequence in sequences.items():
            new_sequence = QKeySequence(new_config['launch_' + key] or None)
            sequence.swap(new_sequence)

        try:
            aqt.mw.form.menuTools.findChild(gui.Action). \
                setShortcut(sequences['configurator'])
        except AttributeError:  # we do not have a config menu
            pass

    on_sequence_change(config)  # set config menu if created before we ran
    config.bind(['launch_' + key for key in sequences.keys()],
                on_sequence_change) 
Example #13
Source File: __init__.py    From awesometts-anki-addon with GNU General Public License v3.0 6 votes vote down vote up
def config_menu():
    """
    Adds a menu item to the Tools menu in Anki's main window for
    launching the configuration dialog.
    """

    gui.Action(
        target=Bundle(
            constructor=gui.Configurator,
            args=(),
            kwargs=dict(addon=addon, sul_compiler=to.substitution_compiled,
                        alerts=aqt.utils.showWarning,
                        ask=aqt.utils.getText,
                        parent=aqt.mw),
        ),
        text="Awesome&TTS...",
        sequence=sequences['configurator'],
        parent=aqt.mw.form.menuTools,
    ) 
Example #14
Source File: editor.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, parent, note_id = None, add_only = False, read_note_id = None, tag_prefill = None, source_prefill = None, text_prefill = None, title_prefill = None, prio_prefill = None):

        QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowMinimizeButtonHint)

        self.mw             = aqt.mw
        self.parent         = parent

        self.note_id        = note_id
        self.note           = None
        self.add_only       = add_only
        self.read_note_id   = read_note_id
        self.tag_prefill    = tag_prefill
        self.source_prefill = source_prefill
        self.text_prefill   = text_prefill
        self.title_prefill  = title_prefill
        self.prio_prefill   = prio_prefill
        self.dark_mode_used = state.night_mode

        if self.note_id is not None:
            self.note = get_note(note_id)
        #self.mw.setupDialogGC(self)
        #self.setWindowModality(Qt.WindowModal)
        #self.setAttribute(Qt.WA_DeleteOnClose)
        self.setup_ui() 
Example #15
Source File: editor.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, mw, note):

        QDialog.__init__(self, None, Qt.Window)
        mw.setupDialogGC(self)

        self.mw         = mw
        self.form       = aqt.forms.editcurrent.Ui_Dialog()

        self.form.setupUi(self)
        self.form.buttonBox.button(QDialogButtonBox.Close).setShortcut(QKeySequence("Ctrl+Return"))
        self.editor     = aqt.editor.Editor(self.mw, self.form.fieldsArea, self)

        self.setWindowTitle(_("Edit Note"))
        self.setMinimumHeight(400)
        self.setMinimumWidth(500)
        self.resize(500, 850)
        self.editor.setNote(note, focusTo=0)
        addHook("reset", self.onReset)
        self.mw.requireReset()
        self.show()
        self.mw.progress.timer(100, lambda: self.editor.web.setFocus(), False) 
Example #16
Source File: miutils.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 6 votes vote down vote up
def miInfo(text, parent=False, level = 'msg', day = True):
    if level == 'wrn':
        title = "Dictionary Warning"
    elif level == 'not':
        title = "Dictionary Notice"
    elif level == 'err':
        title = "Dictionary Error"
    else:
        title = "Dictionary"
    if parent is False:
        parent = aqt.mw.app.activeWindow() or aqt.mw
    icon = QIcon(join(addon_path, 'icons', 'mia.png'))
    mb = QMessageBox(parent)
    if not day:
        mb.setStyleSheet(" QMessageBox {background-color: #272828;}")
    mb.setText(text)
    mb.setWindowIcon(icon)
    mb.setWindowTitle(title)
    b = mb.addButton(QMessageBox.Ok)
    b.setFixedSize(100, 30)
    b.setDefault(True)

    return mb.exec_() 
Example #17
Source File: addDictGroup.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
def getConfig(self):
        return self.mw.addonManager.getConfig(__name__) 
Example #18
Source File: pdf_extract.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, parent, current_page, pages_total, note):

        QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)

        self.extract_start  = None
        self.extract_end    = None
        self.current_page   = current_page
        self.pages_total    = pages_total
        self.note           = note
        self.prio_default   = get_priority(note.id)
        self.mw             = aqt.mw
        self.parent         = parent
        self.setup_ui()
        self.setWindowTitle("Extract") 
Example #19
Source File: addDictGroup.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
def saveDictGroup(self):
        newConfig = self.getConfig()
        gn = self.groupName.text()
        if gn  == '':
            miInfo('The dictionary group must have a name.', level='wrn')
            return
        curGroups = newConfig['DictionaryGroups']
        if self.new and gn in curGroups:
            miInfo('A new dictionary group must have a unique name.', level='wrn')
            return
        if self.fontFromDropdown.isChecked():
            fontName = self.fontDropDown.currentText()
            customFont = False

        else:
            fontName = self.fontFileName.text()
            if fontName == 'None Selected':
                miInfo('You must select a file if you will be using a font from a file.', level='wrn')
                return
            customFont = True
            if not exists(join(self.settings.addonPath,'user_files', 'fonts', fontName)):
                if not self.moveFontToFolder(self.fontToMove):
                    miInfo('The font file was unable to be loaded, please ensure your file exists in the target folder and try again.', level='err')
                    return
        selectedDicts = self.getSelectedDictionaries(True)
        if len(selectedDicts) < 1:
            miInfo('You must select at least one dictionary.', level='wrn')
            return
        dictGroup = {
        'dictionaries' : selectedDicts,
        'customFont' : customFont,
        'font' : fontName
        }
        curGroups[gn] = dictGroup
        self.mw.addonManager.writeConfig(__name__, newConfig)
        self.settings.loadTemplateTable()
        self.settings.loadGroupTable()
        self.hide() 
Example #20
Source File: addDictGroup.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, mw, parent = None, dictionaries = [], group = False, groupName = False):
        super(DictGroupEditor, self).__init__(parent, Qt.Window)
        self.mw = mw
        self.settings = parent
        self.setWindowTitle("Add Dictionary Group")
        self.groupName = QLineEdit()
        self.fontFromDropdown = QRadioButton()
        self.fontFromFile = QRadioButton()
        self.fontDropDown = self.getFontCB()
        self.fontFileName = QLabel('None Selected')
        self.browseFontFile = QPushButton('Browse')
        self.dictionaries = self.setupDictionaries()
        self.selectAll = QPushButton('Select All')
        self.removeAll = QPushButton('Remove All')
        self.cancelButton = QPushButton('Cancel')
        self.saveButton = QPushButton('Save')
        self.layout = QVBoxLayout()
        self.setupLayout()
        self.fontToMove = False
        self.dictList = dictionaries
        self.loadDictionaries(dictionaries)
        self.new = True
        if group:
            self.new = False
            self.loadGroupEditor(group, groupName)
        else:
            self.clearGroupEditor()
        self.initHandlers()
        self.initTooltips()
        self.show() 
Example #21
Source File: worker.py    From FastWordQuery with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.workers = []
        self.queue = Queue()
        self.mutex = QMutex()
        self.progress = ProgressWindow(mw)
        self.total = 0
        self.counter = 0
        self.fails = 0
        self.fields = 0
        self.skips = 0
        self.missed_css = list()
        self.flush = True
        self.query_fields = None 
Example #22
Source File: url_import.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, parent, show_schedule=True):
        QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)

        self.chosen_url     = None
        self._chosen_name   = None
        self.show_schedule  = show_schedule
        self.queue_schedule = 0
        self.mw             = aqt.mw
        self.parent         = parent

        self.setup_ui()
        self.setWindowTitle("URL to PDF") 
Example #23
Source File: common_context_search.py    From anki-addons-misc with GNU Affero General Public License v3.0 5 votes vote down vote up
def lookupLocal(text):
    browser = aqt.dialogs.open("Browser", aqt.mw)
    browser.form.searchEdit.lineEdit().setText('"{}"'.format(text))
    if ANKI20:
        browser.onSearch()
    else:
        browser.onSearchActivated()

# Online search 
Example #24
Source File: schedule_dialog.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, note, parent):
        QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)

        self.mw     = aqt.mw
        self.parent = parent
        self.note   = note

        self.setup_ui()
        self.setWindowTitle("Edit Schedule") 
Example #25
Source File: editor.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def openEditor(mw, nid):
    note = mw.col.getNote(nid)
    dialog = EditDialog(mw, note) 
Example #26
Source File: editor.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def reopen(self, mw):
        tooltip("Please finish editing the existing card first.")
        self.onReset() 
Example #27
Source File: overview_deck_tooltip.py    From anki-addons-misc with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, mw, did):
        object.__init__(self)
        self.mw = mw
        self.col = self.mw.col
        self.did = did
        self.deck = self.col.decks.get(did)
        self.deck_children = self.col.decks.children(did)
        self.deck_limit = ids2str([child_did for (child_name, child_did) in self.deck_children] + [self.did])
        self.html = '' 
Example #28
Source File: overview_deck_tooltip.py    From anki-addons-misc with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_tooltip_html(self, did):
        return DeckReport(mw, did).generate_html() 
Example #29
Source File: about.py    From incremental-reading with ISC License 5 votes vote down vote up
def showAbout():
    dialog = QDialog(mw)

    label = QLabel()
    label.setStyleSheet('QLabel { font-size: 14px; }')
    names = [
        'Tiago Barroso',
        'Frank Kmiec',
        'Aleksej',
        'Christian Weiß',
        'Timothée Chauvin',
    ]
    text = '''
<div style="font-weight: bold">Incremental Reading v%s</div>
<div>Joseph Lorimer &lt;joseph@lorimer.me&gt;</div>
<div>Contributors: %s</div>
<div>Website: <a href="%s">%s</a></div>
''' % (
        __version__,
        ', '.join(names),
        IR_GITHUB_URL,
        IR_GITHUB_URL,
    )
    label.setText(text)

    buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
    buttonBox.accepted.connect(dialog.accept)

    layout = QVBoxLayout()
    layout.addWidget(label)
    layout.addWidget(buttonBox)

    dialog.setLayout(layout)
    dialog.setWindowTitle('About')
    dialog.exec_() 
Example #30
Source File: editor.py    From anki-search-inside-add-card with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_model(self, priority_list):
        model = PriorityListModel(self)

        config = mw.addonManager.getConfig(__name__)
        if self.parent.dark_mode_used:
            tag_bg                  = config["styles.night.tagBackgroundColor"]
            tag_fg                  = config["styles.night.tagForegroundColor"]
        else:
            tag_bg                  = config["styles.tagBackgroundColor"]
            tag_fg                  = config["styles.tagForegroundColor"]

        for c, pitem in enumerate(priority_list):

            # build display text
            text = pitem.title if pitem.title is not None and len(pitem.title.strip()) > 0 else "Untitled"
            text = "<b>%s</b>" % text

            tags = pitem.tags
            if tags is not None and len(tags.strip()) > 0:
                tag_sep = "&nbsp;</span> <span style='color: %s; background-color: %s; margin-right: 5px; border-radius: 5px;'>&nbsp;" % (tag_fg, tag_bg)
                tags = "<span style='color: %s; background-color: %s; margin-right: 5px; border-radius: 5px;'>&nbsp;%s&nbsp;</span>" % (tag_fg, tag_bg, tag_sep.join([t for t in tags.split(" ") if len(t) > 0]))

            item = QStandardItem(text)
            item.setData(QVariant(pitem.id))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
            model.setItem(c, 0, item)
            titem = QStandardItem(tags)
            titem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
            model.setItem(c, 1, titem)
            oitem = QStandardItem()
            oitem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
            model.setItem(c, 2, oitem)

        model.setHeaderData(0, Qt.Horizontal, "Title")
        model.setHeaderData(1, Qt.Horizontal, "Tags")
        model.setHeaderData(2, Qt.Horizontal, "Actions")
        return model