def add_time_base(t=1):
    if Config.play:
        stop()
    if t == 1:
        at = utils.getText("Add additional time for questions and answers")
    elif t == 2:
        at = utils.getText("Add additional time for questions")
    else:
        at = utils.getText("Add additional time for answers")
    if at is not None and len(at) > 0:
        try:
            at = float(at[0])
        except:
            utils.showInfo('You must enter a positive number between 0 and 20!')
            return
    else:
        return
    if at >= 0 and at <= 20:
        if t == 1:
            Config.addition_time = at
            utils.showInfo('Set additional time for questions and answers')
        elif t == 2:
            Config.addition_time_question = at
            utils.showInfo('Set additional time for questions')
        else:
            Config.addition_time_answer = at
            utils.showInfo('Set additional time for answers')
        Config.add_time = True
    else:
        utils.showInfo('Invalid additional time. Time value must be in the range 0 to 20')
Exemple #2
0
 def __init__(self):
     if not mw.col.conf.get(SETTING_TOKEN, False):
         # First run of the Plugin we did not save the access key yet
         client = EvernoteClient(
             consumer_key='scriptkiddi-2682',
             consumer_secret='965f1873e4df583c',
             sandbox=False
         )
         request_token = client.get_request_token('http://brunomart.in/anknotes/index.html')
         url = client.get_authorize_url(request_token)
         showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
         openLink(url)
         oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
         secret_key = getText(prompt="protect your value with a password, it will be asked each time you import your notes")[0]
         auth_token = client.get_access_token(
             request_token.get('oauth_token'),
             request_token.get('oauth_token_secret'),
             oauth_verifier)
         mw.col.conf[SETTING_TOKEN] = encode(secret_key, auth_token)
     else:
         secret_key = getText(prompt="password")[0]
         auth_token_encoded = mw.col.conf.get(SETTING_TOKEN, False)
         auth_token = decode(secret_key, auth_token_encoded)
     self.token = auth_token
     self.client = EvernoteClient(token=auth_token, sandbox=False)
     self.noteStore = self.client.get_note_store()
Exemple #3
0
def switch(did):
    (confName, __
     ) = getText("What should be the option of the descendant of this deck ?")
    (depthMin, __) = getText(
        "Which is the minimal depth to which change must be done (0 is current depth)",
        default="1")
    depthMin = int(depthMin)
    (depthMax, __) = getText(
        "Which is the maximal depth to which change must be done (0 is current depth)",
        default="99")
    depthMin = int(depthMin)
    col = mw.col
    decks = col.decks
    for conf in decks.allConf():
        if conf["name"] == confName:
            break
    if not conf["name"] == confName:
        tooltip("This option does not exists.")
        return
    for (name, did_) in decks.children(did):
        depth = len(re.findall("::", name)) - len(
            re.findall("::",
                       decks.get(did)["name"]))
        if depthMin <= depth <= depthMax:
            deck = decks.get(did_)
            deck["conf"] = conf["id"]
    col.flush()
Exemple #4
0
def changeLaTeX(latexPre=None, latexPost=None):
    models = list(mw.col.models.models.values())
    if not test(latexPre):
        if 'latexPre' in mw.col.conf:
            latexPre = mw.col.conf['latexPre']
    if not test(latexPre):
        model = models[0]
        if 'latexPre' in model:
            latexPre = model['latexPre']

    (latexPre, ret) = getText("LaTeX header", default=latexPre)
    if test(latexPre) and ret:
        mw.col.conf['latexPre'] = latexPre
        for model in models:
            model['latexPre'] = latexPre

    models = list(mw.col.models.models.values())
    if not test(latexPost):
        if 'latexPost' in mw.col.conf:
            latexPost = mw.col.conf['latexPost']
    if not test(latexPost):
        model = models[0]
        if 'latexPost' in model:
            latexPost = model['latexPost']

    (latexPost, ret_) = getText("LaTeX footer", default=latexPost)
    if test(latexPost) and ret_:
        mw.col.conf['latexPost'] = latexPost
        for model in models:
            model['latexPost'] = latexPost

    if ret or ret_:
        mw.col.flush()
