2019-02-05 04:59:03 +01:00
|
|
|
# Copyright: Ankitects Pty Ltd and contributors
|
2012-12-21 08:51:59 +01:00
|
|
|
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
2013-10-20 03:57:42 +02:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import traceback
|
2019-12-20 10:19:03 +01:00
|
|
|
import zipfile
|
2020-03-06 05:36:05 +01:00
|
|
|
from concurrent.futures import Future
|
2021-10-03 10:59:42 +02:00
|
|
|
from typing import Any, Optional
|
2013-10-20 03:57:42 +02:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
import anki.importing as importing
|
2019-12-20 10:19:03 +01:00
|
|
|
import aqt.deckchooser
|
2013-10-20 03:57:42 +02:00
|
|
|
import aqt.forms
|
|
|
|
import aqt.modelchooser
|
Add apkg import/export on backend (#1743)
* Add apkg export on backend
* Filter out missing media-paths at write time
* Make TagMatcher::new() infallible
* Gather export data instead of copying directly
* Revert changes to rslib/src/tags/
* Reuse filename_is_safe/check_filename_safe()
* Accept func to produce MediaIter in export_apkg()
* Only store file folder once in MediaIter
* Use temporary tables for gathering
export_apkg() now accepts a search instead of a deck id. Decks are
gathered according to the matched notes' cards.
* Use schedule_as_new() to reset cards
* ExportData → ExchangeData
* Ignore ascii case when filtering system tags
* search_notes_cards_into_table →
search_cards_of_notes_into_table
* Start on apkg importing on backend
* Fix due dates in days for apkg export
* Refactor import-export/package
- Move media and meta code into appropriate modules.
- Normalize/check for normalization when deserializing media entries.
* Add SafeMediaEntry for deserialized MediaEntries
* Prepare media based on checksums
- Ensure all existing media files are hashed.
- Hash incoming files during preparation to detect conflicts.
- Uniquify names of conflicting files with hash (not notetype id).
- Mark media files as used while importing notes.
- Finally copy used media.
* Handle encoding in `replace_media_refs()`
* Add trait to keep down cow boilerplate
* Add notetypes immediately instaed of preparing
* Move target_col into Context
* Add notes immediately instaed of preparing
* Note id, not guid of conflicting notes
* Add import_decks()
* decks_configs → deck_configs
* Add import_deck_configs()
* Add import_cards(), import_revlog()
* Use dyn instead of generic for media_fn
Otherwise, would have to pass None with type annotation in the default
case.
* Fix signature of import_apkg()
* Fix search_cards_of_notes_into_table()
* Test new functions in text.rs
* Add roundtrip test for apkg (stub)
* Keep source id of imported cards (or skip)
* Keep source ids of imported revlog (or skip)
* Try to keep source ids of imported notes
* Make adding notetype with id undoable
* Wrap apkg import in transaction
* Keep source ids of imported deck configs (or skip)
* Handle card due dates and original due/did
* Fix importing cards/revlog
Card ids are manually uniquified.
* Factor out card importing
* Refactor card and revlog importing
* Factor out card importing
Also handle missing parents .
* Factor out note importing
* Factor out media importing
* Maybe upgrade scheduler of apkg
* Fix parent deck gathering
* Unconditionally import static media
* Fix deck importing edge cases
Test those edge cases, and add some global test helpers.
* Test note importing
* Let import_apkg() take a progress func
* Expand roundtrip apkg test
* Use fat pointer to avoid propogating generics
* Fix progress_fn type
* Expose apkg export/import on backend
* Return note log when importing apkg
* Fix archived collection name on apkg import
* Add CollectionOpWithBackendProgress
* Fix wrong Interrupted Exception being checked
* Add ClosedCollectionOp
* Add note ids to log and strip HTML
* Update progress when checking incoming media too
* Conditionally enable new importing in GUI
* Fix all_checksums() for media import
Entries of deleted files are nulled, not removed.
* Make apkg exporting on backend abortable
* Return number of notes imported from apkg
* Fix exception printing for QueryOp as well
* Add QueryOpWithBackendProgress
Also support backend exporting progress.
* Expose new apkg and colpkg exporting
* Open transaction in insert_data()
Was slowing down exporting by several orders of magnitude.
* Handle zstd-compressed apkg
* Add legacy arg to ExportAnkiPackage
Currently not exposed on the frontend
* Remove unused import in proto file
* Add symlink for typechecking of import_export_pb2
* Avoid kwargs in pb message creation, so typechecking is not lost
Protobuf's behaviour is rather subtle and I had to dig through the docs
to figure it out: set a field on a submessage to automatically assign
the submessage to the parent, or call SetInParent() to persist a default
version of the field you specified.
* Avoid re-exporting protobuf msgs we only use internally
* Stop after one test failure
mypy often fails much faster than pylint
* Avoid an extra allocation when extracting media checksums
* Update progress after prepare_media() finishes
Otherwise the bulk of the import ends up being shown as "Checked: 0"
in the progress window.
* Show progress of note imports
Note import is the slowest part, so showing progress here makes the UI
feel more responsive.
* Reset filtered decks at import time
Before this change, filtered decks exported with scheduling remained
filtered on import, and maybe_remove_from_filtered_deck() moved cards
into them as their home deck, leading to errors during review.
We may still want to provide a way to preserve filtered decks on import,
but to do that we'll need to ensure we don't rewrite the home decks of
cards, and we'll need to ensure the home decks are included as part of
the import (or give an error if they're not).
https://github.com/ankitects/anki/pull/1743/files#r839346423
* Fix a corner-case where due dates were shifted by a day
This issue existed in the old Python code as well. We need to include
the user's UTC offset in the exported file, or days_elapsed falls back
on the v1 cutoff calculation, which may be a day earlier or later than
the v2 calculation.
* Log conflicting note in remapped nt case
* take_fields() → into_fields()
* Alias `[u8; 20]` with `Sha1Hash`
* Truncate logged fields
* Rework apkg note import tests
- Use macros for more helpful errors.
- Split monolith into unit tests.
- Fix some unknown error with the previous test along the way.
(Was failing after 969484de4388d225c9f17d94534b3ba0094c3568.)
* Fix sorting of imported decks
Also adjust the test, so it fails without the patch. It was only passing
before, because the parent deck happened to come before the
inconsistently capitalised child alphabetically. But we want all parent
decks to be imported before their child decks, so their children can
adopt their capitalisation.
* target[_id]s → existing_card[_id]s
* export_collection_extracting_media() → ...
export_into_collection_file()
* target_already_exists→card_ordinal_already_exists
* Add search_cards_of_notes_into_table.sql
* Imrove type of apkg export selector/limit
* Remove redundant call to mod_schema()
* Parent tooltips to mw
* Fix a crash when truncating note text
String::truncate() is a bit of a footgun, and I've hit this before
too :-)
* Remove ExportLimit in favour of separate classes
* Remove OpWithBackendProgress and ClosedCollectionOp
Backend progress logic is now in ProgressManager. QueryOp can be used
for running on closed collection.
Also fix aborting of colpkg exports, which slipped through in #1817.
* Tidy up import log
* Avoid QDialog.exec()
* Default to excluding scheuling for deck list deck
* Use IncrementalProgress in whole import_export code
* Compare checksums when importing colpkgs
* Avoid registering changes if hashes are not needed
* ImportProgress::Collection → ImportProgress::File
* Make downgrading apkgs depend on meta version
* Generalise IncrementableProgress
And use it in entire import_export code instead.
* Fix type complexity lint
* Take count_map for IncrementableProgress::get_inner
* Replace import/export env with Shift click
* Accept all args from update() for backend progress
* Pass fields of ProgressUpdate explicitly
* Move update_interval into IncrementableProgress
* Outsource incrementing into Incrementor
* Mutate ProgressUpdate in progress_update callback
* Switch import/export legacy toggle to profile setting
Shift would have been nice, but the existing shortcuts complicate things.
If the user triggers an import with ctrl+shift+i, shift is unlikely to
have been released by the time our code runs, meaning the user accidentally
triggers the new code. We could potentially wait a while before bringing
up the dialog, but then we're forced to guess at how long it will take the
user to release the key.
One alternative would be to use alt instead of shift, but then we need to
trigger our shortcut when that key is pressed as well, and it could
potentially cause a conflict with an add-on that already uses that
combination.
* Show extension in export dialog
* Continue to provide separate options for schema 11+18 colpkg export
* Default to colpkg export when using File>Export
* Improve appearance of combo boxes when switching between apkg/colpkg
+ Deal with long deck names
* Convert newlines to spaces when showing fields from import
Ensures each imported note appears on a separate line
* Don't separate total note count from the other summary lines
This may come down to personal preference, but I feel the other counts
are equally as important, and separating them feels like it makes it
a bit easier to ignore them.
* Fix 'deck not normal' error when importing a filtered deck for the 2nd time
* Fix [Identical] being shown on first import
* Revert "Continue to provide separate options for schema 11+18 colpkg export"
This reverts commit 8f0b2c175f4794d642823b60414d142a12768441.
Will use a different approach
* Move legacy support into a separate exporter option; add to apkg export
* Adjust 'too new' message to also apply to .apkg import case
* Show a better message when attempting to import new apkg into old code
Previously the user could end seeing a message like:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte
Unfortunately we can't retroactively fix this for older clients.
* Hide legacy support option in older exporting screen
* Reflect change from paths to fnames in type & name
* Make imported decks normal at once
Then skip special casing in update_deck(). Also skip updating
description if new one is empty.
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
2022-05-02 13:12:46 +02:00
|
|
|
from anki.importing.anki2 import MediaMapInvalid, V2ImportIntoV1
|
2021-02-01 13:08:56 +01:00
|
|
|
from anki.importing.apkg import AnkiPackageImporter
|
2022-06-01 12:26:16 +02:00
|
|
|
from aqt.import_export.importing import ColpkgImporter
|
2022-04-22 06:47:17 +02:00
|
|
|
from aqt.main import AnkiQt, gui_hooks
|
2019-12-20 10:19:03 +01:00
|
|
|
from aqt.qt import *
|
2019-12-23 01:34:10 +01:00
|
|
|
from aqt.utils import (
|
2021-01-25 14:45:47 +01:00
|
|
|
HelpPage,
|
2021-01-07 05:24:49 +01:00
|
|
|
disable_help_button,
|
2019-12-23 01:34:10 +01:00
|
|
|
getFile,
|
2021-03-04 19:55:35 +01:00
|
|
|
getText,
|
2019-12-23 01:34:10 +01:00
|
|
|
openHelp,
|
|
|
|
showInfo,
|
|
|
|
showText,
|
|
|
|
showWarning,
|
|
|
|
tooltip,
|
2020-02-27 11:32:57 +01:00
|
|
|
tr,
|
2019-12-23 01:34:10 +01:00
|
|
|
)
|
2019-12-20 10:19:03 +01:00
|
|
|
|
2013-10-20 03:57:42 +02:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
class ChangeMap(QDialog):
|
2021-10-03 10:59:42 +02:00
|
|
|
def __init__(self, mw: AnkiQt, model: dict, current: str) -> None:
|
2021-10-05 05:53:01 +02:00
|
|
|
QDialog.__init__(self, mw, Qt.WindowType.Window)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.mw = mw
|
|
|
|
self.model = model
|
|
|
|
self.frm = aqt.forms.changemap.Ui_ChangeMap()
|
|
|
|
self.frm.setupUi(self)
|
2021-01-07 05:24:49 +01:00
|
|
|
disable_help_button(self)
|
2012-12-21 08:51:59 +01:00
|
|
|
n = 0
|
|
|
|
setCurrent = False
|
2019-12-23 01:34:10 +01:00
|
|
|
for field in self.model["flds"]:
|
2021-03-26 05:21:04 +01:00
|
|
|
item = QListWidgetItem(tr.importing_map_to(val=field["name"]))
|
2012-12-21 08:51:59 +01:00
|
|
|
self.frm.fields.addItem(item)
|
2019-12-23 01:34:10 +01:00
|
|
|
if current == field["name"]:
|
2012-12-21 08:51:59 +01:00
|
|
|
setCurrent = True
|
|
|
|
self.frm.fields.setCurrentRow(n)
|
|
|
|
n += 1
|
2021-03-26 04:48:26 +01:00
|
|
|
self.frm.fields.addItem(QListWidgetItem(tr.importing_map_to_tags()))
|
|
|
|
self.frm.fields.addItem(QListWidgetItem(tr.importing_ignore_field()))
|
2012-12-21 08:51:59 +01:00
|
|
|
if not setCurrent:
|
|
|
|
if current == "_tags":
|
|
|
|
self.frm.fields.setCurrentRow(n)
|
|
|
|
else:
|
2019-12-23 01:34:10 +01:00
|
|
|
self.frm.fields.setCurrentRow(n + 1)
|
2020-07-24 20:38:34 +02:00
|
|
|
self.field: Optional[str] = None
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def getField(self) -> str:
|
2021-10-05 02:01:45 +02:00
|
|
|
self.exec()
|
2012-12-21 08:51:59 +01:00
|
|
|
return self.field
|
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def accept(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
row = self.frm.fields.currentRow()
|
2019-12-23 01:34:10 +01:00
|
|
|
if row < len(self.model["flds"]):
|
|
|
|
self.field = self.model["flds"][row]["name"]
|
2012-12-21 08:51:59 +01:00
|
|
|
elif row == self.frm.fields.count() - 2:
|
|
|
|
self.field = "_tags"
|
|
|
|
else:
|
|
|
|
self.field = None
|
|
|
|
QDialog.accept(self)
|
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def reject(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.accept()
|
|
|
|
|
|
|
|
|
2020-03-06 05:36:05 +01:00
|
|
|
# called by importFile() when importing a mappable file like .csv
|
2021-02-02 15:00:29 +01:00
|
|
|
# ImportType = Union[Importer,AnkiPackageImporter, TextImporter]
|
|
|
|
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
class ImportDialog(QDialog):
|
2021-03-04 19:39:43 +01:00
|
|
|
_DEFAULT_FILE_DELIMITER = "\t"
|
|
|
|
|
2021-02-02 15:00:29 +01:00
|
|
|
def __init__(self, mw: AnkiQt, importer: Any) -> None:
|
2021-10-05 05:53:01 +02:00
|
|
|
QDialog.__init__(self, mw, Qt.WindowType.Window)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.mw = mw
|
|
|
|
self.importer = importer
|
|
|
|
self.frm = aqt.forms.importing.Ui_ImportDialog()
|
|
|
|
self.frm.setupUi(self)
|
2020-05-04 05:23:08 +02:00
|
|
|
qconnect(
|
2021-10-05 05:53:01 +02:00
|
|
|
self.frm.buttonBox.button(QDialogButtonBox.StandardButton.Help).clicked,
|
|
|
|
self.helpRequested,
|
2019-12-23 01:34:10 +01:00
|
|
|
)
|
2021-01-07 05:24:49 +01:00
|
|
|
disable_help_button(self)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.setupMappingFrame()
|
|
|
|
self.setupOptions()
|
|
|
|
self.modelChanged()
|
2013-04-15 06:46:07 +02:00
|
|
|
self.frm.autoDetect.setVisible(self.importer.needDelimiter)
|
2020-01-15 07:53:24 +01:00
|
|
|
gui_hooks.current_note_type_did_change.append(self.modelChanged)
|
2020-05-04 05:23:08 +02:00
|
|
|
qconnect(self.frm.autoDetect.clicked, self.onDelimiter)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.updateDelimiterButtonText()
|
2019-12-23 01:34:10 +01:00
|
|
|
self.frm.allowHTML.setChecked(self.mw.pm.profile.get("allowHTML", True))
|
2020-05-04 05:23:08 +02:00
|
|
|
qconnect(self.frm.importMode.currentIndexChanged, self.importModeChanged)
|
2019-12-23 01:34:10 +01:00
|
|
|
self.frm.importMode.setCurrentIndex(self.mw.pm.profile.get("importMode", 1))
|
2020-01-15 09:33:32 +01:00
|
|
|
self.frm.tagModified.setText(self.mw.pm.profile.get("tagModified", ""))
|
|
|
|
self.frm.tagModified.setCol(self.mw.col)
|
2014-02-22 11:30:32 +01:00
|
|
|
# import button
|
2021-03-26 04:48:26 +01:00
|
|
|
b = QPushButton(tr.actions_import())
|
2021-10-05 05:53:01 +02:00
|
|
|
self.frm.buttonBox.addButton(b, QDialogButtonBox.ButtonRole.AcceptRole)
|
2021-10-05 02:01:45 +02:00
|
|
|
self.exec()
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def setupOptions(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.model = self.mw.col.models.current()
|
|
|
|
self.modelChooser = aqt.modelchooser.ModelChooser(
|
2019-12-23 01:34:10 +01:00
|
|
|
self.mw, self.frm.modelArea, label=False
|
|
|
|
)
|
|
|
|
self.deck = aqt.deckchooser.DeckChooser(self.mw, self.frm.deckArea, label=False)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def modelChanged(self, unused: Any = None) -> None:
|
2021-08-04 04:01:28 +02:00
|
|
|
self.importer.model = self.mw.col.models.current()
|
2012-12-21 08:51:59 +01:00
|
|
|
self.importer.initMapping()
|
|
|
|
self.showMapping()
|
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def onDelimiter(self) -> None:
|
2021-03-04 19:39:43 +01:00
|
|
|
# Open a modal dialog to enter an delimiter
|
2022-11-24 11:18:57 +01:00
|
|
|
# Todo/Idea Constrain the maximum width, so it doesn't take up that much screen space
|
2021-03-04 19:39:43 +01:00
|
|
|
delim, ok = getText(
|
2021-03-26 04:48:26 +01:00
|
|
|
tr.importing_by_default_anki_will_detect_the(),
|
2021-03-04 19:39:43 +01:00
|
|
|
self,
|
|
|
|
help=HelpPage.IMPORTING,
|
2019-12-23 01:34:10 +01:00
|
|
|
)
|
|
|
|
|
2021-03-04 19:39:43 +01:00
|
|
|
# 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
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2021-03-04 19:39:43 +01:00
|
|
|
delim = delim if len(delim) > 0 else self._DEFAULT_FILE_DELIMITER
|
|
|
|
delim = delim.replace("\\t", "\t") # un-escape it
|
|
|
|
if len(delim) > 1:
|
|
|
|
showWarning(
|
2021-03-26 04:48:26 +01:00
|
|
|
tr.importing_multicharacter_separators_are_not_supported_please()
|
2021-03-04 19:39:43 +01:00
|
|
|
)
|
|
|
|
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
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def updateDelimiterButtonText(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.importer.needDelimiter:
|
|
|
|
return
|
|
|
|
if self.importer.delimiter:
|
|
|
|
d = self.importer.delimiter
|
|
|
|
else:
|
|
|
|
d = self.importer.dialect.delimiter
|
|
|
|
if d == "\t":
|
2021-03-26 04:48:26 +01:00
|
|
|
d = tr.importing_tab()
|
2012-12-21 08:51:59 +01:00
|
|
|
elif d == ",":
|
2021-03-26 04:48:26 +01:00
|
|
|
d = tr.importing_comma()
|
2012-12-21 08:51:59 +01:00
|
|
|
elif d == " ":
|
2021-03-26 04:48:26 +01:00
|
|
|
d = tr.studying_space()
|
2012-12-21 08:51:59 +01:00
|
|
|
elif d == ";":
|
2021-03-26 04:48:26 +01:00
|
|
|
d = tr.importing_semicolon()
|
2012-12-21 08:51:59 +01:00
|
|
|
elif d == ":":
|
2021-03-26 04:48:26 +01:00
|
|
|
d = tr.importing_colon()
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2016-05-12 06:45:35 +02:00
|
|
|
d = repr(d)
|
2021-03-26 05:21:04 +01:00
|
|
|
txt = tr.importing_fields_separated_by(val=d)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.frm.autoDetect.setText(txt)
|
2017-02-13 13:12:19 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def accept(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.importer.mapping = self.mapping
|
|
|
|
if not self.importer.mappingOk():
|
2021-03-26 04:48:26 +01:00
|
|
|
showWarning(tr.importing_the_first_field_of_the_note())
|
2012-12-21 08:51:59 +01:00
|
|
|
return
|
|
|
|
self.importer.importMode = self.frm.importMode.currentIndex()
|
2019-12-23 01:34:10 +01:00
|
|
|
self.mw.pm.profile["importMode"] = self.importer.importMode
|
2012-12-21 08:51:59 +01:00
|
|
|
self.importer.allowHTML = self.frm.allowHTML.isChecked()
|
2019-12-23 01:34:10 +01:00
|
|
|
self.mw.pm.profile["allowHTML"] = self.importer.allowHTML
|
2020-01-15 09:33:32 +01:00
|
|
|
self.importer.tagModified = self.frm.tagModified.text()
|
2020-01-02 15:01:44 +01:00
|
|
|
self.mw.pm.profile["tagModified"] = self.importer.tagModified
|
2021-06-04 12:37:45 +02:00
|
|
|
self.mw.col.set_aux_notetype_config(
|
2021-08-04 04:01:28 +02:00
|
|
|
self.importer.model["id"], "lastDeck", self.deck.selected_deck_id
|
2021-06-04 12:37:45 +02:00
|
|
|
)
|
2021-08-04 04:01:28 +02:00
|
|
|
self.mw.col.models.save(self.importer.model, updateReqs=False)
|
2020-05-31 03:24:33 +02:00
|
|
|
self.mw.progress.start()
|
2020-03-06 05:36:05 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def on_done(future: Future) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.mw.progress.finish()
|
2020-03-06 05:36:05 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
future.result()
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
showUnicodeWarning()
|
|
|
|
return
|
|
|
|
except Exception as e:
|
2021-03-26 04:48:26 +01:00
|
|
|
msg = f"{tr.importing_failed_debug_info()}\n"
|
2020-03-06 05:36:05 +01:00
|
|
|
err = repr(str(e))
|
|
|
|
if "1-character string" in err:
|
|
|
|
msg += err
|
|
|
|
elif "invalidTempFolder" in err:
|
|
|
|
msg += self.mw.errorHandler.tempFolderMsg()
|
|
|
|
else:
|
|
|
|
msg += traceback.format_exc()
|
|
|
|
showText(msg)
|
|
|
|
return
|
|
|
|
else:
|
2021-03-26 04:48:26 +01:00
|
|
|
txt = f"{tr.importing_importing_complete()}\n"
|
2020-03-06 05:36:05 +01:00
|
|
|
if self.importer.log:
|
|
|
|
txt += "\n".join(self.importer.log)
|
|
|
|
self.close()
|
2021-03-22 02:26:49 +01:00
|
|
|
showText(txt, plain_text_edit=True)
|
2020-03-06 05:36:05 +01:00
|
|
|
self.mw.reset()
|
|
|
|
|
|
|
|
self.mw.taskman.run_in_background(self.importer.run, on_done)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def setupMappingFrame(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
# qt seems to have a bug with adding/removing from a grid, so we add
|
|
|
|
# to a separate object and add/remove that instead
|
|
|
|
self.frame = QFrame(self.frm.mappingArea)
|
|
|
|
self.frm.mappingArea.setWidget(self.frame)
|
|
|
|
self.mapbox = QVBoxLayout(self.frame)
|
2019-12-23 01:34:10 +01:00
|
|
|
self.mapbox.setContentsMargins(0, 0, 0, 0)
|
2021-02-01 13:08:56 +01:00
|
|
|
self.mapwidget: Optional[QWidget] = None
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def hideMapping(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.frm.mappingGroup.hide()
|
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def showMapping(
|
|
|
|
self, keepMapping: bool = False, hook: Optional[Callable] = None
|
|
|
|
) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
if hook:
|
|
|
|
hook()
|
|
|
|
if not keepMapping:
|
|
|
|
self.mapping = self.importer.mapping
|
|
|
|
self.frm.mappingGroup.show()
|
|
|
|
assert self.importer.fields()
|
|
|
|
# set up the mapping grid
|
|
|
|
if self.mapwidget:
|
|
|
|
self.mapbox.removeWidget(self.mapwidget)
|
|
|
|
self.mapwidget.deleteLater()
|
|
|
|
self.mapwidget = QWidget()
|
|
|
|
self.mapbox.addWidget(self.mapwidget)
|
|
|
|
self.grid = QGridLayout(self.mapwidget)
|
|
|
|
self.mapwidget.setLayout(self.grid)
|
2019-12-23 01:34:10 +01:00
|
|
|
self.grid.setContentsMargins(3, 3, 3, 3)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.grid.setSpacing(6)
|
Move away from Bazel (#2202)
(for upgrading users, please see the notes at the bottom)
Bazel brought a lot of nice things to the table, such as rebuilds based on
content changes instead of modification times, caching of build products,
detection of incorrect build rules via a sandbox, and so on. Rewriting the build
in Bazel was also an opportunity to improve on the Makefile-based build we had
prior, which was pretty poor: most dependencies were external or not pinned, and
the build graph was poorly defined and mostly serialized. It was not uncommon
for fresh checkouts to fail due to floating dependencies, or for things to break
when trying to switch to an older commit.
For day-to-day development, I think Bazel served us reasonably well - we could
generally switch between branches while being confident that builds would be
correct and reasonably fast, and not require full rebuilds (except on Windows,
where the lack of a sandbox and the TS rules would cause build breakages when TS
files were renamed/removed).
Bazel achieves that reliability by defining rules for each programming language
that define how source files should be turned into outputs. For the rules to
work with Bazel's sandboxing approach, they often have to reimplement or
partially bypass the standard tools that each programming language provides. The
Rust rules call Rust's compiler directly for example, instead of using Cargo,
and the Python rules extract each PyPi package into a separate folder that gets
added to sys.path.
These separate language rules allow proper declaration of inputs and outputs,
and offer some advantages such as caching of build products and fine-grained
dependency installation. But they also bring some downsides:
- The rules don't always support use-cases/platforms that the standard language
tools do, meaning they need to be patched to be used. I've had to contribute a
number of patches to the Rust, Python and JS rules to unblock various issues.
- The dependencies we use with each language sometimes make assumptions that do
not hold in Bazel, meaning they either need to be pinned or patched, or the
language rules need to be adjusted to accommodate them.
I was hopeful that after the initial setup work, things would be relatively
smooth-sailing. Unfortunately, that has not proved to be the case. Things
frequently broke when dependencies or the language rules were updated, and I
began to get frustrated at the amount of Anki development time I was instead
spending on build system upkeep. It's now about 2 years since switching to
Bazel, and I think it's time to cut losses, and switch to something else that's
a better fit.
The new build system is based on a small build tool called Ninja, and some
custom Rust code in build/. This means that to build Anki, Bazel is no longer
required, but Ninja and Rust need to be installed on your system. Python and
Node toolchains are automatically downloaded like in Bazel.
This new build system should result in faster builds in some cases:
- Because we're using cargo to build now, Rust builds are able to take advantage
of pipelining and incremental debug builds, which we didn't have with Bazel.
It's also easier to override the default linker on Linux/macOS, which can
further improve speeds.
- External Rust crates are now built with opt=1, which improves performance
of debug builds.
- Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript
compiler. This results in faster builds, by deferring typechecking to test/check
time, and by allowing more work to happen in parallel.
As an example of the differences, when testing with the mold linker on Linux,
adding a new message to tags.proto (which triggers a recompile of the bulk of
the Rust and TypeScript code) results in a compile that goes from about 22s on
Bazel to about 7s in the new system. With the standard linker, it's about 9s.
Some other changes of note:
- Our Rust workspace now uses cargo-hakari to ensure all packages agree on
available features, preventing unnecessary rebuilds.
- pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge
source files and generated files into a single folder for running. By telling
VSCode about the extra search path, code completion now works with generated
files without needing to symlink them into the source folder.
- qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py.
Instead, the generated files are now placed in a separate _aqt package that's
added to the path.
- ts/lib is now exposed as @tslib, so the source code and generated code can be
provided under the same namespace without a merging step.
- MyPy and PyLint are now invoked once for the entire codebase.
- dprint will be used to format TypeScript/json files in the future instead of
the slower prettier (currently turned off to avoid causing conflicts). It can
automatically defer to prettier when formatting Svelte files.
- svelte-check is now used for typechecking our Svelte code, which revealed a
few typing issues that went undetected with the old system.
- The Jest unit tests now work on Windows as well.
If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes:
- please remove node_modules and .bazel
- install rustup (https://rustup.rs/)
- install rsync if not already installed (on windows, use pacman - see docs/windows.md)
- install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and
place on your path, or from your distro/homebrew if it's 1.10+)
- update .vscode/settings.json from .vscode.dist
2022-11-27 06:24:20 +01:00
|
|
|
for num in range(len(self.mapping)): # pylint: disable=consider-using-enumerate
|
2021-03-26 05:21:04 +01:00
|
|
|
text = tr.importing_field_of_file_is(val=num + 1)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.grid.addWidget(QLabel(text), num, 0)
|
|
|
|
if self.mapping[num] == "_tags":
|
2021-03-26 04:48:26 +01:00
|
|
|
text = tr.importing_mapped_to_tags()
|
2012-12-21 08:51:59 +01:00
|
|
|
elif self.mapping[num]:
|
2021-03-26 05:21:04 +01:00
|
|
|
text = tr.importing_mapped_to(val=self.mapping[num])
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2021-03-26 04:48:26 +01:00
|
|
|
text = tr.importing_ignored()
|
2012-12-21 08:51:59 +01:00
|
|
|
self.grid.addWidget(QLabel(text), num, 1)
|
2021-03-26 04:48:26 +01:00
|
|
|
button = QPushButton(tr.importing_change())
|
2012-12-21 08:51:59 +01:00
|
|
|
self.grid.addWidget(button, num, 2)
|
2020-05-04 05:23:08 +02:00
|
|
|
qconnect(button.clicked, lambda _, s=self, n=num: s.changeMappingNum(n))
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-02 15:00:29 +01:00
|
|
|
def changeMappingNum(self, n: int) -> None:
|
2021-08-04 04:01:28 +02:00
|
|
|
f = ChangeMap(self.mw, self.importer.model, self.mapping[n]).getField()
|
2012-12-21 08:51:59 +01:00
|
|
|
try:
|
|
|
|
# make sure we don't have it twice
|
|
|
|
index = self.mapping.index(f)
|
|
|
|
self.mapping[index] = None
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
self.mapping[n] = f
|
|
|
|
if getattr(self.importer, "delimiter", False):
|
|
|
|
self.savedDelimiter = self.importer.delimiter
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def updateDelim() -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.importer.delimiter = self.savedDelimiter
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
self.showMapping(hook=updateDelim, keepMapping=True)
|
|
|
|
else:
|
|
|
|
self.showMapping(keepMapping=True)
|
|
|
|
|
2020-01-15 22:41:23 +01:00
|
|
|
def reject(self) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.modelChooser.cleanup()
|
2018-03-01 05:20:30 +01:00
|
|
|
self.deck.cleanup()
|
2020-01-15 07:53:24 +01:00
|
|
|
gui_hooks.current_note_type_did_change.remove(self.modelChanged)
|
2012-12-21 08:51:59 +01:00
|
|
|
QDialog.reject(self)
|
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def helpRequested(self) -> None:
|
2021-01-25 14:45:47 +01:00
|
|
|
openHelp(HelpPage.IMPORTING)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2021-02-02 15:00:29 +01:00
|
|
|
def importModeChanged(self, newImportMode: int) -> None:
|
2020-01-03 07:32:44 +01:00
|
|
|
if newImportMode == 0:
|
2020-01-15 09:33:32 +01:00
|
|
|
self.frm.tagModified.setEnabled(True)
|
2020-01-03 07:32:44 +01:00
|
|
|
else:
|
2020-01-15 09:33:32 +01:00
|
|
|
self.frm.tagModified.setEnabled(False)
|
2020-01-03 07:32:44 +01:00
|
|
|
|
2013-05-03 14:29:25 +02:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def showUnicodeWarning() -> None:
|
2013-05-03 14:29:25 +02:00
|
|
|
"""Shorthand to show a standard warning."""
|
2021-03-26 04:48:26 +01:00
|
|
|
showWarning(tr.importing_selected_file_was_not_in_utf8())
|
2013-05-03 14:29:25 +02:00
|
|
|
|
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def onImport(mw: AnkiQt) -> None:
|
2021-03-26 04:28:21 +01:00
|
|
|
filt = ";;".join([x[0] for x in importing.importers(mw.col)])
|
2021-03-26 04:48:26 +01:00
|
|
|
file = getFile(mw, tr.actions_import(), None, key="import", filter=filt)
|
2012-12-21 08:51:59 +01:00
|
|
|
if not file:
|
|
|
|
return
|
2016-05-12 06:45:35 +02:00
|
|
|
file = str(file)
|
2018-09-27 03:35:21 +02:00
|
|
|
|
|
|
|
head, ext = os.path.splitext(file)
|
|
|
|
ext = ext.lower()
|
|
|
|
if ext == ".anki":
|
2021-03-26 04:48:26 +01:00
|
|
|
showInfo(tr.importing_anki_files_are_from_a_very())
|
2018-09-27 03:35:21 +02:00
|
|
|
return
|
|
|
|
elif ext == ".anki2":
|
2021-03-26 04:48:26 +01:00
|
|
|
showInfo(tr.importing_anki2_files_are_not_directly_importable())
|
2018-09-27 03:35:21 +02:00
|
|
|
return
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
importFile(mw, file)
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def importFile(mw: AnkiQt, file: str) -> None:
|
2019-03-04 02:22:40 +01:00
|
|
|
importerClass = None
|
2012-12-21 08:51:59 +01:00
|
|
|
done = False
|
2021-03-26 04:28:21 +01:00
|
|
|
for i in importing.importers(mw.col):
|
2012-12-21 08:51:59 +01:00
|
|
|
if done:
|
|
|
|
break
|
2019-03-04 08:03:43 +01:00
|
|
|
for mext in re.findall(r"[( ]?\*\.(.+?)[) ]", i[0]):
|
2021-02-11 01:09:06 +01:00
|
|
|
if file.endswith(f".{mext}"):
|
2019-03-04 02:22:40 +01:00
|
|
|
importerClass = i[1]
|
2012-12-21 08:51:59 +01:00
|
|
|
done = True
|
|
|
|
break
|
2019-03-04 02:22:40 +01:00
|
|
|
if not importerClass:
|
2012-12-21 08:51:59 +01:00
|
|
|
# if no matches, assume TSV
|
2021-03-26 04:28:21 +01:00
|
|
|
importerClass = importing.importers(mw.col)[0][1]
|
2019-03-04 02:22:40 +01:00
|
|
|
importer = importerClass(mw.col, file)
|
2012-12-21 08:51:59 +01:00
|
|
|
# need to show import dialog?
|
|
|
|
if importer.needMapper:
|
|
|
|
# make sure we can load the file first
|
|
|
|
mw.progress.start(immediate=True)
|
|
|
|
try:
|
|
|
|
importer.open()
|
2020-05-29 00:40:03 +02:00
|
|
|
mw.progress.finish()
|
2020-05-12 16:15:01 +02:00
|
|
|
diag = ImportDialog(mw, importer)
|
2012-12-21 08:51:59 +01:00
|
|
|
except UnicodeDecodeError:
|
2020-03-14 09:42:03 +01:00
|
|
|
mw.progress.finish()
|
2013-05-03 14:29:25 +02:00
|
|
|
showUnicodeWarning()
|
2012-12-21 08:51:59 +01:00
|
|
|
return
|
2016-05-12 06:45:35 +02:00
|
|
|
except Exception as e:
|
2020-03-14 09:42:03 +01:00
|
|
|
mw.progress.finish()
|
2013-10-20 03:57:42 +02:00
|
|
|
msg = repr(str(e))
|
2014-06-17 15:31:38 +02:00
|
|
|
if msg == "'unknownFormat'":
|
2021-03-26 04:48:26 +01:00
|
|
|
showWarning(tr.importing_unknown_file_format())
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2021-03-26 04:48:26 +01:00
|
|
|
msg = f"{tr.importing_failed_debug_info()}\n"
|
2016-05-12 06:45:35 +02:00
|
|
|
msg += str(traceback.format_exc())
|
2012-12-21 08:51:59 +01:00
|
|
|
showText(msg)
|
|
|
|
return
|
|
|
|
finally:
|
2020-05-12 16:15:01 +02:00
|
|
|
importer.close()
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2013-09-11 08:56:59 +02:00
|
|
|
# if it's an apkg/zip, first test it's a valid file
|
2021-03-26 04:28:21 +01:00
|
|
|
if isinstance(importer, AnkiPackageImporter):
|
2020-03-06 05:36:05 +01:00
|
|
|
# we need to ask whether to import/replace; if it's
|
|
|
|
# a colpkg file then the rest of the import process
|
|
|
|
# will happen in setupApkgImport()
|
2012-12-21 08:51:59 +01:00
|
|
|
if not setupApkgImport(mw, importer):
|
|
|
|
return
|
2020-03-06 05:36:05 +01:00
|
|
|
|
|
|
|
# importing non-colpkg files
|
2012-12-21 08:51:59 +01:00
|
|
|
mw.progress.start(immediate=True)
|
2020-03-06 05:38:35 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def on_done(future: Future) -> None:
|
2020-03-06 05:38:35 +01:00
|
|
|
mw.progress.finish()
|
2018-12-01 04:37:26 +01:00
|
|
|
try:
|
2020-03-06 05:38:35 +01:00
|
|
|
future.result()
|
|
|
|
except zipfile.BadZipfile:
|
|
|
|
showWarning(invalidZipMsg())
|
Add apkg import/export on backend (#1743)
* Add apkg export on backend
* Filter out missing media-paths at write time
* Make TagMatcher::new() infallible
* Gather export data instead of copying directly
* Revert changes to rslib/src/tags/
* Reuse filename_is_safe/check_filename_safe()
* Accept func to produce MediaIter in export_apkg()
* Only store file folder once in MediaIter
* Use temporary tables for gathering
export_apkg() now accepts a search instead of a deck id. Decks are
gathered according to the matched notes' cards.
* Use schedule_as_new() to reset cards
* ExportData → ExchangeData
* Ignore ascii case when filtering system tags
* search_notes_cards_into_table →
search_cards_of_notes_into_table
* Start on apkg importing on backend
* Fix due dates in days for apkg export
* Refactor import-export/package
- Move media and meta code into appropriate modules.
- Normalize/check for normalization when deserializing media entries.
* Add SafeMediaEntry for deserialized MediaEntries
* Prepare media based on checksums
- Ensure all existing media files are hashed.
- Hash incoming files during preparation to detect conflicts.
- Uniquify names of conflicting files with hash (not notetype id).
- Mark media files as used while importing notes.
- Finally copy used media.
* Handle encoding in `replace_media_refs()`
* Add trait to keep down cow boilerplate
* Add notetypes immediately instaed of preparing
* Move target_col into Context
* Add notes immediately instaed of preparing
* Note id, not guid of conflicting notes
* Add import_decks()
* decks_configs → deck_configs
* Add import_deck_configs()
* Add import_cards(), import_revlog()
* Use dyn instead of generic for media_fn
Otherwise, would have to pass None with type annotation in the default
case.
* Fix signature of import_apkg()
* Fix search_cards_of_notes_into_table()
* Test new functions in text.rs
* Add roundtrip test for apkg (stub)
* Keep source id of imported cards (or skip)
* Keep source ids of imported revlog (or skip)
* Try to keep source ids of imported notes
* Make adding notetype with id undoable
* Wrap apkg import in transaction
* Keep source ids of imported deck configs (or skip)
* Handle card due dates and original due/did
* Fix importing cards/revlog
Card ids are manually uniquified.
* Factor out card importing
* Refactor card and revlog importing
* Factor out card importing
Also handle missing parents .
* Factor out note importing
* Factor out media importing
* Maybe upgrade scheduler of apkg
* Fix parent deck gathering
* Unconditionally import static media
* Fix deck importing edge cases
Test those edge cases, and add some global test helpers.
* Test note importing
* Let import_apkg() take a progress func
* Expand roundtrip apkg test
* Use fat pointer to avoid propogating generics
* Fix progress_fn type
* Expose apkg export/import on backend
* Return note log when importing apkg
* Fix archived collection name on apkg import
* Add CollectionOpWithBackendProgress
* Fix wrong Interrupted Exception being checked
* Add ClosedCollectionOp
* Add note ids to log and strip HTML
* Update progress when checking incoming media too
* Conditionally enable new importing in GUI
* Fix all_checksums() for media import
Entries of deleted files are nulled, not removed.
* Make apkg exporting on backend abortable
* Return number of notes imported from apkg
* Fix exception printing for QueryOp as well
* Add QueryOpWithBackendProgress
Also support backend exporting progress.
* Expose new apkg and colpkg exporting
* Open transaction in insert_data()
Was slowing down exporting by several orders of magnitude.
* Handle zstd-compressed apkg
* Add legacy arg to ExportAnkiPackage
Currently not exposed on the frontend
* Remove unused import in proto file
* Add symlink for typechecking of import_export_pb2
* Avoid kwargs in pb message creation, so typechecking is not lost
Protobuf's behaviour is rather subtle and I had to dig through the docs
to figure it out: set a field on a submessage to automatically assign
the submessage to the parent, or call SetInParent() to persist a default
version of the field you specified.
* Avoid re-exporting protobuf msgs we only use internally
* Stop after one test failure
mypy often fails much faster than pylint
* Avoid an extra allocation when extracting media checksums
* Update progress after prepare_media() finishes
Otherwise the bulk of the import ends up being shown as "Checked: 0"
in the progress window.
* Show progress of note imports
Note import is the slowest part, so showing progress here makes the UI
feel more responsive.
* Reset filtered decks at import time
Before this change, filtered decks exported with scheduling remained
filtered on import, and maybe_remove_from_filtered_deck() moved cards
into them as their home deck, leading to errors during review.
We may still want to provide a way to preserve filtered decks on import,
but to do that we'll need to ensure we don't rewrite the home decks of
cards, and we'll need to ensure the home decks are included as part of
the import (or give an error if they're not).
https://github.com/ankitects/anki/pull/1743/files#r839346423
* Fix a corner-case where due dates were shifted by a day
This issue existed in the old Python code as well. We need to include
the user's UTC offset in the exported file, or days_elapsed falls back
on the v1 cutoff calculation, which may be a day earlier or later than
the v2 calculation.
* Log conflicting note in remapped nt case
* take_fields() → into_fields()
* Alias `[u8; 20]` with `Sha1Hash`
* Truncate logged fields
* Rework apkg note import tests
- Use macros for more helpful errors.
- Split monolith into unit tests.
- Fix some unknown error with the previous test along the way.
(Was failing after 969484de4388d225c9f17d94534b3ba0094c3568.)
* Fix sorting of imported decks
Also adjust the test, so it fails without the patch. It was only passing
before, because the parent deck happened to come before the
inconsistently capitalised child alphabetically. But we want all parent
decks to be imported before their child decks, so their children can
adopt their capitalisation.
* target[_id]s → existing_card[_id]s
* export_collection_extracting_media() → ...
export_into_collection_file()
* target_already_exists→card_ordinal_already_exists
* Add search_cards_of_notes_into_table.sql
* Imrove type of apkg export selector/limit
* Remove redundant call to mod_schema()
* Parent tooltips to mw
* Fix a crash when truncating note text
String::truncate() is a bit of a footgun, and I've hit this before
too :-)
* Remove ExportLimit in favour of separate classes
* Remove OpWithBackendProgress and ClosedCollectionOp
Backend progress logic is now in ProgressManager. QueryOp can be used
for running on closed collection.
Also fix aborting of colpkg exports, which slipped through in #1817.
* Tidy up import log
* Avoid QDialog.exec()
* Default to excluding scheuling for deck list deck
* Use IncrementalProgress in whole import_export code
* Compare checksums when importing colpkgs
* Avoid registering changes if hashes are not needed
* ImportProgress::Collection → ImportProgress::File
* Make downgrading apkgs depend on meta version
* Generalise IncrementableProgress
And use it in entire import_export code instead.
* Fix type complexity lint
* Take count_map for IncrementableProgress::get_inner
* Replace import/export env with Shift click
* Accept all args from update() for backend progress
* Pass fields of ProgressUpdate explicitly
* Move update_interval into IncrementableProgress
* Outsource incrementing into Incrementor
* Mutate ProgressUpdate in progress_update callback
* Switch import/export legacy toggle to profile setting
Shift would have been nice, but the existing shortcuts complicate things.
If the user triggers an import with ctrl+shift+i, shift is unlikely to
have been released by the time our code runs, meaning the user accidentally
triggers the new code. We could potentially wait a while before bringing
up the dialog, but then we're forced to guess at how long it will take the
user to release the key.
One alternative would be to use alt instead of shift, but then we need to
trigger our shortcut when that key is pressed as well, and it could
potentially cause a conflict with an add-on that already uses that
combination.
* Show extension in export dialog
* Continue to provide separate options for schema 11+18 colpkg export
* Default to colpkg export when using File>Export
* Improve appearance of combo boxes when switching between apkg/colpkg
+ Deal with long deck names
* Convert newlines to spaces when showing fields from import
Ensures each imported note appears on a separate line
* Don't separate total note count from the other summary lines
This may come down to personal preference, but I feel the other counts
are equally as important, and separating them feels like it makes it
a bit easier to ignore them.
* Fix 'deck not normal' error when importing a filtered deck for the 2nd time
* Fix [Identical] being shown on first import
* Revert "Continue to provide separate options for schema 11+18 colpkg export"
This reverts commit 8f0b2c175f4794d642823b60414d142a12768441.
Will use a different approach
* Move legacy support into a separate exporter option; add to apkg export
* Adjust 'too new' message to also apply to .apkg import case
* Show a better message when attempting to import new apkg into old code
Previously the user could end seeing a message like:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte
Unfortunately we can't retroactively fix this for older clients.
* Hide legacy support option in older exporting screen
* Reflect change from paths to fnames in type & name
* Make imported decks normal at once
Then skip special casing in update_deck(). Also skip updating
description if new one is empty.
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
2022-05-02 13:12:46 +02:00
|
|
|
except MediaMapInvalid:
|
|
|
|
showWarning(
|
|
|
|
"Unable to read file. It probably requires a newer version of Anki to import."
|
|
|
|
)
|
2021-07-08 02:32:27 +02:00
|
|
|
except V2ImportIntoV1:
|
|
|
|
showWarning(
|
|
|
|
"""\
|
|
|
|
To import this deck, please click the Update button at the top of the deck list, then try again."""
|
|
|
|
)
|
2020-03-06 05:38:35 +01:00
|
|
|
except Exception as e:
|
|
|
|
err = repr(str(e))
|
|
|
|
if "invalidFile" in err:
|
2021-03-26 04:48:26 +01:00
|
|
|
msg = tr.importing_invalid_file_please_restore_from_backup()
|
2020-03-06 05:38:35 +01:00
|
|
|
showWarning(msg)
|
|
|
|
elif "invalidTempFolder" in err:
|
|
|
|
showWarning(mw.errorHandler.tempFolderMsg())
|
|
|
|
elif "readonly" in err:
|
2021-03-26 04:48:26 +01:00
|
|
|
showWarning(tr.importing_unable_to_import_from_a_readonly())
|
2020-03-06 05:38:35 +01:00
|
|
|
else:
|
2021-03-26 04:48:26 +01:00
|
|
|
msg = f"{tr.importing_failed_debug_info()}\n"
|
2022-01-02 00:47:44 +01:00
|
|
|
traceback.print_exc(file=sys.stdout)
|
2021-07-24 12:05:32 +02:00
|
|
|
msg += str(e)
|
2020-03-06 05:38:35 +01:00
|
|
|
showText(msg)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2020-03-06 05:38:35 +01:00
|
|
|
log = "\n".join(importer.log)
|
|
|
|
if "\n" not in log:
|
|
|
|
tooltip(log)
|
|
|
|
else:
|
2021-02-02 06:47:51 +01:00
|
|
|
showText(log, plain_text_edit=True)
|
2020-03-06 05:38:35 +01:00
|
|
|
|
|
|
|
mw.reset()
|
|
|
|
|
|
|
|
mw.taskman.run_in_background(importer.run, on_done)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2021-02-01 14:28:21 +01:00
|
|
|
def invalidZipMsg() -> str:
|
2021-03-26 04:48:26 +01:00
|
|
|
return tr.importing_this_file_does_not_appear_to()
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2014-06-28 22:55:01 +02:00
|
|
|
|
2021-02-01 13:08:56 +01:00
|
|
|
def setupApkgImport(mw: AnkiQt, importer: AnkiPackageImporter) -> bool:
|
2012-12-21 08:51:59 +01:00
|
|
|
base = os.path.basename(importer.file).lower()
|
2019-12-23 01:34:10 +01:00
|
|
|
full = (
|
|
|
|
(base == "collection.apkg")
|
|
|
|
or re.match("backup-.*\\.apkg", base)
|
|
|
|
or base.endswith(".colpkg")
|
|
|
|
)
|
2012-12-21 08:51:59 +01:00
|
|
|
if not full:
|
|
|
|
# adding
|
|
|
|
return True
|
2022-06-01 12:26:16 +02:00
|
|
|
ColpkgImporter.do_import(mw, importer.file)
|
2021-02-01 13:08:56 +01:00
|
|
|
return False
|