Пример #1
0
def save_helper(browser, ftype, notesonly):
    if notesonly and ftype == "csv":
        out = getSaveDir(
            parent=browser,
            title="Select Folder for csv files for exported notes",
            identifier_for_last_user_selection="notesOnlyCsvExport")
    nownow = now()
    if notesonly and ftype == "xlsx":
        out = getSaveFile(
            browser,
            _("Export underyling notes from Browser to xlsx"),  # windowtitle
            "export_notes_xlsx",  # dir_description - used to remember last user choice
            _("Notes as xlsx"),  # key
            '.xlsx',  # ext
            'Anki_notes__%s.xlsx' % nownow)  # filename  # aqt.mw.pm.name
    if not notesonly and ftype == "csv":
        out = getSaveFile(
            browser,
            _("Export Selected From Browser to Csv"),  # windowtitle
            "export_cards_csv",  # dir_description - used to remember last user choice
            _("Cards as CSV"),  # key
            '.csv',  # ext
            'exportcsv___%s.csv' % nownow)  # filename
    if not notesonly and ftype == "xlsx":
        out = getSaveFile(browser, _("Export Selected From Browser to Xlsx"),
                          "export_cards_xlsx", _("Cards as Xlsx"), '.xlsx',
                          'exportcsv___%s.xlsx' % nownow)
    return out