Exemple #5
0
def main():
    start = int(getText('Enter beginning of frequency range: ')[0])
    end = int(getText('Enter end of frequency range: ')[0])
    if end > start and end != 0:
        word_list = getFreqList(range(start, end))

    # Iterate list and add notes
    for word in word_list:
        entry = createEntry(word)
        if entry:
            addNote(subDeck, model, entry)
    showInfo("Done!")
Exemple #6
0
def find_deleted_notes(automated=False):
    if not automated:
        showInfo("""In order for this to work, you must create a 'Table of Contents' Note using the Evernote desktop application. Include all notes that you want to sync with Anki.

Export this note to the following path:
<b>%s</b>

Press Okay to save and close your Anki collection, open the command-line deleted notes detection tool, and then re-open your Anki collection.

Once the command line tool is done running, you will get a summary of the results, and will be prompted to delete Anki Orphan Notes or download Missing Evernote Notes""".replace(
            '\n', '\n<br />') % FILES.USER.TABLE_OF_CONTENTS_ENEX, richText=True)
    from anknotes import find_deleted_notes
    returnedData = find_deleted_notes.do_find_deleted_notes()
    if returnedData is False:
        showInfo("An error occurred while executing the script. Please ensure you created the TOC note and saved it as instructed in the previous dialog.")
        return
    lines = returnedData['Summary']
    info = tableify_lines(lines, '#|Type|Info')
    # info = '<table><tr class=tr0><td class=t1>#</td><td class=t2>Type</td><td class=t3></td></tr>%s</table>' % '\n'.join(lines)
    # info = info.replace('\n', '\n<BR>').replace('  ', '&nbsp; &nbsp; ')
    anknotes_dels = returnedData['AnknotesOrphans']
    anknotes_dels_count = len(anknotes_dels)
    anki_dels = returnedData['AnkiOrphans']
    anki_dels_count = len(anki_dels)
    missing_evernote_notes = returnedData['MissingEvernoteNotes']
    missing_evernote_notes_count = len(missing_evernote_notes)
    showInfo(info, richText=True, minWidth=600)
    db_changed = False
    if anknotes_dels_count > 0:
        correct_code = 'ANKNOTES_DEL_%d' % anknotes_dels_count
        code = getText("Please enter code '%s' to delete your orphan Anknotes DB note(s)" % correct_code)[0]
        if code == correct_code:
            ankDB().executemany("DELETE FROM {n} WHERE guid = ?", [[x] for x in anknotes_dels])
            delete_anki_notes_and_cards_by_guid(anknotes_dels)
            db_changed = True
            show_tooltip("Deleted all %d Orphan Anknotes DB Notes" % anknotes_dels_count, 5, 3)
    if anki_dels_count > 0:
        correct_code = 'ANKI_DEL_%d' % anki_dels_count
        code = getText("Please enter code '%s' to delete your orphan Anki note(s)" % correct_code)[0]
        if code == correct_code:
            delete_anki_notes_and_cards_by_guid(anki_dels)
            db_changed = True
            show_tooltip("Deleted all %d Orphan Anki Notes" % anki_dels_count, 5, 6)
    if db_changed:
        ankDB().commit()
    if missing_evernote_notes_count > 0:
        text = "Would you like to import %d missing Evernote Notes?<BR><BR><a href='%s'>Click to view results</a>" % (
                        missing_evernote_notes_count,
                        convert_filename_to_local_link(get_log_full_path(FILES.LOGS.FDN.UNIMPORTED_EVERNOTE_NOTES, filter_disabled=False)))
        if showInfo(text, cancelButton=True, richText=True):
            import_from_evernote_manual_metadata(missing_evernote_notes)
def showTagsInfoHighlight(self, cids):
    default = getUserOption("default search")
    highlights, ret = getText("Which tags to highlight? (space separated)",
                              default=default)
    if not ret:
        return
    default_percent = getUserOption("default percent to box")
    highlights_percent, ret = getText("Highlights values above x %",
                                      default=str(default_percent))
    if not ret:
        return
    if getUserOption("update default"):
        setUserOption("default search", highlights)
    showTagsInfo(self, cids, highlights, highlights_percent)
