export in a background thread

This commit is contained in:
Damien Elmes 2020-03-06 14:19:25 +10:00
parent 7986a79530
commit 53952ba131

View File

@ -6,6 +6,7 @@ from __future__ import annotations
import os import os
import re import re
import time import time
from concurrent.futures import Future
from typing import List, Optional from typing import List, Optional
import aqt import aqt
@ -131,7 +132,7 @@ class ExportDialog(QDialog):
break break
self.hide() self.hide()
if file: if file:
self.mw.progress.start(immediate=True) # check we can write to file
try: try:
f = open(file, "wb") f = open(file, "wb")
f.close() f.close()
@ -139,39 +140,51 @@ class ExportDialog(QDialog):
showWarning(_("Couldn't save file: %s") % str(e)) showWarning(_("Couldn't save file: %s") % str(e))
else: else:
os.unlink(file) os.unlink(file)
exportedMedia = lambda cnt: self.mw.progress.update(
label=ngettext( # progress handler
"Exported %d media file", "Exported %d media files", cnt def exported_media(cnt):
self.mw.taskman.run_on_main(
lambda: self.mw.progress.update(
label=ngettext(
"Exported %d media file", "Exported %d media files", cnt
)
% cnt
) )
% cnt
) )
hooks.media_files_did_export.append(exportedMedia)
def do_export():
self.exporter.exportInto(file) self.exporter.exportInto(file)
hooks.media_files_did_export.remove(exportedMedia)
period = 3000 def on_done(future: Future):
if self.isVerbatim:
msg = _("Collection exported.")
self.mw.reopen()
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() self.mw.progress.finish()
QDialog.accept(self) hooks.media_files_did_export.remove(exported_media)
# raises if exporter failed
future.result()
self.on_export_finished()
self.mw.progress.start(immediate=True)
hooks.media_files_did_export.append(exported_media)
self.mw.taskman.run_in_background(do_export, on_done)
def on_export_finished(self):
if self.isVerbatim:
msg = _("Collection exported.")
self.mw.reopen()
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=3000)
QDialog.reject(self)