def export_ease_factors(deck_id):
    '''For some deck `deck_id`, returns a dictionary linking card id keys to
    ease factors.
    '''
    deck_name = mw.col.decks.nameOrNone(deck_id)
    if deck_name is None:
        return
    
    # open file picker to store factors
    dt_now_str = str(datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
    suggested_filename = f"ease_factors_{deck_id}_{dt_now_str}"
    export_file = getSaveFile(mw, _("Export"), "export", 
                              key = "",
                              ext = "",
                              fname=suggested_filename)
    if not export_file:
        return

    factors = {}
    card_ids = mw.col.findCards(f'deck:"{deck_name}"')
    for card_id in card_ids:
        card = mw.col.getCard(card_id)
        factors[card_id] = card.factor
    with open(export_file, 'w') as export_file_object: 
        export_file_object.write(str(factors))

    tooltip('Ease Factors were exported')
Пример #3
0
def onExportList(browser):
    # big reach!
    if not browser.form.tableView.selectionModel().hasSelection():
        showWarning("Please select 1 or more rows", browser, help="")
        return
    path = getSaveFile(browser, _("Export Browser List"), "exportcsv", _("Cards as CSV"), '.csv', 'exportcsv.csv')
    if not path:
        return
    file = open(path, "wb")
    writer = csv.writer(file, dialect='excel')

    for rowIndex in browser.form.tableView.selectionModel().selectedRows():
        #wasn't sure if I could modify the "Index" objects we get back from
        #  the selection model. Since the columnData function only accesses
        #  the row() and column() functions, seemed safer to create new
        #  instances.
        row = rowIndex.row()
        rowdata = []
        for column in range(browser.model.columnCount(0)):
            index = RowAndColumn(row, column)
            #let the browser model's columnData function do all the hard work
            answer = escapeText(browser.model.columnData(index))
            rowdata.append(answer.encode('utf8'))
        writer.writerow(rowdata)
    file.close()
Пример #4
0
 def accept(self):
     file = getSaveFile(self, _("Export"), "export", self.exporter.key,
                        self.exporter.ext)
     self.hide()
     if file:
         self.exporter.includeSched = (self.frm.includeSched.isChecked())
         self.exporter.includeMedia = (self.frm.includeMedia.isChecked())
         self.exporter.includeTags = (self.frm.includeTags.isChecked())
         if not self.frm.deck.currentIndex():
             self.exporter.did = None
         else:
             name = self.decks[self.frm.deck.currentIndex()]
             self.exporter.did = self.col.decks.id(name)
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             tooltip(ngettext("%d card exported.", "%d cards exported.", \
                             self.exporter.count) % self.exporter.count)
         finally:
Пример #5
0
 def accept(self):
     self.exporter.includeSched = (
         self.frm.includeSched.isChecked())
     self.exporter.includeMedia = (
         self.frm.includeMedia.isChecked())
     self.exporter.includeTags = (
         self.frm.includeTags.isChecked())
     if not self.frm.deck.currentIndex():
         self.exporter.did = None
     else:
         name = self.decks[self.frm.deck.currentIndex()]
         self.exporter.did = self.col.decks.id(name)
     if (self.isApkg and self.exporter.includeSched and not
         self.exporter.did):
         verbatim = True
         # it's a verbatim apkg export, so place on desktop instead of
         # choosing file
         file = os.path.join(QDesktopServices.storageLocation(
             QDesktopServices.DesktopLocation), "collection.apkg")
         if os.path.exists(file):
             if not askUser(
                 _("%s already exists on your desktop. Overwrite it?")%
                 "collection.apkg"):
                 return
     else:
         verbatim = False
         # Get deck name and remove invalid filename characters
         deck_name = self.decks[self.frm.deck.currentIndex()]
         deck_name = re.sub('[\\\\/?<>:*|"^]', '_', deck_name)
         filename = os.path.join(aqt.mw.pm.base,
                                 u'{0}{1}'.format(deck_name, self.exporter.ext))
         while 1:
             file = getSaveFile(self, _("Export"), "export",
                                self.exporter.key, self.exporter.ext,
                                fname=filename)
             if not file:
                 return
             if checkInvalidFilename(os.path.basename(file), dirsep=False):
                 continue
             break
     self.hide()
     if file:
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             if verbatim:
                 msg = _("A file called collection.apkg was saved on your desktop.")
                 period = 5000
             else:
                 period = 3000
                 msg = ngettext("%d card exported.", "%d cards exported.", \
                             self.exporter.count) % self.exporter.count
             tooltip(msg, period=period)
         finally:
Пример #6
0
 def accept(self):
     file = getSaveFile(
         self, _("Export"), "export",
         self.exporter.key, self.exporter.ext)
     self.hide()
     if file:
         self.exporter.includeSched = (
             self.frm.includeSched.isChecked())
         self.exporter.includeMedia = (
             self.frm.includeMedia.isChecked())
         self.exporter.includeTags = (
             self.frm.includeTags.isChecked())
         if not self.frm.deck.currentIndex():
             self.exporter.did = None
         else:
             name = self.decks[self.frm.deck.currentIndex()]
             self.exporter.did = self.col.decks.id(name)
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             tooltip(_("%d exported.") % self.exporter.count)
         finally:
def get_save_path():
    ext = ".colpkg"
    return getSaveFile(
        mw,
        "Export collection without media with empty fields",  # windowtitle
        "export_emptied_collection_without_media",  # dir_description - used to remember last choice
        "Collection as apkg",  # key
        ext,
        'Anki_collection_without_media_or_field_contents__%s%s' % (now(), ext))  # filename
Пример #8
0
Файл: stats.py Проект: zzp0/anki
 def _imagePath(self):
     name = time.strftime("-%Y-%m-%d@%H-%M-%S.pdf",
                          time.localtime(time.time()))
     name = "anki-"+_("stats")+name
     file = getSaveFile(self, title=_("Save PDF"),
                        dir_description="stats",
                        key="stats",
                        ext=".pdf",
                        fname=name)
     return file
Пример #9
0
 def accept(self):
     self.exporter.includeSched = (
         self.frm.includeSched.isChecked())
     self.exporter.includeMedia = (
         self.frm.includeMedia.isChecked())
     self.exporter.includeTags = (
         self.frm.includeTags.isChecked())
     if not self.frm.deck.currentIndex():
         self.exporter.did = None
     else:
         name = self.decks[self.frm.deck.currentIndex()]
         self.exporter.did = self.col.decks.id(name)
     if (self.isApkg and self.exporter.includeSched and not
         self.exporter.did):
         verbatim = True
         # it's a verbatim apkg export, so place on desktop instead of
         # choosing file
         file = os.path.join(QDesktopServices.storageLocation(
             QDesktopServices.DesktopLocation), "collection.apkg")
         if os.path.exists(file):
             if not askUser(
                 _("%s already exists on your desktop. Overwrite it?")%
                 "collection.apkg"):
                 return
     else:
         verbatim = False
         while 1:
             file = getSaveFile(
                 self, _("Export"), "export",
                 self.exporter.key, self.exporter.ext)
             if not file:
                 return
             if checkInvalidFilename(file, dirsep=False):
                 continue
             break
     self.hide()
     if file:
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             if verbatim:
                 msg = _("A file called collection.apkg was saved on your desktop.")
                 period = 5000
             else:
                 period = 3000
                 msg = ngettext("%d card exported.", "%d cards exported.", \
                             self.exporter.count) % self.exporter.count
             tooltip(msg, period=period)
         finally:
Пример #10
0
 def onExport(self):
     o = getSaveFile(mw,
                     title="Anki - Select file for export",
                     dir_description="jsonbuttons",
                     key=".json",
                     ext=".json",
                     fname="anki_addon_styling_buttons_config.json")
     if o:
         self.updateConfig()
         with open(o, 'w') as fp:
             json.dump(self.config, fp)
Пример #11
0
 def _imagePath(self) -> str:
     name = time.strftime("-%Y-%m-%d@%H-%M-%S.pdf", time.localtime(time.time()))
     name = f"anki-{tr.statistics_stats()}{name}"
     file = getSaveFile(
         self,
         title=tr.statistics_save_pdf(),
         dir_description="stats",
         key="stats",
         ext=".pdf",
         fname=name,
     )
     return file
Пример #12
0
 def _imagePath(self):
     name = time.strftime("-%Y-%m-%d@%H-%M-%S.pdf", time.localtime(time.time()))
     name = "anki-" + tr(TR.STATISTICS_STATS) + name
     file = getSaveFile(
         self,
         title=tr(TR.STATISTICS_SAVE_PDF),
         dir_description="stats",
         key="stats",
         ext=".pdf",
         fname=name,
     )
     return file
Пример #13
0
def exportDeck():
    deckId = chooseDeck(prompt="Choose deck to export scheduling from")
    if deckId == 0:
        return
    cids = mw.col.decks.cids(deckId, children=False)
    cards = {}

    for cid in cids:
        card = mw.col.getCard(cid)
        note = mw.col.getNote(card.nid)
        sfld = stripHTMLMedia(note.fields[note.col.models.sortIdx(
            note._model)])
        # Skip new cards
        if card.queue == 0:
            continue
        if sfld in cards:
            showText("Card with duplicated field found; aborting.")
            return

        revlogKeys = ["id", "ease", "ivl", "lastIvl", "factor", "time", "type"]
        revlogsArray = mw.col.db.all(
            "select " + ", ".join(revlogKeys) + " from revlog " +
            "where cid = ?", cid)
        revlogsDict = list(
            map(
                lambda row:
                {revlogKeys[i]: row[i]
                 for i in range(0, len(revlogKeys))}, revlogsArray))

        cards[sfld] = dict(due=card.due,
                           queue=card.queue,
                           ivl=card.ivl,
                           factor=card.factor,
                           left=card.left,
                           type=card.type,
                           lapses=card.lapses,
                           reps=card.reps,
                           flags=card.flags,
                           revlogs=revlogsDict)

    file = getSaveFile(
        mw, "Export scheduling info to file", "anki-times", "JSON", ".json",
        re.sub('[\\\\/?<>:*|"^]', '_', mw.col.decks.name(deckId)) +
        "-scheduling")
    if not file:
        return

    output = {"meta": {"crt": mw.col.crt}, "cards": cards}

    with open(file, "w") as f:
        json.dump(output, f, ensure_ascii=False)
Пример #14
0
 def accept(self):
     self.exporter.includeSched = (
         self.frm.includeSched.isChecked())
     self.exporter.includeMedia = (
         self.frm.includeMedia.isChecked())
     self.exporter.includeTags = (
         self.frm.includeTags.isChecked())
     if not self.frm.deck.currentIndex():
         self.exporter.did = None
     else:
         name = self.decks[self.frm.deck.currentIndex()]
         self.exporter.did = self.col.decks.id(name)
     if (self.isApkg and self.exporter.includeSched and not
         self.exporter.did):
         verbatim = True
         # it's a verbatim apkg export, so place on desktop instead of
         # choosing file
         file = os.path.join(QDesktopServices.storageLocation(
             QDesktopServices.DesktopLocation), "collection.apkg")
         if os.path.exists(file):
             if not askUser(
                 _("%s already exists on your desktop. Overwrite it?")%
                 "collection.apkg"):
                 return
     else:
         verbatim = False
         file = getSaveFile(
             self, _("Export"), "export",
             self.exporter.key, self.exporter.ext)
         if not file:
             return
     self.hide()
     if file:
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             if verbatim:
                 msg = _("A file called collection.apkg was saved on your desktop.")
                 period = 5000
             else:
                 period = 3000
                 msg = ngettext("%d card exported.", "%d cards exported.", \
                             self.exporter.count) % self.exporter.count
             tooltip(msg, period=period)
         finally:
Пример #15
0
def do_the_export():
    'Query filename from user, then export revision history to CSV file'
    filename = getSaveFile(parent=None,
                           title="Export memorization performance history",
                           dir_description="qs_addon",
                           key="Comma-separated values",
                           ext="csv",
                           fname="RevisionHistory.csv")
    if filename:
        mw.progress.start()
        pe = PerformanceExtractor()
        try:
            pe.export_csv(filename)
        except IOError:
            showInfo((f"Could not open file <tt>{filename}</tt> for writing. Please make sure"
                      f"it's not open by another application already."))
            return
        mw.progress.finish()
        showInfo("{} reviews exported".format(len(pe.history)))
Пример #16
0
 def accept(self):
     file = getSaveFile(
         self, _("Choose file to export to"), "export",
         self.exporter.key, self.exporter.ext)
     self.hide()
     if file:
         self.exporter.includeSched = (
             self.frm.includeSched.isChecked())
         self.exporter.includeTags = (
             self.frm.includeTags.isChecked())
         if not self.frm.deck.currentIndex():
             self.exporter.did = None
         else:
             name = self.decks[self.frm.deck.currentIndex()]
             self.exporter.did = self.col.decks.id(name)
         self.mw.progress.start(immediate=True)
         self.exporter.exportInto(file)
         self.mw.progress.finish()
         tooltip(_("%d exported.") % self.exporter.count)
     QDialog.accept(self)
def export_deck(did):
    # inspired by aqt.exporting.ExportDialog.accept
    exporter = AnkiPackageExporter(mw.col)
    exporter.includeSched = False
    exporter.includeMedia = gc("include media that starts with underscore"
                               )  # get _styles_for_syntax_highlighting.css
    exporter.includeTags = False
    exporter.includeHTML = False
    exporter.did = did
    now = time.strftime("-%Y-%m-%d@%H-%M-%S", time.localtime(time.time()))
    while 1:
        file = getSaveFile(
            mw,  # parent
            _("Export"),  # windowtitle
            "debug_export_all_notetypes",  # dir_description - used to remember last user choice for dir
            exporter.key,  # key
            exporter.ext,  # ext
            'export_all_notetypes__%s.apkg' % now)  # filename
        if not file:
            return
        if checkInvalidFilename(os.path.basename(file), dirsep=False):
            continue
        break
    if file:
        mw.progress.start(immediate=True)
        try:
            f = open(file, "wb")
            f.close()
        except (OSError, IOError) as e:
            showWarning(_("Couldn't save file: %s") % str(e))
        else:
            os.unlink(file)
            exportedMedia = lambda cnt: mw.progress.update(label=ngettext(
                "Exported %d media file", "Exported %d media files", cnt) % cnt
                                                           )
            addHook("exportedMediaFiles", exportedMedia)
            exporter.exportInto(file)
            remHook("exportedMediaFiles", exportedMedia)
            tooltip("Exporting finished", 3000)
        finally:
            mw.progress.finish()
Пример #18
0
 def accept(self):
     self.exporter.includeSched = (self.frm.includeSched.isChecked())
     self.exporter.includeMedia = (self.frm.includeMedia.isChecked())
     self.exporter.includeTags = (self.frm.includeTags.isChecked())
     if not self.frm.deck.currentIndex():
         self.exporter.did = None
     else:
         name = self.decks[self.frm.deck.currentIndex()]
         self.exporter.did = self.col.decks.id(name)
     if (self.isApkg and self.exporter.includeSched
             and not self.exporter.did):
         verbatim = True
         # it's a verbatim apkg export, so place on desktop instead of
         # choosing file; use homedir if no desktop
         usingHomedir = False
         file = os.path.join(
             QDesktopServices.storageLocation(
                 QDesktopServices.DesktopLocation), "collection.apkg")
         if not os.path.exists(os.path.dirname(file)):
             usingHomedir = True
             file = os.path.join(
                 QDesktopServices.storageLocation(
                     QDesktopServices.HomeLocation), "collection.apkg")
         if os.path.exists(file):
             if usingHomedir:
                 question = _(
                     "%s already exists in your home directory. Overwrite it?"
                 )
             else:
                 question = _(
                     "%s already exists on your desktop. Overwrite it?")
             if not askUser(question % "collection.apkg"):
                 return
     else:
         verbatim = False
         # Get deck name and remove invalid filename characters
         deck_name = self.decks[self.frm.deck.currentIndex()]
         deck_name = re.sub('[\\\\/?<>:*|"^]', '_', deck_name)
         filename = os.path.join(
             aqt.mw.pm.base, u'{0}{1}'.format(deck_name, self.exporter.ext))
         while 1:
             file = getSaveFile(self,
                                _("Export"),
                                "export",
                                self.exporter.key,
                                self.exporter.ext,
                                fname=filename)
             if not file:
                 return
             if checkInvalidFilename(os.path.basename(file), dirsep=False):
                 continue
             break
     self.hide()
     if file:
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError), e:
             showWarning(_("Couldn't save file: %s") % unicode(e))
         else:
             os.unlink(file)
             self.exporter.exportInto(file)
             if verbatim:
                 if usingHomedir:
                     msg = _(
                         "A file called %s was saved in your home directory."
                     )
                 else:
                     msg = _("A file called %s was saved on your desktop.")
                 msg = msg % "collection.apkg"
                 period = 5000
             else:
                 period = 3000
                 if self.isTextNote:
                     msg = ngettext(
                         "%d note exported.", "%d notes exported.",
                         self.exporter.count) % self.exporter.count
                 else:
                     msg = ngettext(
                         "%d card exported.", "%d cards exported.",
                         self.exporter.count) % self.exporter.count
             tooltip(msg, period=period)
         finally:
Пример #19
0
    def accept(self) -> None:
        self.exporter.includeSched = self.frm.includeSched.isChecked()
        self.exporter.includeMedia = self.frm.includeMedia.isChecked()
        self.exporter.includeTags = self.frm.includeTags.isChecked()
        self.exporter.includeHTML = self.frm.includeHTML.isChecked()
        idx = self.frm.deck.currentIndex()
        if self.cids is not None:
            # Browser Selection
            self.exporter.cids = self.cids
            self.exporter.did = None
        elif idx == 0:
            # All decks
            self.exporter.did = None
            self.exporter.cids = None
        else:
            # Deck idx-1 in the list of decks
            self.exporter.cids = None
            name = self.decks[self.frm.deck.currentIndex()]
            self.exporter.did = self.col.decks.id(name)
        if self.isVerbatim:
            name = time.strftime("-%Y-%m-%d@%H-%M-%S",
                                 time.localtime(time.time()))
            deck_name = tr(TR.EXPORTING_COLLECTION) + name
        else:
            # Get deck name and remove invalid filename characters
            deck_name = self.decks[self.frm.deck.currentIndex()]
            deck_name = re.sub('[\\\\/?<>:*|"^]', "_", deck_name)

        filename = "{0}{1}".format(deck_name, self.exporter.ext)
        if callable(self.exporter.key):
            key_str = self.exporter.key(self.col)
        else:
            key_str = self.exporter.key
        while 1:
            file = getSaveFile(
                self,
                tr(TR.ACTIONS_EXPORT),
                "export",
                key_str,
                self.exporter.ext,
                fname=filename,
            )
            if not file:
                return
            if checkInvalidFilename(os.path.basename(file), dirsep=False):
                continue
            if os.path.commonprefix([self.mw.pm.base,
                                     file]) == self.mw.pm.base:
                showWarning("Please choose a different export location.")
                continue
            break
        self.hide()
        if file:
            # check we can write to file
            try:
                f = open(file, "wb")
                f.close()
            except (OSError, IOError) as e:
                showWarning(tr(TR.EXPORTING_COULDNT_SAVE_FILE, val=str(e)))
            else:
                os.unlink(file)

            # progress handler
            def exported_media(cnt) -> None:
                self.mw.taskman.run_on_main(lambda: self.mw.progress.update(
                    label=tr(TR.EXPORTING_EXPORTED_MEDIA_FILE, count=cnt)))

            def do_export() -> None:
                self.exporter.exportInto(file)

            def on_done(future: Future) -> None:
                self.mw.progress.finish()
                hooks.media_files_did_export.remove(exported_media)
                # raises if exporter failed
                future.result()
                self.on_export_finished()

            self.mw.progress.start()
            hooks.media_files_did_export.append(exported_media)

            self.mw.taskman.run_in_background(do_export, on_done)