Exemple #8
0
    def onProfilePass(self):
        pw, ret = getText(_("""\
Lock account with password, or leave blank:"""))
        if not ret:
            return
        if not pw:
            self.prof['key'] = None
            return
        pw2, ret = getText(_("Confirm password:"******"Passwords didn't match"))
        self.prof['key'] = self.mw.pm._pwhash(pw)
Exemple #9
0
    def onProfilePass(self):
        pw, ret = getText(_("""\
Lock account with password, or leave blank:"""))
        if not ret:
            return
        if not pw:
            self.prof['key'] = None
            return
        pw2, ret = getText(_("Confirm password:"******"Passwords didn't match"))
        self.prof['key'] = self.mw.pm._pwhash(pw)
Exemple #10
0
 def onRename(self) -> None:
     nt = self.current_notetype()
     txt = getText(tr.actions_new_name(), default=nt["name"])
     name = txt[0].replace('"', "")
     if txt[1] and name:
         nt["name"] = name
         self.saveAndRefresh(nt)
Exemple #11
0
def getDelayWithResponse():
    (s, r) = getText(
        "How many days would you like to postpone your cards? (negative number to subtract days)"
    )
    if r:
        return (RepresentsInt(s), r)
    return (None, r)
Exemple #12
0
 def setup_client(self):
     auth_token = SETTINGS.EVERNOTE.AUTH_TOKEN.fetch()
     if not auth_token:
         # First run of the Plugin we did not save the access key yet
         secrets = {
             'holycrepe': '36f46ea5dec83d4a',
             'scriptkiddi-2682': '965f1873e4df583c'
         }
         client = EvernoteClient(
             consumer_key=EVERNOTE.API.CONSUMER_KEY,
             consumer_secret=secrets[EVERNOTE.API.CONSUMER_KEY],
             sandbox=EVERNOTE.API.IS_SANDBOXED)
         request_token = client.get_request_token(
             'https://fap-studios.de/anknotes/index.html')
         url = client.get_authorize_url(request_token)
         showInfo(
             "We will open a Evernote Tab in your browser so you can allow access to your account"
         )
         openLink(url)
         oauth_verifier = getText(
             prompt=
             "Please copy the code that showed up, after allowing access, in here"
         )[0]
         auth_token = client.get_access_token(
             request_token.get('oauth_token'),
             request_token.get('oauth_token_secret'), oauth_verifier)
         SETTINGS.EVERNOTE.AUTH_TOKEN.save(auth_token)
     else:
         client = EvernoteClient(token=auth_token,
                                 sandbox=EVERNOTE.API.IS_SANDBOXED)
     self.token = auth_token
     self.client = client
     log("Set up Evernote Client", 'client')
Exemple #13
0
 def onRename(self) -> None:
     nt = self.current_notetype()
     txt = getText(_("New name:"), default=nt["name"])
     name = txt[0].strip('"')
     if txt[1] and name:
         nt["name"] = name
         self.saveAndRefresh(nt)
Exemple #14
0
 def onAdd(self) -> None:
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(tr(TR.ACTIONS_NAME), default=m["name"])[0].replace('"', "")
         if txt:
             m["name"] = txt
         self.saveAndRefresh(m)
    def __init__(self, query_field_names, target_field_name, locale):
        """Initialiser.

        Args:
            query_field_name (str): the name of the query field.
            target_field_name (str): the name of the target field.
            langauge (str): Either the English name of a language, e.g.
                "English", "Japanese", "Portuguese", "French (France)"
                or a language code, e.g. "en-gb", "ja-jp"

        Raises:
            ValueError if the language is not supported.
        """
        AnySourceFieldUpdater.__init__(self, query_field_names, target_field_name)
        self.locale = locale

        parser = ConfigParser()
        section = 'cognitive services'
        option = 'bing search api key'
        if parser.read(CONFIG_FILE) and parser.has_option(section, option):
            self.api_key = parser.get(section, option)
        else:
            prompt = 'Please input API key for the Bing Search API.'
            self.api_key = getText(prompt)[0].encode('utf-8')
            if not parser.has_section(section):
                parser.add_section(section)
            parser.set(section, option, self.api_key)
            with open(CONFIG_FILE, 'w') as f:
                parser.write(f)
