def select_note_fields_all(note_id): example_row = mw.col.db.first('SELECT flds FROM notes WHERE id = :nid', nid=note_id) example_flds = example_row[0].split('\x1f') choices = [ '[{}] {}'.format(i, fld[:20]) for i, fld in enumerate(example_flds) ] expr_idx = chooseList('Which field contains the Japanese expression?', choices) reading_idx = chooseList('Which field contains the reading?', choices) output_idx = chooseList('Which field should the pitch accent be shown in?', choices) return expr_idx, reading_idx, output_idx
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)
def _getPriority(self, name=None): if name: prompt = 'Select priority for <b>{}</b>'.format(name) else: prompt = 'Select priority for import' return self.settings['priorities'][chooseList( prompt, self.settings['priorities'])]
def chooseDeck(prompt="Choose deck"): "Shows a deck selector and returns the deck ID. If cancelled, return 0." choices = sorted(mw.col.decks.allNames()) chosenIndex = chooseList(prompt, ["Cancel"] + choices) if chosenIndex == 0: return 0 return mw.col.decks.id(choices[chosenIndex - 1])
def select_deck_id(msg): decks = [] for row in mw.col.db.execute('SELECT id, name FROM decks'): d_id = row[0] d_name = row[1] decks.append((d_id, d_name)) choices = [deck[1] for deck in decks] choice = chooseList(msg, choices) return decks[choice][0]
def select_note_fields_del(note_id): example_row = mw.col.db.first('SELECT flds FROM notes WHERE id = :nid', nid=note_id) example_flds = example_row[0].split('\x1f') choices = [ '[{}] {}'.format(i, fld[:20]) for i, fld in enumerate(example_flds) ] del_idx = chooseList( 'Which field should the pitch accent be removed from?', choices) return del_idx
def select_deck_id(msg): decks = [] for row in mw.col.db.execute('SELECT decks FROM col'): deks = json.loads(row[0]) for key in deks: d_id = deks[key]['id'] d_name = deks[key]['name'] decks.append((d_id, d_name)) choices = [deck[1] for deck in decks] choice = chooseList(msg, choices) return decks[choice][0]
def onChangeSortField(self): from aqt.utils import chooseList m = self.card.model() fields = [f['name'] for f in m['flds']] mm = self.col.models idx = chooseList(_("Choose field to sort this model by:"), fields, mm.sortIdx(m)) if idx != mm.sortIdx(m): self.mw.progress.start() mm.setSortIdx(m, idx) self.mw.progress.finish() self.onSearch()
def copyScheduling(): decks = mw.col.decks.all() deckFromIndex = chooseList("Choose deck to copy from", chain(map(lambda deck: deck['name'], decks), ["Cancel"])) if deckFromIndex == len(decks): return otherDecks = decks.copy() otherDecks.pop(deckFromIndex) deckToIndex = chooseList("Choose deck to copy to", chain(map(lambda deck: deck['name'], otherDecks), ["Cancel"])) if deckToIndex == len(otherDecks): return deckFrom = decks[deckFromIndex] deckTo = otherDecks[deckToIndex] mw.checkpoint("Copy scheduling") try: _copyScheduling(deckFrom, deckTo) except: mw.col.db.rollback() raise
def onChangeSortField(self): from aqt.utils import chooseList m = self.card.model() fields = [f['name'] for f in m['flds']] mm = self.col.models idx = chooseList(_("Choose field to sort this model by:"), fields, mm.sortIdx(m)) if idx != mm.sortIdx(m): self.mw.progress.start() mm.setSortIdx(m, idx) self.mw.progress.finish() self.onSearch()
def select_note_type(note_type_ids): note_types = [] for row in mw.col.db.execute('SELECT id, name FROM notetypes'): n_id = row[0] n_name = row[1] note_types.append((n_id, n_name)) choices = [note_type[1] for note_type in note_types] choice = chooseList( 'Select a note type.', choices ) return note_types[choice][0]
def get_definition(editor, word_name): editor.loadNote() editor.web.setFocus() editor.web.eval("focusField(0);") editor.web.eval("caretToEnd();") editor_fields = editor.note.fields if not find_word_in_dictionary(word_name): return words_to_choose_from_as_strings = [] definitions = [] words = get_words() for word in words: for sense in word.senses: for definition in sense.definitions: words_to_choose_from_as_strings.append( '%s | %s | %s' % (word.headword, word.part_of_speech, definition)) definitions.append(definition) chosen_index = chooseList('Choose definition', words_to_choose_from_as_strings) word = find_word_by_definition(words, definitions[chosen_index]) examples = find_examples_by_definition(words, definitions[chosen_index]) # set sentences editor_fields[0] = '' for example in examples: editor_fields[0] += str(example) + "<br>\n" # set definition audio = word.pronunciation.audio.get_anki_sound( ) if word.pronunciation is not None else '' ipa = '\\%s\\' % word.pronunciation.ipa if word.pronunciation is not None else '' editor_fields[1] = '%s, <i>%s</i>, %s %s <br>\n' % ( word.headword, word.part_of_speech, ipa, audio) editor_fields[1] += definitions[chosen_index].text refresh_fields(editor) # download media if word.pronunciation is not None: urllib.request.urlretrieve(word.pronunciation.audio.file_url, word.pronunciation.audio.file_name) #editor.urlToLink(word.pronunciation.audio.file_url) for example in examples: urllib.request.urlretrieve(example.audio.file_url, example.audio.file_name)
def select_note_type(note_type_ids): row = mw.col.db.first('SELECT models FROM col') models_dict = json.loads(row[0]) model_names = [models_dict[str(mid)]['name'] for mid in note_type_ids] choice = chooseList('Select a note type.', model_names) return note_type_ids[choice]
def onFocusLost(flag, n, fidx): global af global jp global sw if not af.isTargetNoteType(n.model()['name']): return flag fields = mw.col.models.fieldNames(n.model()) src = fields[fidx] if not af.isFieldInSrc(src): return flag srcTxt = mw.col.media.strip(n[src]) try: if not af.findDstFieldName(n): return flag if not af.isAllFieldEmpty(): return flag if srcTxt == '': af.flushDstFields() return True if not jp.serchWord(srcTxt): return flag #kana = af.getFieldValue(n,'KanaFields') if jp.isMultiPronounces(): logging.debug("pop QComboBox to select pronounce") list = jp.getKanaList() index = chooseList("multi pronounce", list, startrow=0, parent=None) jp.setIndexPronounces(index) sentence = jp.getSentence() meaning = jp.getMeaning() pronounce = jp.getPronounce() if meaning: meaning = LF2BR(removeFirstLF(onlyOneLF(meaning))) af.addDstValue('MeaningFields', cc.convert(meaning)) if pronounce: af.addDstValue('KanaFields', pronounce[0]) af.addDstValue( 'PronounceAudioField', AnkiMedia.audioLinkToField(pronounce[1], pronounce[2])) if sentence and sw.sentence_generate: if pronounce[2] == None: file_name = srcTxt + "_sentence" else: file_name = pronounce[2] + "_sentence" af.addDstValue('SentenceFields', sentence[0]) af.addDstValue('SentenceMeaningFields', cc.convert(sentence[1])) af.addDstValue('SentenceAudioField', AnkiMedia.audioLinkToField(sentence[2], file_name)) if not af.generateFields(): return flag except crawler.CrawlerError as e: logging.warning(e) except requests.ConnectionError as e: showInfo(e) except Exception as e: logging.error('Error when serch word:' + jp.word) logging.error(e) logging.error(traceback.format_exc()) jp.dumpHtmlResult() jp = None raise return True