Пример #20
0
    def accept(self):
        self.exporter.includeSched = (self.frm.includeSched.isChecked())
        self.exporter.includeMedia = (self.frm.includeMedia.isChecked())
        self.exporter.includeTags = (self.frm.includeTags.isChecked())
        if not self.frm.deck.currentIndex():  #position 0 means: all decks.
            self.exporter.did = None
        else:
            name = self.decks[self.frm.deck.currentIndex()]
            self.exporter.did = self.col.decks.id(name)
        if self.isVerbatim:
            name = time.strftime("-%Y-%m-%d@%H-%M-%S",
                                 time.localtime(time.time()))
            deck_name = _("collection") + name
        else:
            # Get deck name and remove invalid filename characters
            deck_name = self.decks[self.frm.deck.currentIndex()]
            deck_name = re.sub('[\\\\/?<>:*|"^]', '_', deck_name)

        if not self.isVerbatim and self.isApkg and self.exporter.includeSched and self.col.schedVer(
        ) == 2:
            showInfo(
                "Please switch to the regular scheduler before exporting a single deck .apkg with scheduling."
            )
            return

        filename = '{0}{1}'.format(deck_name, self.exporter.ext)
        while 1:
            file = getSaveFile(self,
                               _("Export"),
                               "export",
                               self.exporter.key,
                               self.exporter.ext,
                               fname=filename)
            if not file:
                return
            if checkInvalidFilename(os.path.basename(file), dirsep=False):
                continue
            break
        self.hide()
        if file:
            self.mw.progress.start(immediate=True)
            try:
                f = open(file, "wb")
                f.close()
            except (OSError, IOError) as e:
                showWarning(_("Couldn't save file: %s") % str(e))
            else:
                os.unlink(file)
                exportedMedia = lambda cnt: self.mw.progress.update(
                    label=ngettext("Exported %d media file",
                                   "Exported %d media files", cnt) % cnt)
                addHook("exportedMediaFiles", exportedMedia)
                self.exporter.exportInto(file)
                remHook("exportedMediaFiles", exportedMedia)
                period = 3000
                if self.isVerbatim:
                    msg = _("Collection exported.")
                else:
                    if self.isTextNote:
                        msg = ngettext(
                            "%d note exported.", "%d notes exported.",
                            self.exporter.count) % self.exporter.count
                    else:
                        msg = ngettext(
                            "%d card exported.", "%d cards exported.",
                            self.exporter.count) % self.exporter.count
                tooltip(msg, period=period)
            finally:
                self.mw.progress.finish()
        QDialog.accept(self)