Exemple #16
0
def set_due_date_dialog(
    *,
    mw: aqt.AnkiQt,
    parent: QWidget,
    card_ids: List[int],
    config_key: Optional[Config.String.Key.V],
) -> None:
    if not card_ids:
        return

    default_text = (mw.col.get_config_string(config_key)
                    if config_key is not None else "")
    prompt = "\n".join([
        tr(TR.SCHEDULING_SET_DUE_DATE_PROMPT, cards=len(card_ids)),
        tr(TR.SCHEDULING_SET_DUE_DATE_PROMPT_HINT),
    ])
    (days, success) = getText(
        prompt=prompt,
        parent=parent,
        default=default_text,
        title=tr(TR.ACTIONS_SET_DUE_DATE),
    )
    if not success or not days.strip():
        return

    mw.perform_op(
        lambda: mw.col.sched.set_due_date(card_ids, days, config_key),
        success=lambda _: tooltip(
            tr(TR.SCHEDULING_SET_DUE_DATE_DONE, cards=len(card_ids)),
            parent=parent,
        ),
    )
Exemple #17
0
def answerCard(self, card, ease):
    if ease == 1 and remem.conf.get("reschedule_siblings_on_again", False):
        if card.ivl >= 21: return  #avoid Lapse new ivl option
        if card.id in mw.reviewer._answeredIds: return

        conf = mw.col.decks.confForDid(card.did)
        if not card.odid or conf['resched']:
            bound = card.ivl + remem.conf.get("sibling_boundary", 365)
            cids = [
                i for i in mw.col.db.list(
                    "select id from cards where nid=? and type=2 and queue=2 and id!=? and ivl > ?",
                    card.nid, card.id, bound)
            ]
            L = len(cids)
            if L > 0:
                am = ok = remem.conf.get("automatic_mode", False)
                if not am:
                    t, ok = getText(
                        "You have %d sibling(s) out of bound, reschedule them?"
                        % L,
                        default=str(cids))
                if am or ok:
                    dMin = remem.conf.get("sibling_days_min", 7)
                    dMax = remem.conf.get("sibling_days_max", 20)
                    log = remem.conf.get("revlog_rescheduled", True)
                    customReschedCards(cids, dMin, dMax, log)
Exemple #18
0
 def onAdd(self) -> None:
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(_("Name:"), default=m["name"])[0]
         if txt:
             m["name"] = txt
         self.saveAndRefresh(m)
    def __init__(self):

        if USE_APPLESCRIPT is False:

            if not mw.col.conf.get(SETTING_TOKEN, False):
                # First run of the Plugin we did not save the access key yet
                client = EvernoteClient(
                    consumer_key='scriptkiddi-2682',
                    consumer_secret='965f1873e4df583c',
                    sandbox=False
                )
                request_token = client.get_request_token('https://fap-studios.de/anknotes/index.html')
                url = client.get_authorize_url(request_token)
                showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
                openLink(url)
                oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
                auth_token = client.get_access_token(
                    request_token.get('oauth_token'),
                    request_token.get('oauth_token_secret'),
                    oauth_verifier)
                mw.col.conf[SETTING_TOKEN] = auth_token
            else:
                auth_token = mw.col.conf.get(SETTING_TOKEN, False)

            self.token = auth_token
            self.client = EvernoteClient(token=auth_token, sandbox=False)
            self.noteStore = self.client.get_note_store()
