Partially completes #1068, and will allow mobile clients to drop
their separate diff-match-patch imports. Does not yet try to handle
case folding or combining-char stripping, and leaves some of the outer
HTML wrapping up to the frontend for now.
The logic for rendering the provided string has changed: missing chars
are now only inserted if they follow a correct section, and the original
text is shown instead of hyphens. This is an experiment, and can be
changed if it's not well received.
* Add ExportFormat enum and use it in Exporter classes
* Add exporter hooks and call them from new exporters
* Fix filter argument order and add example to docstring
* Refactor: Avoid repeating ExportFormat
* Rename Options to ExportOptions for better namespacing in add-ons
* Add simplified legacy exporter hooks
Allows add-ons to be notified of exports when legacy handlers are enabled, without the need for monkey-patches.
* Switch away from ExportFormat, opting to pass exporter class/instance instead
* Consistently use exporter instances rather than classes
* Revert Exportdialog.exporters rename
* Revert "Revert Exportdialog.exporters rename"
This reverts commit 357a3aa85928cce702f06b88da5187d2b45cd22b.
* added option to load the last loaded profile
* add formatting changes for tests
* fix comments - integrate as new functionality rather than as an option, fix type hinting and remove bug if profile is deleted
on_all_or_selected_rows_changed() unsets the editor note, but it is
called too late - by that time the note has already been deleted, and
the editor sometimes tries to save the deleted note due to an unfocus/
key timeout.
https://forums.ankiweb.net/t/two-suppr-lead-to-an-empty-warning/20860
Will need to check that this does not regression when #1691 is merged.
* Allow webviews to opt in to default D&D handling
* Remove redundant webview.js include
* Block default drag & drop behavior in reviewing screens
* Fix mypy error
* Fix footer moving upwards
* Fix column detection
Was broken because escaped line breaks were not considered.
Also removes delimiter detection on `#columns:` line. User must use tabs
or set delimiter beforehand.
* Add CSV preview
* Parse `#tags column:`
* Optionally export deck and notetype with CSV
* Avoid clones in CSV export
* Prevent bottom of page appearing under footer (dae)
* Increase padding to 1em (dae)
With 0.5em, when a vertical scrollbar is shown, it sits right next to
the right edge of the content, making it look like there's no right
margin.
* Experimental changes to make table fit+scroll (dae)
- limit individual cells to 15em, and show ellipses when truncated
- limit total table width to body width, so that inner table is shown
with scrollbar
- use class rather than id - ids are bad practice in Svelte components,
as more than one may be displayed on a single page
* Skip importing foreign notes with filtered decks
Were implicitly imported into the default deck before.
Also some refactoring to fetch deck ids and names beforehand.
* Hide spacer below hidden field mapping
* Fix guid being replaced when updating note
* Fix dupe identity check
Canonify tags before checking if dupe is identical, but only add update
tags later if appropriate.
* Fix deck export for notes with missing card 1
* Fix note lines starting with `#`
csv crate doesn't support escaping a leading comment char. :(
* Support import/export of guids
* Strip HTML from preview rows
* Fix initially set deck if current is filtered
* Make isHtml toggle reactive
* Fix `html_to_text_line()` stripping sound names
* Tweak export option labels
* Switch to patched rust-csv fork
Fixes writing lines starting with `#`, so revert 5ece10ad05f331.
* List column options with first column field
* Fix flag for exports with HTML stripped
* update get_linux_dark_mode to use freedesktop.org standard
* Update CONTRIBUTORS
* run formatter
* Update CONTRIBUTORS
* allow for multiple dark mode detection strategies on Linux
* string -> str
* update docstring
* Update CONTRIBUTORS
* Add crate csv
* Add start of csv importing on backend
* Add Menomosyne serializer
* Add csv and json importing on backend
* Add plaintext importing on frontend
* Add csv metadata extraction on backend
* Add csv importing with GUI
* Fix missing dfa file in build
Added compile_data_attr, then re-ran cargo/update.py.
* Don't use doubly buffered reader in csv
* Escape HTML entities if CSV is not HTML
Also use name 'is_html' consistently.
* Use decimal number as foreign ease (like '2.5')
* ForeignCard.ivl → ForeignCard.interval
* Only allow fixed set of CSV delimiters
* Map timestamp of ForeignCard to native due time
* Don't trim CSV records
* Document use of empty strings for defaults
* Avoid creating CardGenContexts for every note
This requires CardGenContext to be generic, so it works both with an
owned and borrowed notetype.
* Show all accepted file types in import file picker
* Add import_json_file()
* factor → ease_factor
* delimter_from_value → delimiter_from_value
* Map columns to fields, not the other way around
* Fallback to current config for csv metadata
* Add start of new import csv screen
* Temporary fix for compilation issue on Linux/Mac
* Disable jest bazel action for import-csv
Jest fails with an error code if no tests are available, but this would
not be noticable on Windows as Jest is not run there.
* Fix field mapping issue
* Revert "Temporary fix for compilation issue on Linux/Mac"
This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82.
* Add HtmlSwitch and move Switch to components
* Fix spacing and make selectors consistent
* Fix shortcut tooltip
* Place import button at the top with path
* Fix meta column indices
* Remove NotetypeForString
* Fix queue and type of foreign cards
* Support different dupe resolution strategies
* Allow dupe resolution selection when importing CSV
* Test import of unnormalized text
Close #1863.
* Fix logging of foreign notes
* Implement CSV exports
* Use db_scalar() in notes_table_len()
* Rework CSV metadata
- Notetypes and decks are either defined by a global id or by a column.
- If a notetype id is provided, its field map must also be specified.
- If a notetype column is provided, fields are now mapped by index
instead of name at import time. So the first non-meta column is used for
the first field of every note, regardless of notetype. This makes
importing easier and should improve compatiblity with files without a
notetype column.
- Ensure first field can be mapped to a column.
- Meta columns must be defined as `#[meta name]:[column index]` instead
of in the `#columns` tag.
- Column labels contain the raw names defined by the file and must be
prettified by the frontend.
* Adjust frontend to new backend column mapping
* Add force flags for is_html and delimiter
* Detect if CSV is HTML by field content
* Update dupe resolution labels
* Simplify selectors
* Fix coalescence of oneofs in TS
* Disable meta columns from selection
Plus a lot of refactoring.
* Make import button stick to the bottom
* Write delimiter and html flag into csv
* Refetch field map after notetype change
* Fix log labels for csv import
* Log notes whose deck/notetype was missing
* Fix hiding of empty log queues
* Implement adding tags to all notes of a csv
* Fix dupe resolution not being set in log
* Implement adding tags to updated notes of a csv
* Check first note field is not empty
* Temporary fix for build on Linux/Mac
* Fix inverted html check (dae)
* Remove unused ftl string
* Delimiter → Separator
* Remove commented-out line
* Don't accept .json files
* Tweak tag ftl strings
* Remove redundant blur call
* Strip sound and add spaces in csv export
* Export HTML by default
* Fix unset deck in Mnemosyne import
Also accept both numbers and strings for notetypes and decks in JSON.
* Make DupeResolution::Update the default
* Fix missing dot in extension
* Make column indices 1-based
* Remove StickContainer from TagEditor
Fixes line breaking, border and z index on ImportCsvPage.
* Assign different key combos to tag editors
* Log all updated duplicates
Add a log field for the true number of found notes.
* Show identical notes as skipped
* Split tag-editor into separate ts module (dae)
* Add progress for CSV export
* Add progress for text import
* Tidy-ups after tag-editor split (dae)
- import-csv no longer depends on editor
- remove some commented lines
A 10ms delay was chosen as it tends to result in the progress window
appearing immediately when clicking into the unfocused window, preventing
another action from being started before the progress window appears.
Closes#1873
As mentioned on #1879, the dialog.deleteLater() call appears to be
causing crashes on some systems on Qt 6.3. Explicitly destroying the page
prior to the containing webview appears to work around the issue.
In v3, it's more informative to show the count of child decks separately,
since increasing the limit of the current deck does not increase the limits
of child decks. When we rework the decks list in the future, a tooltip
will hopefully provide an easier way for users to see where cards are
available, and where limits are being applied.
Closes#1868
Probably a race condition. `.get_row()` is not a reliable check for card
or note existence, because it returns from an outdated cache,
if the backend is currently blocked.
* Remove custom config and use tex-chtml-full for editor Mathjax
* Add mathjax package in /ts
* Share mathjax config between tex-svg and tex-chtml
* Use "[+]" in Mathjax config again
* Remove mention of MathJaxReady
* Satisfy eslint
The old `media_files_did_export` hook has been kept around for use with
the legacy apkg exporter (an add-on uses it), and a new
`legacy_export_progress` hook has been added so we can get progress
from the new colpkg exporter until we move over fully to the new code.
* 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>
This change causes local links to unsupported formats like PDF to be
handled by _processUrls() instead of _processText, converting them to
correct hyperlinks in case they contain spaces.
* Scroll stats to top when exporting (#1114)
It's obviously a bit of a "hacky" solution, since it's slightly jarring for users to scroll down, click export, then find themselves all the way at the top again, but it's somewhat less confusing than wondering why your PDF is broken :-)
* Clarified comment in stats.py (#1114)
* Apply scrolling fix to new stats screen, not legacy stats (dae)
Also wait for JS callback before saving the PDF, as JS is executed
asynchronously.
Addresses #1777 by adding the `minimumContentsLength` property to the comboBox, which causes the size policy to not require expanding beyond that amount while still expanding if the user stretches the window manually.
Note that users who were previously experiencing large window widths due to the previous behaviour might see the same size again due the geometry being restored.
* Always enable manually installed add-ons
Ensures that manually installed add-ons are enabled after the installation, even if previously disabled.
Prevents scenarios where users could end up with no active add-on build (e.g. when switching between stable add-on builds distributed via AnkiWeb and betas distributed via GitHub).
* Improve type annotations
* Also enable disabled AnkiWeb add-ons upon interactive installation
Applies to add-ons that users actively install via their AnkiWeb ID. Updates are exempt, preserving whatever status add-ons were in.
* Prevent disabled add-ons from triggering conflicts
* Fix download_addons() not passing on force_enable argument (dae)
- Use a separate `gldriver6` file for configuring Qt6 so we don't
pick up old settings, or cause problems when switching back and forth.
- Default to OpenGL/auto instead of software, as that was what we
were using throughout the beta period.
- Try to detect driver failure on startup. Untested.
- Hide the selector in the preferences again, as if Anki is unable
to automatically switch drivers, the user could change the setting
and then not be able to get back into Anki.
* First attempt at adding a directory for icons under //ts
* Fix image import
* Fix import order
* Add cloze button group
* Fix issue with toolbar.toolbar dynamically slottable
* Change tooltip for repeating cloze deletion
* Fix repeat cloze button not working on macOS (dae)
* TemplateSaveError -> CardTypeError
* Don't show success tooltip if export fails
* Attach help page to error
Show help link if export fails due to card type error.
* Add type (dae)
* Add shared show_exception() (dae)
- Use a shared routine for printing standard backend errors, so that
we can take advantage of the help links in eg. the card layout screen
as well.
- The truthiness check on help in showInfo() would have ignored the
enum 0 value.
- Close the exporting dialog on a documented failure as well
* Fix local variable help_page
* Add Deleted error and disable all bad browser rows
* Avoid error when opening the browse screen to a card with a missing note (dae)
* In cards mode, a missing note is NotFound, not Deleted (dae)
So we distinguish between referential integrity error, and explicit
deletion.
* Remove redundant try block
* Collection needs to be closed prior to backup even when not downgrading
* Backups -> BackupLimits
* Some improvements to backup_task
- backup_inner now returns the error instead of logging it, so that
the frontend can discover the issue when they await a backup (or create
another one)
- start_backup() was acquiring backup_task twice, and if another thread
started a backup between the two locks, the task could have been accidentally
overwritten without awaiting it
* Backups no longer require a collection close
- Instead of closing the collection, we ensure there is no active
transaction, and flush the WAL to disk. This means the undo history
is no longer lost on backup, which will be particularly useful if we
add a periodic backup in the future.
- Because a close is no longer required, backups are now achieved with
a separate command, instead of being included in CloseCollection().
- Full sync no longer requires an extra close+reopen step, and we now
wait for the backup to complete before proceeding.
- Create a backup before 'check db'
* Add File>Create Backup
https://forums.ankiweb.net/t/anki-mac-os-no-backup-on-sync/6157
* Defer checkpoint until we know we need it
When running periodic backups on a timer, we don't want to be fsync()ing
unnecessarily.
* Skip backup if modification time has not changed
We don't want the user leaving Anki open overnight, and coming back
to lots of identical backups.
* Periodic backups
Creates an automatic backup every 30 minutes if the collection has been
modified.
If there's a legacy checkpoint active, tries again 5 minutes later.
* Switch to a user-configurable backup duration
CreateBackup() now uses a simple force argument to determine whether
the user's limits should be respected or not, and only potentially
destructive ops (full download, check DB) override the user's configured
limit.
I considered having a separate limit for collection close and automatic
backups (eg keeping the previous 5 minute limit for collection close),
but that had two downsides:
- When the user closes their collection at the end of the day, they'd
get a recent backup. When they open the collection the next day, it
would get backed up again within 5 minutes, even though not much had
changed.
- Multiple limits are harder to communicate to users in the UI
Some remaining decisions I wasn't 100% sure about:
- If force is true but the collection has not been modified, the backup
will be skipped. If the user manually deleted their backups without
closing Anki, they wouldn't get a new one if the mtime hadn't changed.
- Force takes preference over the configured backup interval - should
we be ignored the user here, or take no backups at all?
Did a sneaky edit of the existing ftl string, as it hasn't been live
long.
* Move maybe_backup() into Collection
* Use a single method for manual and periodic backups
When manually creating a backup via the File menu, we no longer make
the user wait until the backup completes. As we continue waiting for
the backup in the background, if any errors occur, the user will get
notified about it fairly quickly.
* Show message to user if backup was skipped due to no changes
+ Don't incorrectly assert a backup will be created on force
* Add "automatic" to description
* Ensure we backup prior to importing colpkg if collection open
The backup doesn't happen when invoked from 'open backup' in the profile
screen, which matches Anki's previous behaviour. The user could
potentially clobber up to 30 minutes of their work if they exited to
the profile screen and restored a backup, but the alternative is we
create backups every time a backup is restored, which may happen a number
of times if the user is trying various ones. Or we could go back to a
separate throttle amount for this case, at the cost of more complexity.
* Remove the 0 special case on backup interval; minimum of 5 minutes
https://github.com/ankitects/anki/pull/1728#discussion_r830876833
* Write media files in chunks
* Test media file writing
* Add iter `ReadDirFiles`
* Remove ImportMediaError, fail fatally instead
Partially reverts commit f8ed4d89ba.
* Compare hashes of media files to be restored
* Improve `MediaCopier::copy()`
* Restore media files atomically with tempfile
* Make downgrade flag an enum
* Remove SchemaVersion::Latest in favour of Option
* Remove sha1 comparison again
* Remove unnecessary repr(u8) (dae)
* Fix legacy colpkg import; disable v3 import/export; add roundtrip test
The test has revealed we weren't decompressing the media files on v3
import. That's easy to fix, but means all files need decompressing
even when they already exist, which is not ideal - it would be better
to store size/checksum in the metadata instead.
* Switch media and meta to protobuf; re-enable v3 import/export
- Fixed media not being decompressed on import
- The uncompressed size and checksum is now included for each media
entry, so that we can quickly check if a given file needs to be extracted.
We're still just doing a naive size comparison on colpkg import at the
moment, but we may want to use a checksum in the future, and will need
a checksum for apkg imports.
- Checksums can't be efficiently encoded in JSON, so the media list
has been switched to protobuf to reduce the the space requirements.
- The meta file has been switched to protobuf as well, for consistency.
This will mean any colpkg files exported with beta7 will be
unreadable.
* Avoid integer version comparisons
* Re-enable v3 test
* Apply suggestions from code review
Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
* Add export_colpkg() method to Collection
More discoverable, and easier to call from unit tests
* Split import/export code out into separate folders
Currently colpkg/*.rs contain some routines that will be useful for
apkg import/export as well; in the future we can refactor them into a
separate file in the parent module.
* Return a proper error when media import fails
This tripped me up when writing the earlier unit test - I had called
the equivalent of import_colpkg()?, and it was returning a string error
that I didn't notice. In practice this should result in the same text
being shown in the UI, but just skips the tooltip.
* Automatically create media folder on import
* Move roundtrip test into separate file; check collection too
* Remove zstd version suffix
Prevents a warning shown each time Rust Analyzer is used to check the
code.
Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
Ideally this would have been in beta 6 :-) No add-ons appear to be
using customstudy.py/taglimit.py though, so it should hopefully not be
disruptive.
In the earlier custom study changes, we didn't get around to addressing
issue #1136. Now instead of trying to determine the maximum increase
to allow (which doesn't work correctly with nested decks), we just
present the total available to the user again, and let them decide. There's
plenty of room for improvement here still, but further work here might
be better done once we look into decoupling deck limits from deck presets.
Tags and available cards are fetched prior to showing the dialog now,
and will show a progress dialog if things take a while.
Tags are stored in an aux var now, so they don't inflate the deck
object size.
tools/mypy-watch now prints .py paths relative to the workspace root,
which makes it easy to click on them to jump to the relevant file/line
in VS Code.
* Add forget prompt with options
- Restore original position
- Reset reps and lapses
* Restore position when resetting for export
* Add config context to avoid passing keys
* Add routine to fetch defaults; use method-specific enum (dae)
* Keep original position by default (dae)
* Fix code completion for forget dialog (dae)
Needs to be a symbolic link to the generated file
* Add zstd dep
* Implement backend backup with zstd
* Implement backup thinning
* Write backup meta
* Use new file ending anki21b
* Asynchronously backup on collection close in Rust
* Revert "Add zstd dep"
This reverts commit 3fcb2141d2be15f907269d13275c41971431385c.
* Add zstd again
* Take backup col path from col struct
* Fix formatting
* Implement backup restoring on backend
* Normalize restored media file names
* Refactor `extract_legacy_data()`
A bit cumbersome due to borrowing rules.
* Refactor
* Make thinning calendar-based and gradual
* Consider last kept backups of previous stages
* Import full apkgs and colpkgs with backend
* Expose new backup settings
* Test `BackupThinner` and make it deterministic
* Mark backup_path when closing optional
* Delete leaky timer
* Add progress updates for restoring media
* Write restored collection to tempfile first
* Do collection compression in the background thread
This has us currently storing an uncompressed and compressed copy of
the collection in memory (not ideal), but means the collection can be
closed without waiting for compression to complete. On a large collection,
this takes a close and reopen from about 0.55s to about 0.07s. The old
backup code for comparison: about 0.35s for compression off, about
8.5s for zip compression.
* Use multithreading in zstd compression
On my system, this reduces the compression time of a large collection
from about 0.55s to 0.08s.
* Stream compressed collection data into zip file
* Tweak backup explanation
+ Fix incorrect tab order for ignore accents option
* Decouple restoring backup and full import
In the first case, no profile is opened, unless the new collection
succeeds to load.
In the second case, either the old collection is reloaded or the new one
is loaded.
* Fix number gap in Progress message
* Don't revert backup when media fails but report it
* Tweak error flow
* Remove native BackupLimits enum
* Fix type annotation
* Add thinning test for whole year
* Satisfy linter
* Await async backup to finish
* Move restart disclaimer out of backup tab
Should be visible regardless of the current tab.
* Write restored collection in chunks
* Refactor
* Write media in chunks and refactor
* Log error if removing file fails
* join_backup_task -> await_backup_completion
* Refactor backup.rs
* Refactor backup meta and collection extraction
* Fix wrong error being returned
* Call sync_all() on new collection
* Add ImportError
* Store logger in Backend, instead of creating one on demand
init_backend() accepts a Logger rather than a log file, to allow other
callers to customize the logger if they wish.
In the future we may want to explore using the tracing crate as an
alternative; it's a bit more ergonomic, as a logger doesn't need to be
passed around, and it plays more nicely with async code.
* Sync file contents prior to rename; sync folder after rename.
* Limit backup creation to once per 30 min
* Use zstd::stream::copy_decode
* Make importing abortable
* Don't revert if backup media is aborted
* Set throttle implicitly
* Change force flag to minimum_backup_interval
* Don't attempt to open folders on Windows
* Join last backup thread before starting new one
Also refactor.
* Disable auto sync and backup when restoring again
* Force backup on full download
* Include the reason why a media file import failed, and the file path
- Introduce a FileIoError that contains a string representation of
the underlying I/O error, and an associated path. There are a few
places in the code where we're currently manually including the filename
in a custom error message, and this is a step towards a more consistent
approach (but we may be better served with a more general approach in
the future similar to Anyhow's .context())
- Move the error message into importing.ftl, as it's a bit neater
when error messages live in the same file as the rest of the messages
associated with some functionality.
* Fix importing of media files
* Minor wording tweaks
* Save an allocation
I18n strings with replacements are already strings, so we can skip the
extra allocation. Not that it matters here at all.
* Terminate import if file missing from archive
If a third-party tool is creating invalid archives, the user should know
about it. This should be rare, so I did not attempt to make it
translatable.
* Skip multithreaded compression on small collections
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
* Load fields_web from fields.py if appropriate flag is set
* Add FieldsPage as entry for new fields view
* Pass mypy
* Fix pylint
* Fix fields_web in Qt5 (dae)
May not be related to the CI error, but required for compatibility
with Qt5.
md_in_html imports fine when done manually; it is likely PyOxidizer
has not instrumented import_module().
File "aqt.addons", line 631, in addonConfigHelp
File "markdown.core", line 386, in markdown
File "markdown.core", line 96, in __init__
File "markdown.core", line 123, in registerExtensions
File "markdown.core", line 162, in build_extension
File "importlib", line 127, in import_module
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'md_in_html'
The previous change in 1871b57663 failed
to consider the browser refreshing case, as reported here:
https://forums.ankiweb.net/t/anki-2-1-50-beta-3-4/17501/30
I previously attempted to solve this by having SetFlag skip the queue
rebuild, then mutating the captured mtimes in the queues. That didn't
work correctly when undoing, as the queue mutations weren't recorded.
This approach combines that attempt and the previous change: flag
setting is an undoable operation again, but does not change the card's
modification time, so it can be applied/undone without a queue build
being required. Instead of special-casing flag changes in the review
screen, we now just redraw the flag on changes.card, as any other card
op will have triggered a queue rebuild.
* Move Trigger into its own file
* Try implement HandlerList
* Implement new input handler and handler-list
* Use new refocus HandlerList in TextColorButton
* Fix TextColorButton on windows
* Move ColorPicker to editor-toolbar
* Change trigger behavior of overwriteSurround
* Fix mathjax-overlay flushCaret
* Insert image via bridgeCommand return value
* Fix invoking color picker with F8
* Have remove format work even when collapsed
* Satisfy formatter
* Insert media via callback resolved from python
* Replace print with web.eval
* Fix python formatting
* remove unused function (dae)
* Add progress.single_shot()
* Fix periodic garbage collection
* Properly cleanup mediasync timers
* Revert some replacements with `single_shot()`
These timers shouldn't fire if their widget is destroyed.
* Add timer docs explaining issues and alternatives
* Apply suggestions from code review
* Tweak docstrings
* Truncate long deck names to match AnkiWeb behavior
Prevent long deck name from obscuring deck stats in main deck browser - match behavior at https://ankiweb.net/decks/ for handling long deck names (truncate name)
* Fix formatting
* Update CONTRIBUTORS
Add myself to contributors list
* Clarify some comments
* Don't destructure insertion trigger
* Make superscript and subscript use domlib/surround
* Create new {Text,Highlight}ColorButton
* Use domlib/surround for textcolor
- However there's still a crucial bug, when you're breaking existing
colored span when unsurrounding, their color is not restored
* Add underline format to removeFormats
* Simplify type of ElementMatcher and ElementClearer for end users
* Add some comments for normalize-insertion-ranges
* Split normalize-insertion-ranges into remove-adjacent and remove-within
* Factor out find-remove from unsurround.ts
* Rename merge-mach, simplify remove-within
* Clarify some comments
* Refactor first reduce
* Refactor reduceRight
* Flatten functions in merge-ranges
* Move some functionality to merge-ranges and do not export
* Refactor merge-ranges
* Remove createInitialMergeMatch
* Finish refactoring of merge-ranges
* Refactor merge-ranges to minimal-ranges and add some unit testing
* Move more logic into text-node
* Remove most most of the logic from remove-adjacent
- remove-adjacent is still part of the "merging" logic, as it increases
the scope of the child node ranges
* Add some tests for edge cases
* Merge remove-adjacent logic into minimal-ranges
* Refactor unnecessary list destructuring
* Add some TODOs
* Put removing nodes and adding new nodes into sequence
* Refactor MatchResult to MatchType and return clear from matcher
* Inline surround/helpers
* Shorten name of param
* Add another edge case test
* Add an example where commonAncestorContainer != normalization level
* Fix bug in find-adjacent when find more than one nested nodes
* Allow comments for Along type
* Simplify find-adjacent by removing intermediate and/or curried functions
* Remove extend-adjacent
* Add more tests when find-adjacent finds by descension
* Fix find-adjacent descending into block-level elements
* Add clarifying comment to refusing to descend into block-level elements
* Move shifting logic into find-adjacent
* Rename file matcher to match-type
* Give a first implemention of TreeVertex
* Remove MatchType.ALONG
- findAdjacent now directly modifies the range
* Rename MatchType.MATCH into MatchType.REMOVE
* Implement a version of find-within that utilizies match-tree
* Turn child node range into a class
* Fix bug in new find-adjacent function
* Make all find-adjacent tests test for ranges
* Surrounding within farthestMatchingAncestor when available
* Fix an issue with negligable elements
- also rename "along" elements to "negligable"
* Add two TODOs to SurroundFormat interface
* Have a messy first implementation of the new tree-node algorithm
* Maintain whether formatting nodes are covered or within user selection
* Move covered and insideRange into TreeNode superclass
* Reimplement findAdjacent logic
* Add extension logic
* Add an evaluate method to nodes
* Introduce BlockNode
* Add a first evaluate implementation
* Add left shift and inner shift logic
* Implement SurroundFormatUser
* Allow pass in formatter, ascender and merger from outside
* Fix insideRange and covered switch-up
* Fix MatchNode.prototype.isAscendable
* Fix another switch-up of covered and insideRange...
* Remove a lot of old code
* Have surround functions only return the range
- I still cannot think of a good reason why we should return addedNodes
and removedNodes, except for testing.
* Create formatting-tree directory
* Create build-tree directory + Move find-above up to /domlib
* Remove range-anchors
* Move unsurround logic into no-splitting
* Fix extend-merge
* Fix inner shift being eroneusly returned as left shift
* Fix oversight in SplitRange
* Redefine how ranges are recreated
* Rename covered to insideMatch and put as fourth parameter instead of third
* Keep track of match holes and match leaves
* Rename ChildNodeRange to FlatRange
* Change signature of matcher
* Fix bug in extend-merge
* Improve Match class
* Utilize cache in TextColorButton
* Implement getBaseSurrounder for TextColorButton
* Add matchAncestors field to FormattingNode
* Introduce matchAncestors and getCache
* Do clearing during parsing already
- This way, you know whether elements will be removed before getting to
Formatting nodes
* Make HighlightColorButton use our surround mechanism
* Fix a bug with calling .removeAttribute and .hasAttribute
* Add side button to RemoveFormat button
* Add disabled to remove format side button
* Expose remove formats on RemoveFormat button
* Reinvent editor/surround as Surrounder class
* Fix split-text when working with insert trigger
* Try counteracting the contenteditable's auto surrounding
* Remove matching elements before normalizing
* Rewrite match-type
* Move setting match leaves into build
* Change editing strings
- So that color strings match bold/italic strings better
* Fix border radius of List options menu
* Implement extensions functionality
* Remove some unnecessary code
* Fix split range endOffset
* Type MatchType
* Reformat MatchType + add docs
* Fix domlib/surround/apply
* Satisfy last tests
* Register Surrounder as package
* Clarify some comments
* Correctly implement reformat
* Reformat with inactive eraser formats
* Clear empty spans with RemoveFormatButton
* Fix Super/Subscript button
* Use ftl string for hardcoded tooltip
* Adjust wording
* Improve type annotations in studydeck.py
* Use `super()`
* Explicitly delete widget after closing dialog if parent is None
* Consolidate common cleanup tasks into a function
..., and connect it to `finished` signal
* Fix new deck not being selected
* Remove redundant assignments
* Fix wrong hook being torn down
* Fix item models not being destroyed
* Add missing gc for FilteredDeckConfigDialog
* Add missing type annotation
* Pass calling widget as parent to QTimer
Implicitly passing `self.mw` as the parent means that the QTimer won't
get destroyed before quitting the app, which also thwarts garbage
collection of any data captured by a passed closure.
* Make `Editor._links` an instance variable
Browser is inserting a closure into this dict capturing itself. As a class
variable, it won't get destroyed, so neither will the browser.
* Make `Editor._links` funcs take instance again
* Deprecate calling progress.timer() without parent
* show caller location when printing deprecation warning (dae)
* Call StudyDeck with callback
* StudyDeck w/ callback, remove redundant assignment
* Replace exec() with show() for various dialogs
* Update super init args for Models.__init__
* Make StudyDialog ApplicationModal
* Remove .exec() from various dialogs and menus
* Add main view menu
* Add browser view menu
* Use standard keys for zooming and full screen
* Capitalise menu item names
* Toggle Showing Cards/Notes -> Toggle Cards/Notes
* Explicitly set linux full screen key
on_toggle_fullscreen -> on_toggle_full_screen
* Show buried until daily limits in overview screen
This explains differences between the counts shown in the deck tree and
those shown in the overview screen.
Closes#1633.
* interday learning cards can be buried too (dae)
* add 'buried' tooltip to bury counts; generate row in helper fn (dae)
* Use grey for buried counts
* Use submodule imports in aqt
* Use submodule imports in pylib
* More submodule imports in pylib
These required removing some direct imports to get rid of import cycles.
On a Linux machine here, the tests consistently fail when two copies
of black are run at once:
% bazel test //qt:format_check //pylib:format_check --cache_test_results=no
==================== Test output for //qt:format_check:
Process SyncManager-1:
Traceback (most recent call last):
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/managers.py", line 583, in _run_server
server = cls._Server(registry, address, authkey, serializer)
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/managers.py", line 156, in __init__
self.listener = Listener(address=address, backlog=16)
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/connection.py", line 453, in __init__
self._listener = SocketListener(address, family, backlog)
File "/home/dae/.cache/bazel/_bazel_dae/fc22e40cbbf8b7d16ac57a00991b1ef1/external/python/lib/python3.9/multiprocessing/connection.py", line 596, in __init__
self._socket.bind(address)
OSError: [Errno 98] Address already in use
I dug briefly into Black's code, but suspect this is actually an issue
with the multiprocessing library. Didn't have time to investigate it
further; this workaround will do for now.
(One day I'll get around to merging those separate scripts into a single
one. One day. :-))
All platforms:
- rename scripts/ to tools/: Bazelisk expects to find its wrapper script
(used by the Mac changes below) in tools/. Rather than have a separate
scripts/ and tools/, it's simpler to just move everything into tools/.
- wheel outputs and binary bundles now go into .bazel/out/dist. While
not technically Bazel build products, doing it this way ensures they get
cleaned up when 'bazel clean' is run, and it keeps them out of the source
folder.
- update to the latest Bazel
Windows changes:
- bazel.bat has been removed, and tools\setup-env.bat has been added.
Other scripts like .\run.bat will automatically call it to set up the
environment.
- because Bazel is now on the path, you can 'bazel test ...' from any
folder, instead of having to do \anki\bazel.
- the bat files can handle being called from any working directory,
so things like running "\anki\tools\python" from c:\ will work.
- build installer as part of bundling process
Mac changes:
- `arch -arch x86_64 bazel ...` will now automatically use a different
build root, so that it is cheap to switch back and forth between archs
on a new Mac.
- tools/run-qt* will now automatically use Rosetta
- disable jemalloc in Mac x86 build for now, as it won't build under
Rosetta (perhaps due to its build scripts using $host_cpu instead of
$target_cpu)
- create app bundle as part of bundling process
Linux changes:
- remove arm64 orjson workaround in Linux bundle, as without a
readily-available, relatively distro-agonstic PyQt/Qt build
we can use, the arm64 Linux bundle is of very limited usefulness.
- update Docker files for release build
- include fcitx5 in both the qt5 and qt6 bundles
- create tarballs as part of the bundling process
* Call StudyDeck with callback
* StudyDeck w/ callback, remove redundant assignment
* Replace exec() with show() for various dialogs
* Update super init args for Models.__init__
* Make StudyDialog ApplicationModal
* Callback for StudyDeck, use with onModelChange
* Add types to callback function
* Rationalise types
* Update CONTRIBUTORS
* Fix type hints
I'm still getting to grips with the type hints!
* Consistency with callback checks
* | not supported for type hints on 3.9
* Fix button focus highlight on Windows
* Use none instead of none for outline and box-shadow
* Unnest selectors in reviewer-bottom
Co-authored-by: Henrik Giesel <hengiesel@gmail.com>
* Add componentHook functionality
* Register package NoteEditor
* Rename OldEditorAdapter to NoteEditor
* Expose instances in component-hook as well
* Rename NoteTypeButtons to NotetypeButtons
* Move PreviewButton initialization to BrowserEditor.svelte
* Remove focusInRichText
- Same thing can be done by inspecting activeInput
* Satisfy formatter
* Fix remaining rebase issues
* Add .bazel to .prettierignore
* Rename currentField and activeInput to focused{Field,Input}
* Move identifier to lib and registration to sveltelib
* Fix Dynamic component insertion
* Simplify editingInputIsRichText
* Give extra warning in svelte/svelte.ts
- This was caused by doing a rename of a files, that only differed in
case: NoteTypeButtons.svelte to NotetypeButtons.svelte
- It was quite tough to figure out, and this console.log might make it
easier if it ever happens again
* Change signature of contextProperty
* Add ts/typings for add-on definition files
* Add Anki types in typings/common/index.d.ts
* Export without .svelte suffix
It conflicts with how Svelte types its packages
* Fix left over .svelte import from editor.py
* Rename NoteTypeButtons to unrelated to ensure case-only rename
* Rename back to NotetypeButtons.svelte
* Remove unused component-hook.ts, Fix typing in lifecycle-hooks
* Merge runtime-require and register-package into one file
+ Give some preliminary types to require
* Rename uiDidLoad to loaded
* Fix eslint / svelte-check
* Rename context imports to noteEditorContext
* Fix import name mismatch
- I wonder why these issues are not caught by svelte-check?
* Rename two missed usages of uiDidLoad
* Fix ButtonDropdown from having wrong border-radius
* Uniformly rename libraries to packages
- I don't have a strong opinion on whether to name them libraries or
packages, I just think we should have a uniform name.
- JS/TS only uses the terms "module" and "namespace", however `package`
is a reserved keyword for future use, whereas `library` is not.
* Refactor registration.ts into dynamic-slotting
- This is part of an effort to refactor the dynamic slotting (extending
buttons) functionality out of components like ButtonGroup.
* Remove dynamically-slottable logic from ButtonToolbar
* Use DynamicallySlottable in editor-toolbar
* Fix no border radius on indentation button dropdown
* Fix AddonButtons
* Remove Item/ButtonGroupItem in deck-options, where it's not necessary
* Remove unnecessary uses of Item and ButtonGroupItem
* Fix remaining tests
* Fix relative imports
* Revert change return value of remapBinToSrcDir to ./bazel/out...
* Remove typings directory
* Adjust comments for dynamic-slottings
When backups were moved into a separate thread 5 years ago, it improved
performance when switching between different profiles, as the backup
happened in the background. But when closing Anki, we wait on the
background thread to complete, so Anki hangs until the backup finishes.
The performance difference on a large collection is considerable:
- 0.45s without compression
- 7.9s with compression
Given that the majority of users probably aren't using multiple profiles,
I think the speed increase is probably worth the extra disk usage. In
the future, we may want to look into using zstd to compress the backups,
which may even be a performance win over the uncompressed version on
some devices.
* Add fix for users without gnome schema
On some systems, the result of the `gsettings get org.gnome.desktop.interface gtk-theme` command is `No such schema “org.gnome.desktop.interface”`, which causes Anki to fail to find a value, subsequently crashing on some Linux systems.
* Fix whitespace
* NF: rename "fields" into "field_names" for clarity
* NF: remove an useless enumerate
the integral value was never used
* NF: rename new and old into new_note and old_note for clarity
* NF: rename old_field to old_field_value for clarity
Unfortunately 5efaf5a4be broke the Svelte
language tools - presumably having paths outside of the repo is confusing
them.
As a plan B, the symlinks have been shifted to a single subdir. Along
with some exclusions in the VS Code config, this should allow VS Code
to continue to work out of the box, but the docs will need updating
to reflect the extra work required for PyCharm/IntelliJ.
+ fix svelte-check execution on a system without node installed. It
still throws up some errors that are presumably caused by our multiple
rootDirs - not sure if there's an easy way to work around that.
The default symlink location can cause slowdowns and wasted CPU cycles
in VS Code and PyCharm/IntelliJ, as they try to watch Bazel's (large)
build folder for changes. The issue can be mostly ameliorated in VS Code
by excluding the symlinks using globs in settings like watcherExclude,
but the Rust extension doesn't support globs, so each folder needs to be
listed out separately. And because the product name symlink depends on
the name of the directory you're building from, we can't just include
the excludes in .vscode - it will depend on the folder the user is storing
things.
PyCharm and IntelliJ behave even worse here - they continue to monitor
for changes in all folders of the repo, even if those folders have been
marked as excluded in the project settings. Placing the folders into the
IDE-global Editor>File Types>Ignored Files And Folders works around this,
but again we run into troubles making this work out of the box, especially
with the product name in the symlink.
One option would be to turn the symlinks off completely. They are not
required for building, and for scripting/debugging, we can get the folder
locations via 'bazel info'. But with that approach, we would no longer
be able to symlink build products into the source tree, as we do for
things like the generated backend methods and translations, so we'd lose
code completion for them that way.
Another option would be to place the symlinks in .bazel/ inside the repo.
That solves the VS Code case (in conjunction with a workspace config file),
but doesn't fully fix IntelliJ/PyCharm.
The only remaining option I can see is to place the symlinks outside the
repo. Bazel won't expand ~ in the symlink path, so we can't use something
like ~/.cache/bazel/anki to place the files near the other build files.
So we end up having to have the files written to ../bazel/anki, in the
repo's parent folder. Not very clean, but I don't see a better alternative
at the moment.
.gitignore is still ignoring bazel-*, as currently bazel-dist and
bazel-pkg will be created when building/packaging. They should be fairly
innocuous, but we may want to rename them at one point.
Other changes:
- add missing symlink for pylib hooks
- add a sample .user.bazelrc file