Пример #21
0
    def accept(self):
        self.exporter.includeSched = (
            self.frm.includeSched.isChecked())
        self.exporter.includeMedia = (
            self.frm.includeMedia.isChecked())
        self.exporter.includeTags = (
            self.frm.includeTags.isChecked())
        self.exporter.includeHTML = (
            self.frm.includeHTML.isChecked())
        if not self.frm.deck.currentIndex():
            self.exporter.did = None
        else:
            name = self.decks[self.frm.deck.currentIndex()]
            self.exporter.did = self.col.decks.id(name)
        if self.isVerbatim:
            name = time.strftime("-%Y-%m-%d@%H-%M-%S",
                                 time.localtime(time.time()))
            deck_name = _("collection")+name
        else:
            # Get deck name and remove invalid filename characters
            deck_name = self.decks[self.frm.deck.currentIndex()]
            deck_name = re.sub('[\\\\/?<>:*|"^]', '_', deck_name)

        if not self.isVerbatim and self.isApkg and self.exporter.includeSched and self.col.schedVer() == 2:
            showInfo("Please switch to the regular scheduler before exporting a single deck .apkg with scheduling.")
            return

        filename = '{0}{1}'.format(deck_name, self.exporter.ext)
        while 1:
            file = getSaveFile(self, _("Export"), "export",
                               self.exporter.key, self.exporter.ext,
                               fname=filename)
            if not file:
                return
            if checkInvalidFilename(os.path.basename(file), dirsep=False):
                continue
            break
        self.hide()
        if file:
            self.mw.progress.start(immediate=True)
            try:
                f = open(file, "wb")
                f.close()
            except (OSError, IOError) as e:
                showWarning(_("Couldn't save file: %s") % str(e))
            else:
                os.unlink(file)
                exportedMedia = lambda cnt: self.mw.progress.update(
                        label=ngettext("Exported %d media file",
                                       "Exported %d media files", cnt) % cnt
                        )
                addHook("exportedMediaFiles", exportedMedia)
                self.exporter.exportInto(file)
                remHook("exportedMediaFiles", exportedMedia)
                period = 3000
                if self.isVerbatim:
                    msg = _("Collection exported.")
                else:
                    if self.isTextNote:
                        msg = ngettext("%d note exported.", "%d notes exported.",
                                    self.exporter.count) % self.exporter.count
                    else:
                        msg = ngettext("%d card exported.", "%d cards exported.",
                                    self.exporter.count) % self.exporter.count
                tooltip(msg, period=period)
            finally:
                self.mw.progress.finish()
        QDialog.accept(self)