Exemple #20
0
    def onDelimiter(self) -> None:

        # Open a modal dialog to enter an delimiter
        # Todo/Idea Constrain the maximum width, so it doesnt take up that much screen space
        delim, ok = getText(
            tr(TR.IMPORTING_BY_DEFAULT_ANKI_WILL_DETECT_THE),
            self,
            help=HelpPage.IMPORTING,
        )

        # If the modal dialog has been confirmed, update the delimiter
        if ok:
            # Check if the entered value is valid and if not fallback to default
            # at the moment every single character entry as well as '\t' is valid

            delim = delim if len(delim) > 0 else self._DEFAULT_FILE_DELIMITER
            delim = delim.replace("\\t", "\t")  # un-escape it
            if len(delim) > 1:
                showWarning(
                    tr(TR.
                       IMPORTING_MULTICHARACTER_SEPARATORS_ARE_NOT_SUPPORTED_PLEASE
                       ))
                return
            self.hideMapping()

            def updateDelim() -> None:
                self.importer.delimiter = delim
                self.importer.updateDelimiter()
                self.updateDelimiterButtonText()

            self.showMapping(hook=updateDelim)

        else:
            # If the operation has been canceled, do not do anything
            pass
Exemple #21
0
    def __init__(self):

        if USE_APPLESCRIPT is False:

            if not mw.col.conf.get(SETTING_TOKEN, False):
                # First run of the Plugin we did not save the access key yet
                client = EvernoteClient(consumer_key='scriptkiddi-2682',
                                        consumer_secret='965f1873e4df583c',
                                        sandbox=False)
                request_token = client.get_request_token(
                    'https://fap-studios.de/anknotes/index.html')
                url = client.get_authorize_url(request_token)
                showInfo(
                    "We will open a Evernote Tab in your browser so you can allow access to your account"
                )
                openLink(url)
                oauth_verifier = getText(
                    prompt=
                    "Please copy the code that showed up, after allowing access, in here"
                )[0]
                auth_token = client.get_access_token(
                    request_token.get('oauth_token'),
                    request_token.get('oauth_token_secret'), oauth_verifier)
                mw.col.conf[SETTING_TOKEN] = auth_token
            else:
                auth_token = mw.col.conf.get(SETTING_TOKEN, False)

            self.token = auth_token
            self.client = EvernoteClient(token=auth_token, sandbox=False)
            self.noteStore = self.client.get_note_store()
Exemple #22
0
    def onDelimiter(self) -> None:

        # Open a modal dialog to enter an delimiter
        # Todo/Idea Constrain the maximum width, so it doesnt take up that much screen space
        delim, ok = getText(
            tr.importing_by_default_anki_will_detect_the(),
            self,
            help=HelpPage.IMPORTING,
        )

        # If the modal dialog has been confirmed, update the delimiter
        if ok:
            # Check if the entered value is valid and if not fallback to default
            # at the moment every single character entry as well as '\t' is valid

            delim = delim if len(delim) > 0 else self._DEFAULT_FILE_DELIMITER
            delim = delim.replace("\\t", "\t")  # un-escape it
            if len(delim) > 1:
                showWarning(
                    tr.
                    importing_multicharacter_separators_are_not_supported_please(
                    ))
                return
            self.hideMapping()

            def updateDelim() -> None:
                self.importer.delimiter = delim
                self.importer.updateDelimiter()
                self.updateDelimiterButtonText()

            self.showMapping(hook=updateDelim)

        else:
            # If the operation has been canceled, do not do anything
            pass
Exemple #23
0
 def onRename(self):
     """Ask the user for a new name for the model. Save it"""
     txt = getText(_("New name:"), default=self.model['name'])
     if txt[1] and txt[0]:
         self.model['name'] = txt[0]
         self.mm.save(self.model)
     self.updateModelsList()
Exemple #24
0
 def onRename(self) -> None:
     nt = self.current_notetype()
     txt = getText(tr(TR.ACTIONS_NEW_NAME), default=nt["name"])
     name = txt[0].replace('"', "")
     if txt[1] and name:
         nt["name"] = name
         self.saveAndRefresh(nt)
