Due to the orphan rule, this meant removing our usages of impl ProtoStruct,
or converting them to a trait when they were used commonly.
rslib now directly references anki_proto and anki_i18n, instead of
'pub use'-ing them, and we can put the generated files back in OUT_DIR.
* Skip linting target folder
Contains build files not passing the copyright header check.
* Implicitly clear duplicate keys when serializing
Fixes `originalStockKind` not being cleared from `other`, as it had
mistakenly been added to the field list for `NoteFieldSchema11`.
A couple of motivations for this:
- genbackend.py was somewhat messy, and difficult to change with the
lack of types. The mobile clients used it as a base for their generation,
so improving it will make life easier for them too, once they're ported.
- It will make it easier to write a .ts generator in the future
- We currently implement a bunch of helper methods on protobuf types
which don't allow us to compile the protobuf types until we compile
the Anki crate. If we change this in the future, we will be able to
do more of the compilation up-front.
We no longer need to record the services in the proto file, as we can
extract the service order from the compiled protos. Support for map types
has also been added.
* Default to current deck in csv import if settings allow it
Reuses defaults_for_adding(). In the future we might also want to update
the last deck/notetype on successful completion, if entries weren't
specified in the file.
https://forums.ankiweb.net/t/importing-new-notes-to-wrong-deck-in-anki-2-1-63/30598
* Address review feedback from Rumo
* Store coordinates as ratios of full size
* Use single definition for cappedCanvasSize()
* Move I/O review code into ts/image-occlusion
A bit simpler when it's all in one place.
* Reduce number precision, and round to whole pixels
>>> n=10000
>>> for i in range(1, int(n)): assert i == round(float("%0.4f" % (i/n))*n)
* Minor typing tweak
So, it turns out that typing is mostly broken in ts/image-occlusion.
We're importing from fabric which is a js file without types, so types
like fabric.Canvas are resolving to any.
I first tried switching to `@types/fabric`, which introduced a slew of
typing errors. Wasted a few hours trying to address them, before deciding
to give up on it, since the types were not complete. Then found fabric
has a 6.0 beta that introduces typing, and spent some time with that, but
ran into some new issues as it still seems to be a work in progress.
I think we're probably best off waiting until it's out and stabilized
before sinking more effort into this.
* Refactor (de)serialization of occlusions
To make the code easier to follow/maintain, cloze deletions are now decoded/
encoded into simple data classes, which can then be converted to Fabric objects
and back. The data objects handle converting from absolute/normal positions, and
producing values suitable for writing to text (eg truncated floats).
Various other changes:
- Polygon points are now stored as 'x,y x2,y2 ...' instead of JSON in cloze
divs, as that makes the handling consistent with reading from cloze deletion
text.
- Fixed the reviewer not showing updated placement when a polygon was moved.
- Disabled rotation controls in the editor, since we don't support rotation during
review.
- Renamed hideInactive to occludeInactive, as it wasn't clear whether the former
meant to hide the occlusions, or keep them (hiding the content). It's stored
as 'oi=1' in the cloze text.
* Increase canvas size limit, and double pixels when required.
* Size canvas based on container size
This results in sharper masks when the intrinsic image size is smaller
than the container, and more legible ones when the container is smaller than
the intrinsic image size.
By using the container instead of the viewport, we account for margins,
and when the pixel ratio is 1x, the canvas size and container size should
match.
* Disable zoom animation on editor load
* Default to rectangle when adding new occlusions
* Allow users to add/update notes directly from mask editing page
* The mask editor needs to work with css pixels, not actual pixels
The canvas and image were being scaled too large, which impacted
performance.
* Migrate check_copyright to Rust
* Add a new lint to check accidental usages of /// in ts/svelte comments
* Fix a bunch of incorrect jdoc comments
* Move contributor check into minilints
Will allow users to detect the issue locally with './ninja check'
before pushing to CI.
* Make Cargo.toml consistent with other crates
* Cloze styling is not required in I/O notetype
* Use raw string for IO template
* Rename to notetype.css and use more specific ids
* Move internal i/o styling into runtime
Storing it in the notetype makes it difficult to make changes, and
makes it easier for the user to break.
* Fix misaligned occlusions
At larger screen sizes, the canvas was not increasing above its configured
size, so it ended up being placed top center instead of expanding to fit
the entire container area.
To resolve this, both the image and canvas are forced to the container
size, and the container is constrained to the size of the viewport,
with the same aspect ratio as the image.
Closes#2492
- Ensure our unit tests cover the non-legacy path, and check file
contents and not just existence.
- Pass `compressed` into copy_and_ensure_sha1_set(). We can't just
test for self.sha1.is_none(), as that fails in the case where an existing
media file was found in the legacy path.
https://forums.ankiweb.net/t/anki-media-file-corruption-when-exporting-png-files/30315
* Fix sync client ignoring directories
Current implementation of the sync client does not properly send requests to a
self-hosted sync server if the URL has directories.
If the self-hosted sync URL is `https://example.org/foo/bar/`, Anki is expected
to send requests to `https://example.org/foo/bar/sync/hostKey`. Instead, it will
discard the directories and wrongly send requests to
`https://example.org/sync/hostKey`.
Fixes: e5d5d1d ("Fix panic with invalid sync server URL with port")
* Add XeR to contributors
* Fix file extension not being appended on export
Regressed in #2427
* Improve import messaging when notetype has changed
- If the local notes are up to date, we don't need to warn about the
changed notetype, as no updates are required.
- Make it clearer that a changed notetype only affects updates.
Will update the docs as well.
* Allow user to select I/O notetype instead of enforcing a specific name
* Display a clearer error when I/O note is missing an image
Opening the card layout screen from "manage notetypes" was showing an
error about the Anki version being too old.
Replacement error is not currently translatable.
* Preserve existing notetype when adding I/O notetype
* Add a 'from clipboard' string
The intention is to use this in the future to allow an image occlusion
to be created from an image on the clipboard.
* Tweak I/O init
- Use union type instead of multiple nullable values
- Pass the notetype id in to initialization
* Fix image insertion in I/O note
- The regex expected double quotes, and we were using single ones
- Image tags don't need to be closed
* Use more consistent naming in image_occlusion.proto
* Tweaks to default I/O notetype
- Show the header on the front side as well (I presume this is what
users expect; if not am happy to revert)
- Don't show comments on card (again, I presume users expect to use
this field to add notes that aren't displayed during review, as they
can use back extra for that)
* Fix sticky footer missing background
Caused by earlier CSS refactoring
* Store the original stock notetype kind in the notetype
Will allow us to provide a command to restore a notetype to its default
settings/templates.
* Add a new action to restore a notetype to its original state
* add note types with occlusions and image fields
* generate image occlusion cloze div data
- generate div element with data-* atrributes for canvas shape generate for reviewer
* getting image data & deck id and adding notes
the implementation added into backend
- added service index in backend.proto for image occlusion request
- created image_occlusion.proto with required message and service
- implementation in backend for getting image and adding notes, also during editing return imagecloze note and update notes
- add notes to selected deck, if no notetype then add image occlusion notetypes
- reuse notetype from stock notetypes when not exist
* script for generating shapes using canvas api in reviewer
- the flash issues fixed by loading image and using image size to draw canvas, also when image get resized, calculate scale using natural width and canvas width to draw shape at right position
- limit size of canvas for safari
* init image occlusion page in ts and build page
with
- fabricjs for editing shapes
- panzoom for drag and zoom
- pickr for color picker
- build page using web.rs
* implement top toolbar for canvas shapes
- undo & redo tools
- zoom in, zoom out and zoom fit
- group & ungroup
- copy & paste
- set transparency of shapes
- align tools
* implement side toolbar for drawing shapes
add top toolbar and the side toolbar contains following tools
- cursor for selecting shapes
- zoom for drag and zoom shapes in mask editor
- rectangle for creating it
- ellipse for creating it
- polygon for creating it using points
- shape fill color
- question mask color (currently only single color can be added for all shapes)
* add maskeditor page for editing mask
- add side toolbar and sidebar include toptoolbar
- load maskeditor in two mode
- for adding note using path to image
- for editing note using note id
* implement note editor page for adding notes
- the note editor page have simple button (B/I/U) and option to toggle html view
- option to select deck for adding notes into that deck
- option to generate to hide all, guess one & hide one, guess one notes
* add image occlusion page
add side toolbar, top toolbar, mask editor and note editor
- option to switch between mask editor and note editor
* implement generates notes and save notes
implemention to show toast components for messages
* removed pickr & implemented color picker component
- remove pickr
- implemented using html5 canvas
- range input for changing color
- another range input for opacity changes
- hex and rgba value support
* rename methods name & rust unwrap safety
- change plural names to singular
- create respone message in proto and return response with imagecloze note or error if not found with note id
- remove image_occlusion from post handler list
- rename service name in mediasrv.py
- rename methods name for image occlusion in backend and image_occlusion
- update frontend also for update functions' names
- handle error in frontend mask-editor.ts, when error getting notes then toast message shown to frontend
* extract to function & add comments & remove global
- extract function in mask-editor.ts to reduce duplicate
- remove unused global from css
- add comments to store.ts explaining usage
- changes id to noteId in lib.ts
- add comments for limitSize, becuase of duplicate implementation
* remove image_occlusion notetype
- remove from stock notetype, stdmodels
- add implementation for notetype to image occlusion
- add i18n for errors
* update smooth scroll, always show cursor tools
- change questionmask to qmask
- make selectable for shape true in all tools to simplify edits and draw shapes
- update image occlusion in reviewer ts to load image properly
* add and get notetype else return errors
* fix: not showing occlusion
* Use a oneof for ImageClozeNoteResponse
Makes it clearer that only one of them can be returned
* Don't crash if image filename not provided
The second unwrap should be ok, as the input is utf8
* Refactor get_image_cloze_note
- fixes crash when note doesn't exist - Ok(None) case was not covered
- decouples business logic from native error->proto error conversion
- no need for original copy
- field[x] is more idiomatic than field.get(x).unwrap()
- don't need mutable access to fields
* Fix crash if image file unreadable
+ Use our read_file helper for better error context
* Add metadata() helper
* Fix crash if file metadata can't be read
* remove color picker, qmask and shape color
- remove strings from ftl
- remove color picker component
- remove from cloze generation
- remove icons for two buttons
- use constant color for shapes
* update color in reviewer and ftl strings
* fix shape position in canvas & add border to shape
- rename mask to inactive shape and active shape color
- border witdth and border color
- change decimal point deserializing string and toFixed(2)
- add thin border in mask editor, may be image background was transparent
* fix shape position in canvas after modified
- do not draw fixed ratio shapes by turn of uniformScaling
- fix rectangle width,height
- fix ellipse rx,ry,width,height
- fix polygon postion and points
- draw outside of canvas also
* fix border width and color in reviewer canvas
- rename variable
* refactor cloze div generate and remove angle
* fix origin when drawn outside of canvas from right
* fix shape at boundry & not include rx,ry rectangle
- move shapes at boundry when pointer is outside of canvas
- include rx, ry for ellipse only
- include points for polygon only
* fix lint errors & update image size in editor canvas based on height and width
* remove unsupported layerX & layerX for touchscreen
- fix shapes at edges
* implemented undo redo with canvas state
- implemented undo redo using fabric canvas events
- polygon is special case and implemented only added and modified event
- rectangle and ellipse have object:added, object:modified and object:removed case
- change id to undo and redo
* remove background image from canvas and used css to put image tag below canvas editor
- set image width and height after adding image
* fix for polygon points, add br in cloze strings, & toogle masks button
- fix shapes at edges
- toggle masks button to show/hide masks
- hide clozes string, it contains <br>
- set height for div container (used 'relative' in css)
* refactor top toolbar, add space and border radius
- rename cursor tools
- add left and right border
* fix undo after undo happen, use transparent color in draw mode
* fix stats calendar daylight saving time offset bug
Previously, when computing counts for the calendar in the stats menu, it was assumed that days had 86,400 seconds. However, this assumption does not hold true on the day when daylight savings occurs.
* add self to CONTRIBUTORS and about.py
* fix stats calendar anki day to calendar day mapping
Since Anki days don't necessarily roll over at midnight, mapping an Anki day into a calendar day needs to have a linear shift applied. By providing the frontend with access to the scheduler's rollover hour, we can account for this offset.
* Add option to exclude fields from unqualified searches
* Use temp tables instead
This is slightly faster according to my (very rough) tests.
* Make query a bit more readable
* exclude_from_search -> excludeFromSearch
* Remove superfluous notetypes table from query
* Rework to use field search logic
Thanks to Rumo for the suggestion: https://github.com/ankitects/anki/pull/2394#issuecomment-1446702402
* Exclude fields from field searches too
* Fix error on notetypes with no included fields
* Add back the exclude_fields function
This approach seems to perform better on average than the previously
benchmarked ones.
* Use pure-SQL approach to excluding fields
* Change single field search to use new approach
* Fix flawed any_excluded/sortf_excluded logic
* Support field exclusion in the nc operator
Also fix search text being wrapped in % in the any_excluded=true case.
* Support field exclusion in the re and w operators
* Label field exclusion as being slower
* Unqualified search should be wrapped in % in all cases
I was under the impression that it shouldn't be wrapped with the new
field exclusion logic.
* Remove unnecessary .collect()
* Refactor some complex return types into structs
* Do not exclude fields in field searches
* Add a test and docstring for CollectRanges
* Avoid destructuring in closures
* Remove the exclude_fields function
Minor wording tweaks by dae:
* num_fields -> total_fields_in_note
* fields -> field_ranges_to_search
* fields -> fields_to_search
* SingleField -> FieldQualified
* mid -> ntid
* Move open_test_collection into Collection test impl
* Fix invalid ids when checking database
* Report fixed invalid ids
* Improve message when trying to export invalid ids
Also move ImportError due to namespace conflicts with snafu macro.
* Take a human name in DeckAdder::new
* Mention timestamps in the db check message (dae)
Will help to correlate the fix with the message shown when importing/
exporting.
* Ensure state mutator runs after card is rendered
* Ensure ease buttons only show when states are ready
* Pass context into states mutator
* Revert queuing of state mutator hook
Now that context data is exposed users shouldn't rely on the question
having been rendered anymore.
* Use callbacks instead of signals and timeout
... to track whether the states mutator ran or failed.
* Make mutator async
* Remove State enum
* Reduce requests and compute seed on backend
* Remove outdated comment.
* Revert removal of independent bury rules
* Revert 'hierarchical bury modes'
It's now again allowed to bury new, but not review cards e.g., but
siblings of previously gathered card queues will not be buried.
* Tweak docs (dae)
* Add missing Learn and PreviewRepeat queues
* Add CardAdder test helper
* Add option to have new cards ignore the review limit
Also entails a lot of refactoring because the old code was deeply
coupled to the previous behaviour.
* Add global option to ignore review limit
* Refactor decrementation
* Unify testing
d20a7d291f introduced a serious regression,
causing cards to be reset to the default ease when upgrading to the latest
schema version. This could also be triggered when exporting a colpkg with
legacy support.
* Implement TTS using windows crate
* Use API calls instead of SSML
* Properly stop player in case of TTS error
* Add context to WindowsErrors
* Validate available voices
* Remove TTS text from synthesize error
* Limit maximum buffer size
* Make validation optional and list it in tts filter
* We no longer need the winrt module (dae)
* Use a separate request object so the meaning of the bool is clear (dae)
* Slightly shorten runtime error message (dae)
The default message appears to clip slightly.
* Alternate buffer implementation (dae)
* Use array instead of vec
* Drop the max buffer size to 128k (dae)
* Add Rust bin to deprecate unused ftl entries
* Align function names with bin names
* Support passing in multiple ftl roots
* Use source instead of jsons for deprecating
* Fix CargoRun not working more than once (dae)
* Add ftl:deprecate (dae)
* Deprecate some strings (dae)
This is not all of the strings that are currently unused
* Check json files before deprecating; add allowlist (dae)
The scheduler messages we'll probably want to reuse for the v2->v3
transition, so I'd prefer to keep them undeprecated for now.
* Deprecate old bury options (dae)
* Support gathering usages from Kotlin files for AnkiDroid (dae)
* Update json scripts (dae)
* Remove old deprecation headers
* Parameterize JSON roots to keep
* Tweak deprecation message (dae)
* Enforce hierarchical bury modes
Interday learning burying is only allowed if review burying is enabled
and review burying is only allowed if new burying is enabled.
Closes#2352.
* Switch front end to new bury modes
* Wording tweaks (dae)
* Hide interday option if using v2 scheduler (dae)
* Allow burying cards in browser
This code is based on existing "toggle suspend" command in browser.
- Adds "toggle bury" command to browser cards menu.
- Adds "browsing-toggle-bury" to core translation. Only english-language.
- Adds "buried" coloring to rows for buried cards in browser table.
Not yet done:
- Keyboard shortcut for "toggle bury" action.
- Non-english translations.
* Add contributor as requested in CONTRIBUTORS.
* Fix formatting in browser_table.rs.
* Add keyboard shortcut to "toggle bury" command.
This adds keyboard shortcut "ctrl-shift-j" to "toggle bury" command in
browser cards menu.
* Simplify logic for color of buried-card rows.
da7d4dd2fc changed the name of the env
var in .cargo/config.toml, causing the check in setup_protoc() to think
a custom path had been provided, which skipped the download and extract
step.
* Support specifying a working dir to a build command
* Use nightly for formatting
* Pass valid TERM in from environment
Rustfmt depends on a valid setting, and not just the var to be non-empty.
* Wrap comment
This PR replaces the existing Python-driven sync server with a new one in Rust.
The new server supports both collection and media syncing, and is compatible
with both the new protocol mentioned below, and older clients. A setting has
been added to the preferences screen to point Anki to a local server, and a
similar setting is likely to come to AnkiMobile soon.
Documentation is available here: <https://docs.ankiweb.net/sync-server.html>
In addition to the new server and refactoring, this PR also makes changes to the
sync protocol. The existing sync protocol places payloads and metadata inside a
multipart POST body, which causes a few headaches:
- Legacy clients build the request in a non-deterministic order, meaning the
entire request needs to be scanned to extract the metadata.
- Reqwest's multipart API directly writes the multipart body, without exposing
the resulting stream to us, making it harder to track the progress of the
transfer. We've been relying on a patched version of reqwest for timeouts,
which is a pain to keep up to date.
To address these issues, the metadata is now sent in a HTTP header, with the
data payload sent directly in the body. Instead of the slower gzip, we now
use zstd. The old timeout handling code has been replaced with a new implementation
that wraps the request and response body streams to track progress, allowing us
to drop the git dependencies for reqwest, hyper-timeout and tokio-io-timeout.
The main other change to the protocol is that one-way syncs no longer need to
downgrade the collection to schema 11 prior to sending.
1. Add outer brackets.
2. Coalesce aggregate, because `null and true` is `null` in SQL land,
so cards that were not introduced, but manually rescheduled in the
period of interest, would not show up in a negated search.
* Relax chrono specification for AnkiDroid
https://github.com/ankidroid/Anki-Android-Backend/pull/251
* Add AnkiDroid service and AnkiDroid customizations
Most of the work here was done by David in the Backend repo; integrating
it into this repo for ease of future maintenance.
Based on 5d9f262f4c
with some tweaks:
- Protobuf imports have been fixed to match the recent refactor
- FatalError has been renamed to AnkidroidPanicError
- Tweaks to the desktop code to deal with the extra arg to open_collection,
and exclude AnkiDroid service methods from our Python code.
* Refactor AnkiDroid's DB code to avoid uses of unsafe
The Rust community appear to have converged on tracing - it's used by
the Rust compiler, and receives close to 10x the number of downloads
that slog does. Its API is more ergonomic, and it does a much nicer
job with async rust.
To make this change, we no longer pass around explicit loggers, and rely
on a globally-registered one. The log file location has been changed
from one in each profile folder to a single one in the base folder. This
will remain empty for most users, since only errors are logged by default,
but may be useful for debugging future changes.
The existing architecture serializes all cards and revlog entries in
the search range into a protobuf message, which the web frontend needs
to decode and then process. The thinking at the time was that this would
make it easier for add-ons to add extra graphs, but in the ~2.5 years
since the new graphs were introduced, no add-ons appear to have taken
advantage of it.
The cards and revlog entries can grow quite large on large collections -
on a collection I tested with approximately 2.5M reviews, the serialized
data is about 110MB, which is a lot to have to deserialize in JavaScript.
This commit shifts the preliminary processing of the data to the Rust end,
which means the data is able to be processed faster, and less needs to
be sent to the frontend. On the test collection above, this reduces the
serialized data from about 110MB to about 160KB, resulting in a more
than 2x performance improvement, and reducing frontend memory usage from
about 400MB to about 40MB.
This also makes #2043 more feasible - while it is still about 50-100%
slower than protobufjs, with the much smaller message size, the difference
is only about 10ms.
* Run cargo +nightly fmt
* Latest prost-build includes clippy workaround
* Tweak Rust protobuf imports
- Avoid use of stringify!(), as JetBrains editors get confused by it
- Stop merging all protobuf symbols into a single namespace
* Remove some unnecessary qualifications
Found via IntelliJ lint
* Migrate some asserts to assert_eq/ne
* Remove mention of node_modules exclusion
This no longer seems to be necessary after migrating away from Bazel,
and excluding it means TS/Svelte files can't be edited properly.
This reverts commit 09cb8b3cf6.
Overhead on larger folders/slower devices is more than I originally
anticipated, and can run into multiple seconds. This seems to be
particularly egregious on mobile, which I presume is due to sandboxing
overhead.
* Remove deprecated `and_hms()`
* Update chrono
* Update licenses and fix script
* Remove deprecated Date struct
* Remove chrono pin
* Skip format check on .vscode
Was failing for no reason.
* Replace deprecated chrono functions
* Add cargo-deny to update-licenses & pin versions (dae)
* Remove time 0.1 dependency (dae)
We don't need to wait for chrono 0.5; it was provided behind a legacy
feature flag.
(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
* Fix reparented_name not correctly handling tags that are prefixes of the
new parent
To reproduce the issue:
1. Add two tags: `a` and `ab`.
2. From the browser's sidebar, drag & drop `a` into `ab`.
Result: panic
* Fix reparent_tags panicking if new parent is a child of source tag
This is the "foo, foo::bar" case that should be a no-op.
* Add more tests for tag reparenting
* Add crate snafu
* Replace all inline structs in AnkiError
* Derive Snafu on AnkiError
* Use snafu for card type errors
* Use snafu whatever error for InvalidInput
* Use snafu for NotFoundError and improve message
* Use snafu for FileIoError to attach context
Remove IoError.
Add some context-attaching helpers to replace code returning bare
io::Errors.
* Add more context-attaching io helpers
* Add message, context and backtrace to new snafus
* Utilize error context and backtrace on frontend
* Rename LocalizedError -> BackendError.
* Remove DocumentedError.
* Have all backend exceptions inherit BackendError.
* Rename localized(_description) -> message
* Remove accidentally committed experimental trait
* invalid_input_context -> ok_or_invalid
* ensure_valid_input! -> require!
* Always return `Err` from `invalid_input!`
Instead of a Result to unwrap, the macro accepts a source error now.
* new_tempfile_in_parent -> new_tempfile_in_parent_of
* ok_or_not_found -> or_not_found
* ok_or_invalid -> or_invalid
* Add crate convert_case
* Use unqualified lowercase type name
* Remove uses of snafu::ensure
* Allow public construction of InvalidInputErrors (dae)
Needed to port the AnkiDroid changes.
* Make into_protobuf() public (dae)
Also required for AnkiDroid. Not sure why it worked previously - possible
bug in older Rust version?
* Show warning if multiple type boxes are used
* Report templates referencing media in Media Check
* Apply suggestions from code review
* Fix media-check.ftl
* Only report media references with fields
Like `<img src={{Front}}>`.
Also report Anki sound tags and latex.
* Loop existing media regexes
* Enable state-dependent custom scheduling data
* Next(Card)States -> SchedulingStates
The fact that `current` was included in `next` always bothered me,
and custom data is part of the card state, so that was a bit confusing
too.
* Store custom_data in SchedulingState
* Make custom_data optional when answering
Avoids having to send it 4 extra times to the frontend, and avoids the
legacy answerCard() API clobbering the stored data.
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
* Keep filtered decks when importing apkg
If all original decks exist and scheduling is included.
* Create missing decks from csv
* Export original decks if with_scheduling
* Also remap original deck ids on import
* Update imported filtered decks
* Fix meta column being mapped to tags
* Fix ids in csv deck and notetype columns
Note: This implies names which parse to an i64 will be seen as ids,
likely resulting in the intended deck/notetype not being found.
* Check for scheduling with revlog and deck configs
Might help with cases in which scheduling was included, but all cards
are new. In such a case, filtered deck should not be converted.
* Fix duplicate with same GUID being created
* Remove redundant `distinct`s from sql query
* Match notes by _either_ guid _or_ first field
* Refactor to emphasise GUID/first field distinction
* Export default deck and config if with scheduling
* Fix default deck being exported if it's a parent
* Add card meta for persisting custom scheduling state
* Rename meta -> custom_data
* Enforce limits on size of custom data
Large values will slow down table scans of the cards table, and it's
easier to be strict now and possibly relax things in the future than
the opposite.
* Pack card states and customData into a single message
+ default customData to empty if it can't be parsed
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
* Introduce setting to collapse field by default
* Fix schema order
* Change wording from adjective to imperative
sounds a bit less clunky
* Update rslib/src/notetype/schema11.rs (dae)
* Keep settings in single column
* Add back Toggle Visual Editor string
* Add RichTextBadge component and show it conditionally
* Reverse input order depending on default setting
* Make PlainTextInput border-radius responsive to toggle states
* Prevent first Collapsible transition differently
* Focus inputs after Collapsible transition
The double tick calls are just a temporary solution until I find the exact moment an input is focusable again.
* Use requestAnimationFrame to await focusable state
Note: Svelte tick doesn't seem to work in this scenario.
* Keep content of unmapped fields when importing
* Test new behaviour
* Fix typo in `canonify_tags_without_resgistering`
* Log updated note instead of original one
* Revert merging imported tags
But keep old note tags if no new ones are provided.
* Introduce field setting to use plain text editor by default
* Remove leftover function from #1476
* Use boolean instead of string
* Simplify clear_other_field_duplicates
* Convert plain text key to camelCase
* Move HTML item below the existing checkbox, instead of to the right (dae)
Showing it on the right is more space efficient, but feels a bit
cluttered IMHO.
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.
* Refactor MediaManager transactions
* Add media entries when importing
* Fix legacy apkg import not setting csum
Also test for this in the roundtrip test.
* Avoid reallocating MediaCopier's buffer
* Make sha1 optional (dae)
* Add deck-specific limits to DeckNormal
* Add deck-specific limits to schema11
* Add DeckLimitsDialog
* deck_limits_qt6.py needs to be a symlink
* Clear duplicate deck setting keys on downgrade
* Export deck limits when exporting with scheduling
* Revert "deck_limits_qt6.py needs to be a symlink"
This reverts commit 4ee7be1e10c4e8c49bb20de3bf45ac18b5e2d4f6.
* Revert "Add DeckLimitsDialog"
This reverts commit eb0e2a62d33df0b518d9204a27b09e97966ce82a.
* Add day limits to DeckNormal
* Add deck and day limits mock to deck options
* Revert "Add deck and day limits mock to deck options"
This reverts commit 0775814989e8cb486483d06727b1af266bb4513a.
* Add Tabs component for daily limits
* Add borders to tabs component
* Revert "Add borders to tabs component"
This reverts commit aaaf5538932540f944d92725c63bb04cfe97ea14.
* Implement tabbed limits properly
* Add comment to translations
* Update rslib/src/decks/limits.rs
Co-authored-by: Damien Elmes <dae@users.noreply.github.com>
* Fix camel case in clear_other_duplicates()
* day_limit → current_limit
* Also import day limits
* Remember last used day limits
* Add day limits to schema 11
* Tweak comment (dae)
* Exclude day limit in export (dae)
* Tweak tab wording (dae)
* Update preset limits on preset change
* Explain tabs in tooltip (dae)
* Omit deck and today limits if v2 is enabled
* Preserve deck limit when switching to today limit
* Expose cloze text as attribute on front side
* Update test_models.py
* Update template_filters.rs
* Escape HTML for data-attribute
* Use minimal HTML encoding in Rust
to match Python's html.escape and pass tests.
* Rename attribute to data-cloze
to make it more generic.
* Run formatter
* Revert to using Rust encode_attribute and add helper function for tests
* Adjust remaining steps after config update
* Handle relearning steps separately
Also refactor a lot.
* Also adjust remaining steps after deck change
* Test step adjustment after config update
* Fix `SearchBuilder::(re)learning_cards()`
* Fix step adjustment after deck change
* Test step adjustment after deck change
* Fix test name
* Readjust remaining steps according to last delay
Also atomize tests and add some tooling.
* Throw error for unknown condition fields as well
So if 'foo' is not a field, refuse to save a template containing
`{{#foo}}bar{{/foo}}`. Previously, only `{{foo}}` would be checked.
As a side effect, templates which *only* contain fields as conditions
may be saved. Meh.
* Display template errors in q/a columns only
So the affected browser row remains active and the user can fix the
template more easily.
* Specify if error occured in a browser template
* Minor wording tweak (dae)
There's an argument for using the exact wording as well, but this just
reads a little more naturally to me.