Пример #22
0
    def accept(self):
        self.exporter.includeSched = self.frm.includeSched.isChecked()
        self.exporter.includeMedia = self.frm.includeMedia.isChecked()
        self.exporter.includeTags = self.frm.includeTags.isChecked()
        self.exporter.includeHTML = self.frm.includeHTML.isChecked()
        idx = self.frm.deck.currentIndex()
        if self.cids is not None:
            # Browser Selection
            self.exporter.cids = self.cids
            self.exporter.did = None
        elif idx == 0:
            # All decks
            self.exporter.did = None
            self.exporter.cids = None
        else:
            # Deck idx-1 in the list of decks
            self.exporter.cids = None
            name = self.decks[self.frm.deck.currentIndex()]
            self.exporter.did = self.col.decks.id(name)
        if self.isVerbatim:
            name = time.strftime("-%Y-%m-%d@%H-%M-%S",
                                 time.localtime(time.time()))
            deck_name = _("collection") + name
        else:
            # Get deck name and remove invalid filename characters
            deck_name = self.decks[self.frm.deck.currentIndex()]
            deck_name = re.sub('[\\\\/?<>:*|"^]', "_", deck_name)

        filename = "{0}{1}".format(deck_name, self.exporter.ext)
        while 1:
            file = getSaveFile(
                self,
                _("Export"),
                "export",
                self.exporter.key,
                self.exporter.ext,
                fname=filename,
            )
            if not file:
                return
            if checkInvalidFilename(os.path.basename(file), dirsep=False):
                continue
            if os.path.commonprefix([self.mw.pm.base,
                                     file]) == self.mw.pm.base:
                showWarning("Please choose a different export location.")
                continue
            break
        self.hide()
        if file:
            self.mw.progress.start(immediate=True)
            try:
                f = open(file, "wb")
                f.close()
            except (OSError, IOError) as e:
                showWarning(_("Couldn't save file: %s") % str(e))
            else:
                os.unlink(file)
                exportedMedia = lambda cnt: self.mw.progress.update(
                    label=ngettext("Exported %d media file",
                                   "Exported %d media files", cnt) % cnt)
                hooks.media_files_did_export.append(exportedMedia)
                self.exporter.exportInto(file)
                hooks.media_files_did_export.remove(exportedMedia)
                period = 3000
                if self.isVerbatim:
                    msg = _("Collection exported.")
                else:
                    if self.isTextNote:
                        msg = (ngettext(
                            "%d note exported.",
                            "%d notes exported.",
                            self.exporter.count,
                        ) % self.exporter.count)
                    else:
                        msg = (ngettext(
                            "%d card exported.",
                            "%d cards exported.",
                            self.exporter.count,
                        ) % self.exporter.count)
                tooltip(msg, period=period)
            finally:
                self.mw.progress.finish()
        QDialog.accept(self)