Exemple #25
0
def set_due_date_dialog(
    *,
    parent: QWidget,
    card_ids: Sequence[CardId],
    config_key: Optional[Config.String.Key.V],
) -> Optional[CollectionOp[OpChanges]]:
    assert aqt.mw
    if not card_ids:
        return None

    default_text = (aqt.mw.col.get_config_string(config_key)
                    if config_key is not None else "")
    prompt = "\n".join([
        tr.scheduling_set_due_date_prompt(cards=len(card_ids)),
        tr.scheduling_set_due_date_prompt_hint(),
    ])
    (days, success) = getText(
        prompt=prompt,
        parent=parent,
        default=default_text,
        title=tr.actions_set_due_date(),
    )
    if not success or not days.strip():
        return None
    else:
        return CollectionOp(
            parent, lambda col: col.sched.set_due_date(
                card_ids, days, config_key)).success(lambda _: tooltip(
                    tr.scheduling_set_due_date_done(cards=len(card_ids)),
                    parent=parent,
                ))
Exemple #26
0
    def importWebpage(self, url=None):
        if not url:
            url, accepted = getText('Enter URL:', title='Import Webpage')
        else:
            accepted = True

        if not url or not accepted:
            return

        if not urlsplit(url).scheme:
            url = 'http://' + url

        try:
            webpage = self._fetchWebpage(url)
        except HTTPError as error:
            showWarning('The remote server has returned an error:'
                        ' HTTP Error {} ({})'.format(error.code, error.reason))
            return

        body = '\n'.join(map(str, webpage.find('body').children))
        source = self.settings['sourceFormat'].format(
            date=date.today(), url='<a href="%s">%s</a>' % (url, url))

        if self.settings['prioEnabled']:
            priority = self.settings['priorities'][chooseList(
                'Enter priority for "' + webpage.title.string +
                '".\nYou can change it later.', self.settings['priorities'])]
        else:
            priority = None

        self._createNote(webpage.title.string, body, source, priority)
Exemple #27
0
 def setup_client(self):
     auth_token = SETTINGS.EVERNOTE.AUTH_TOKEN.fetch()
     if not auth_token:
         # First run of the Plugin we did not save the access key yet
         secrets = {'holycrepe': '36f46ea5dec83d4a', 'scriptkiddi-2682': '965f1873e4df583c'}
         client = EvernoteClient(
             consumer_key=EVERNOTE.API.CONSUMER_KEY,
             consumer_secret=secrets[EVERNOTE.API.CONSUMER_KEY],
             sandbox=EVERNOTE.API.IS_SANDBOXED
         )
         request_token = client.get_request_token('https://fap-studios.de/anknotes/index.html')
         url = client.get_authorize_url(request_token)
         showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
         openLink(url)
         oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
         auth_token = client.get_access_token(
             request_token.get('oauth_token'),
             request_token.get('oauth_token_secret'),
             oauth_verifier)
         SETTINGS.EVERNOTE.AUTH_TOKEN.save(auth_token)
     else:
         client = EvernoteClient(token=auth_token, sandbox=EVERNOTE.API.IS_SANDBOXED)
     self.token = auth_token
     self.client = client
     log("Set up Evernote Client", 'client')
Exemple #28
0
 def onAdd(self):
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(_("Name:"), default=m['name'])[0]
         if txt:
             m['name'] = txt
         self.mm.save(m)
         self.updateModelsList()
Exemple #29
0
 def onAdd(self) -> None:
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(tr.actions_name(),
                       default=m["name"])[0].replace('"', "")
         if txt:
             m["name"] = txt
         self.saveAndRefresh(m)
Exemple #30
0
def ask_value():
    global card_filter
    r = utils.getText(prompt=u"Enter CardID", default=u"0")
    num = int(r[0])
    if r[1] == 0 or num is None:
        card_filter = ""
    else:
        card_filter = r[0]
Exemple #31
0
 def onAdd(self):
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(_("Name:"), default=m["name"])[0]
         if txt:
             m["name"] = txt
         self.mm.save(m)
         self.updateModelsList()
Exemple #32
0
    def onRename(self) -> None:
        nt = self.current_notetype()
        text, ok = getText(tr.actions_new_name(), default=nt["name"])
        if ok and text.strip():
            nt["name"] = text

            update_notetype_legacy(parent=self, notetype=nt).success(
                self.refresh_list).run_in_background()
Exemple #33
0
def sort(self):
    cids = self.selectedCards()
    params = self.col.get_config("special sort", "")
    (params, ret) = getText("How to sort those cards", self, default=params)
    if not ret:
        return
    self.col.set_config("special sort", params)
    sortCids(cids, f"[{params}]")
Exemple #34
0
def myGetField(parent, question, last_val, **kwargs):
    te = TagEdit(parent, type=1)
    te.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
    te.strings = last_val
    te.showCompleter = lambda te=te: showCompleter(te)
    ret = getText(question, parent, edit=te, **kwargs)
    te.hideCompleter()
    return ret
def myGetField(parent, question, last_val, **kwargs):
    te = TagEdit(parent, type=1)
    te.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
    te.strings = last_val
    te.showCompleter = lambda te=te: showCompleter(te)
    ret = getText(question, parent, edit=te, **kwargs)
    te.hideCompleter()
    return ret
Exemple #36
0
 def ask_to_reschedule(self):
     nd = getText("Reschedule with intervals of __ days: ")
     try:
         ndi = int(nd[0])
     except:
         tooltip('input is not an integer. Aborting')
     else:
         self.add_and_reschedule(ndi, ndi)
Exemple #37
0
 def emptyTrash(self, dynId):
     global PURGE
     t, ok = getText("""Empty Recycle Bin? Type: I Shall Not Hoard""")
     if ok and t.lower() == "i shall not hoard":
         PURGE = True
         cids = mw.col.db.list("select id from cards where did=?", dynId)
         mw.col.remCards(cids)
         return True
     return False
Exemple #38
0
 def onAdd(self):
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(_("Name:"), default=m['name'])[0]
         if txt:
             m['name'] = txt
         self.mm.ensureNameUnique(m)
         self.mm.save(m)
         self.updateModelsList()
Exemple #39
0
 def onAdd(self):
     m = AddModel(self.mw, self).get()
     if m:
         txt = getText(_("Name:"), default=m["name"])[0]
         if txt:
             m["name"] = txt
         self.mm.ensureNameUnique(m)
         self.mm.save(m)
         self.updateModelsList()
Exemple #40
0
def onResetTimes(browser):

    # Make sure user selected something.
    if not browser.form.tableView.selectionModel().hasSelection():
        showWarning("Please select at least one card to reset creation date.", parent=browser)
        return
 
    # Preprocess cards, collecting note IDs.
    (card_cnt, nids) = identifyNotes(browser.selectedCards())
    
    # debug
    #showInfo(("Processed %s cards leading to %s notes") % (card_cnt, len(nids)))
    
    # Prompt for date.
    todaystr = time.strftime('%Y/%m/%d', time.localtime())
    (s, ret) = getText("Enter a date as YYYY/MM/DD to set as the creation time, or 'today' for current date (%s):" % todaystr, parent=browser)

    if (not s) or (not ret):
        return
    
    # Generate a random MM:HH:SS. This will help prevent the same timestamp from
    # being used if this addon is executed multiple times with the same date.
    random_time = ("%s:%s:%s") % (random.randint(0, 23), random.randint(0, 59), random.randint(0, 59))

    # Don't want random? Uncomment the following line and specify any time you 
    # want in the format HH:MM:SS where HH is 00-24:
    #random_time = "15:01:01"

    
    if s == 'today':
        desttime = time.mktime(time.strptime(("%s %s") % (todaystr, random_time), '%Y/%m/%d %H:%M:%S'))
    else:
        try:
            desttime = time.mktime(time.strptime(("%s %s") % (s, random_time), '%Y/%m/%d %H:%M:%S'))
        except ValueError:
            showWarning("Sorry, I didn't understand that date.  Please enter 'today' or a date in YYYY/MM/DD format", parent=browser)
            return
   
    # This mimics anki/utils.py timestampID function (which calls intTime for
    # seconds since epoch and multiplies those seconds by 1000).
    desttime = desttime * 1000
    
    # debug
    # showInfo(("desttime %s") % desttime)

    # Force a full sync if collection isn't already marked for one. This is
    # apparently because we are changing the key column of the table.
    # (Per Damien on 2013/01/07: http://groups.google.com/group/anki-users/msg/3c8910e10f6fd0ac?hl=en )
    mw.col.modSchema(check=True)
    
    # Do it.
    resetCreationTimes(nids, desttime)
        
    # Done.
    mw.reset()
    tooltip(ngettext("Creation time reset for %d note.", "Creation time reset for %d notes.", len(nids)) % len(nids))