Пример #23
0
 def accept(self):
     self.exporter.includeSched = (
         self.frm.includeSched.isChecked())
     self.exporter.includeMedia = (
         self.frm.includeMedia.isChecked())
     self.exporter.includeTags = (
         self.frm.includeTags.isChecked())
     if not self.frm.deck.currentIndex():
         self.exporter.did = None
     else:
         name = self.decks[self.frm.deck.currentIndex()]
         self.exporter.did = self.col.decks.id(name)
     if (self.isApkg and self.exporter.includeSched and not
         self.exporter.did):
         verbatim = True
         # it's a verbatim apkg export, so place on desktop instead of
         # choosing file; use homedir if no desktop
         usingHomedir = False
         file = os.path.join(QStandardPaths.writableLocation(
             QStandardPaths.DesktopLocation), "collection.apkg")
         if not os.path.exists(os.path.dirname(file)):
             usingHomedir = True
             file = os.path.join(QStandardPaths.writableLocation(
                 QStandardPaths.HomeLocation), "collection.apkg")
         if os.path.exists(file):
             if usingHomedir:
                 question = _("%s already exists in your home directory. Overwrite it?")
             else:
                 question = _("%s already exists on your desktop. Overwrite it?")
             if not askUser(question % "collection.apkg"):
                 return
     else:
         verbatim = False
         # Get deck name and remove invalid filename characters
         deck_name = self.decks[self.frm.deck.currentIndex()]
         deck_name = re.sub('[\\\\/?<>:*|"^]', '_', deck_name)
         filename = '{0}{1}'.format(deck_name, self.exporter.ext)
         while 1:
             file = getSaveFile(self, _("Export"), "export",
                                self.exporter.key, self.exporter.ext,
                                fname=filename)
             if not file:
                 return
             if checkInvalidFilename(os.path.basename(file), dirsep=False):
                 continue
             break
     self.hide()
     if file:
         self.mw.progress.start(immediate=True)
         try:
             f = open(file, "wb")
             f.close()
         except (OSError, IOError) as e:
             showWarning(_("Couldn't save file: %s") % str(e))
         else:
             os.unlink(file)
             exportedMedia = lambda cnt: self.mw.progress.update(
                     label=ngettext("Exported %d media file",
                                    "Exported %d media files", cnt) % cnt
                     )
             addHook("exportedMediaFiles", exportedMedia)
             self.exporter.exportInto(file)
             remHook("exportedMediaFiles", exportedMedia)
             if verbatim:
                 if usingHomedir:
                     msg = _("A file called %s was saved in your home directory.")
                 else:
                     msg = _("A file called %s was saved on your desktop.")
                 msg = msg % "collection.apkg"
                 period = 5000
             else:
                 period = 3000
                 if self.isTextNote:
                     msg = ngettext("%d note exported.", "%d notes exported.",
                                 self.exporter.count) % self.exporter.count
                 else:
                     msg = ngettext("%d card exported.", "%d cards exported.",
                                 self.exporter.count) % self.exporter.count
             tooltip(msg, period=period)
         finally:
             self.mw.progress.finish()
     QDialog.accept(self)