def promptNewInterval(self, card):

    dayString = getText("Number of days until next review: ")
    try:
        days = int(dayString[0])
    except ValueError:
        return

    if days > 0:
        mw.col.sched.reschedCards( [card.id], days, days )
        tooltip('Rescheduled for review in ' + str(days) + ' days'  )
        mw.reset()
Exemple #42
0
 def onRename(self):
     txt = getText(_("New name?"), default=self.model.name)
     if txt[0]:
         self.model.name = txt[0]
     self.updateModelsList()
Exemple #43
0
 def onRename(self):
     txt = getText(_("New name:"), default=self.model['name'])
     if txt[1] and txt[0]:
         self.model['name'] = txt[0]
         self.mm.save(self.model)
     self.updateModelsList()
def newKeyHandler(self, evt):
    key = unicode(evt.text())
    card = mw.reviewer.card
    if not key:
        origKeyHandler(self, evt)
        return
    elif key == reschedule_shortcut:
        mw.checkpoint(_("Reschedule card"))
        promptNewInterval(self, card)
        #    elif key == reschedule_four_weeks:
        #mw.checkpoint(_("Reschedule card"))
        #mw.col.sched.reschedCards( [card.id], 21, 42 )
        #tooltip('Rescheduled for review in 3-6 weeks'  )
        #mw.reset()
    elif key == reschedule_tomorrow:
        mw.checkpoint(_("Reschedule card"))
        mw.col.sched.reschedCards( [card.id], 1, 1 )
        tooltip('Rescheduled for review tomorrow'  )
        mw.reset()
    elif key in edit_occupyImage:
        patt=r"""<img.*?src=(["'])(.*?)\1"""
        pattern = re.compile(patt, flags=re.I|re.M|re.S)
        note = mw.reviewer.card.note()
        field_names = [item[0] for item in note.items()]
        imagename=""
        field_name=""
        valid_ext=False
        for fldName in field_names:
            m = pattern.search(note[fldName])
            if(m):
                imagename = m.group(2)
                valid_ext = imagename.endswith((".jpg",".jpeg",".gif",".png"))
                if(valid_ext):
                    field_name=fldName
                    break
        if(valid_ext):
            try:
                mw.reviewer.image_occlusion
            except:
                mw.reviewer.image_occlusion = ImageOcc_Add(mw.reviewer)
                
            mw.reviewer.image_occlusion.add_notes(field_name)
    elif key in edit_rtl:
        mw.checkpoint(_("Made RTL"))
        note = mw.reviewer.card.note()
        for item in note.items():
            if item[0] in rtl_fileds_arr:
                note[item[0]] = "<div class='f r'>" + note[item[0]] + "</div>"
                note.flush()
                redraw_card()
    elif key in key_add_note :
        if key!="N":
            import win32api
            win32api.LoadKeyboardLayout('00000429',1) # to switch to english
        text, ok = getText("your note on this card?")
        if ok:
            note = mw.reviewer.card.note()
            for item in note.items():
                if item[0] in rtl_fileds_arr:
                    note[item[0]] = note[item[0]] + "<p class=\"%(className)s\">%(text)s</p>" % \
                        {'className':"floatLeft" if key=="N" else "f r",
                        'text':text}
                    note.flush()
                    redraw_card()
    elif key in key_english:
        import win32api
        win32api.LoadKeyboardLayout('00000409',1) # to switch to english
    else:
        origKeyHandler(self, evt)
Exemple #45
0
 def renameTemplate(self, item):
     txt = getText(_("New name?"), default=self.template['name'])
     if txt[0]:
         self.template['name'] = txt[0]