* Remove --medium-border variable
* Implement color palette using Sass maps
I hand-picked the gray tones, the other colors are from the Tailwind CSS v3 palette.
Significant changes:
- light theme is brighter
- dark theme is darker
- borders are softer
I also deleted some platform- and night-mode-specific code.
* Use custom colors for note view switch
* Use same placeholder color for all inputs
* Skew color palette for more dark values
by removing gray[3], which wasn't used anywhere. Slight adjustments were made to the darker tones.
* Adjust frame- window- and border colors
* Give deck browser entries --frame-bg as background color
* Define styling for QComboBox and QLineEdit globally
* Experiment with CSS filter for inline-colors
Inside darker inputs, some colors like dark blue will be hard to read, so we could try to improve text-color contrast with global adjustments depending on the theme.
* Use different map structure for _vars.scss
after @hgiesel's idea: https://github.com/ankitects/anki/pull/2016#discussion_r947087871
* Move custom QLineEdit styles out of searchbar.py
* Merge branch 'main' into color-palette
* Revert QComboBox stylesheet override
* Align gray color palette more with macOS
* Adjust light theme
* Use --slightly-grey-text for options tab color
* Replace gray tones with more neutral values
* Improve categorization of global colors
by renaming almost all of them and sorting them into separate maps.
* Saturate highlight-bg in light theme
* Tweak gray tones
* Adjust box-shadow of EditingArea to make fields look inset
* Add Sass functions to access color palette and semantic variables
in response to https://github.com/ankitects/anki/pull/2016#issuecomment-1220571076
* Showcase use of access functions in several locations
@hgiesel in buttons.scss I access the color palette directly. Is this what you meant by "... keep it local to the component, and possibly make it global at a later time ..."?
* Fix focus box shadow transition and remove default shadow for a cleaner look
I couldn't quite get the inset look the way I wanted, because inset box-shadows do not respect the border radius, therefore causing aliasing.
* Tweak light theme border and shadow colors
* Add functions and colors to base_lib
* Add vars_lib as dependency to base_lib and button_mixins_lib
* Improve uses of default-themed variables
* Use old --frame-bg color and use darker tone for canvas-default
* Return CSS var by default and add palette-of function for raw value
* Showcase use of palette-of function
The #{...} syntax is required only because the use cases are CSS var definitions. In other cases a simple palette-of(keyword, theme) would suffice.
* Light theme: decrease brightness of canvas-default and adjust fg-default
* Use canvas-inset variable for switch knob
* Adjust light theme
* Add back box-shadow to EditingArea
* Light theme: darken background and flatten transition
also set hue and saturation of gray-8 to 0 (like all the other grays).
* Reduce flag colors to single default value
* Tweak card/note accent colors
* Experiment with inset look for fields again
Is this too dark in night mode? It's the same color used for all other text inputs.
* Dark theme: make border-default one shade darker
* Tweak inset shadow color
* Dark theme: make border-faint darker than canvas-default
meaning two shades darker than it currently was.
* Fix PlainTextInput not expanding
* Dark theme: use less saturated flag colors
* Adjust gray tones
* Fix nested variables not getting extracted correctly
* Rename canvas-outset to canvas-elevated
* Light theme: darken canvas-default
* Make canvas-elevated a bit darker
* Rename variables and use them in various components
* Refactor button mixins
* Remove fusion vars from Anki
* Adjust button gradients
* Refactor button mixins
* Fix deck browser table td background color
* Use color function in buttons.scss
* Rework QTabWidget stylesheet
* Fix crash on browser open
* Perfect QTableView header
* Fix bottom toolbar button gradient
* Fix focus outline of bottom toolbar buttons
* Fix custom webview scrollbar
* Fix uses of vars in various webviews
The command @use vars as * lead to repeated inclusion of the CSS vars.
* Enable primary button color with mixin
* Run prettier
* Fix Python code style issues
* Tweak colors
* Lighten scrollbar shades in light theme
* Fix code style issues caused by merge
* Fix harsh border color in editor
caused by leftover --medium-border variables, probably introduced with a merge commit.
* Compile Sass before extracting Python colors/props
This means the Python side doesn't need to worry about the map structure and Sass functions, just copy the output CSS values.
* Desaturate primary button colors by 10%
* Convert accidentally capitalized variable names to lowercase
* Simplify color definitions with qcolor function
* Remove default border-focus variable
* Remove redundant colon
* Apply custom scrollbar CSS only on Windows and Linux
* Make border-subtle color brighter than background in dark theme
* Make border-subtle color a shade brighter in light theme
* Use border-subtle for NoteEditor and EditorToolbar border
* Small patches
* Fix Windows dark mode detection: OpenKey can fail
#1497 introduced reading hardcoded Windows Registry key, which assumes key exists. This is not true on Windows 7. Later addition of `try-except` block missed that OpenKey might fail.
This fix allows launching current version of Anki on Windows 7 when installed with Pip with the modified Python 3.9 installation.
* Update CONTRIBUTORS
CI req: Add myself to the contributor list
* Add flag for enabling insert symbols feature
* Add symbols overlay directory
* Detect if :xy is inserted into editable
* Allow naive updating of overlay, and special handling of ':'
* First step towards better Virtual Element support
* Update floating to reference range on insert text
* Position SymbolsOverlay always on top or bottom
* Add a data-provider to emulate API
* Show correct suggestions in symbols overlay
* Rename to replacementLength
* Allow replacing via clicking in menu
* Optionally remove inline padding of Popover
* Hide Symbols overlay on blur of content editable
* Add specialKey to inputHandler and generalize how arrow movement is detected
- This way macOS users can use Ctrl-N to mean down, etc.
* Detect special key from within SymbolsOverlay
* Implement full backwards search while typing
* Allow navigating symbol menu and accepting with enter
* Add some entries to data-provider
* Satisfy eslint
* Generate symbolsTable from sources
* Use other github source, allow multiple names
In return, symbol must be unique
* Automatically scroll in symbols dropdown
* Use from npm packages rather than downloading from URL
* Remove console.log
* Remove print
* Add pointerDown event to input-handler
- so that SymbolsOverlay can reset on field click
* Make tab do the same as enter
* Make font a bit smaller but increase relative icon size
* Satisfy type requirement of handlerlist
* Revert changing default size of DropdownItems
* Remove some now unused code for bootstrap dropdowns
* Remove --medium-border variable
* Implement color palette using Sass maps
I hand-picked the gray tones, the other colors are from the Tailwind CSS v3 palette.
Significant changes:
- light theme is brighter
- dark theme is darker
- borders are softer
I also deleted some platform- and night-mode-specific code.
* Use custom colors for note view switch
* Use same placeholder color for all inputs
* Skew color palette for more dark values
by removing gray[3], which wasn't used anywhere. Slight adjustments were made to the darker tones.
* Adjust frame- window- and border colors
* Give deck browser entries --frame-bg as background color
* Define styling for QComboBox and QLineEdit globally
* Experiment with CSS filter for inline-colors
Inside darker inputs, some colors like dark blue will be hard to read, so we could try to improve text-color contrast with global adjustments depending on the theme.
* Use different map structure for _vars.scss
after @hgiesel's idea: https://github.com/ankitects/anki/pull/2016#discussion_r947087871
* Move custom QLineEdit styles out of searchbar.py
* Merge branch 'main' into color-palette
* Revert QComboBox stylesheet override
* Align gray color palette more with macOS
* Adjust light theme
* Add custom styling for Qt controls
* Use --slightly-grey-text for options tab color
* Replace gray tones with more neutral values
* Improve categorization of global colors
by renaming almost all of them and sorting them into separate maps.
* Saturate highlight-bg in light theme
* Tweak gray tones
* Adjust box-shadow of EditingArea to make fields look inset
* Add Sass functions to access color palette and semantic variables
in response to https://github.com/ankitects/anki/pull/2016#issuecomment-1220571076
* Showcase use of access functions in several locations
@hgiesel in buttons.scss I access the color palette directly. Is this what you meant by "... keep it local to the component, and possibly make it global at a later time ..."?
* Fix focus box shadow transition and remove default shadow for a cleaner look
I couldn't quite get the inset look the way I wanted, because inset box-shadows do not respect the border radius, therefore causing aliasing.
* Tweak light theme border and shadow colors
* Add functions and colors to base_lib
* Add vars_lib as dependency to base_lib and button_mixins_lib
* Improve uses of default-themed variables
* Use old --frame-bg color and use darker tone for canvas-default
* Return CSS var by default and add palette-of function for raw value
* Showcase use of palette-of function
The #{...} syntax is required only because the use cases are CSS var definitions. In other cases a simple palette-of(keyword, theme) would suffice.
* Light theme: decrease brightness of canvas-default and adjust fg-default
* Use canvas-inset variable for switch knob
* Adjust light theme
* Add back box-shadow to EditingArea
* Light theme: darken background and flatten transition
also set hue and saturation of gray-8 to 0 (like all the other grays).
* Reduce flag colors to single default value
* Tweak card/note accent colors
* Experiment with inset look for fields again
Is this too dark in night mode? It's the same color used for all other text inputs.
* Dark theme: make border-default one shade darker
* Tweak inset shadow color
* Dark theme: make border-faint darker than canvas-default
meaning two shades darker than it currently was.
* Fix PlainTextInput not expanding
* Dark theme: use less saturated flag colors
* Adjust gray tones
* Create stylesheet overrides for various Qt widgets
Including QPushButton, QComboBox, QSpinBox, QLineEdit, QListWidget, QTabWidget, QTreeWidget, QToolTip, QTableView, QScrollBar and sub-widgets.
* Make webview scrollbar look identical to Qt one
* Add blue colors for primary buttons
* Tweak disabled state of SpinBox button
* Apply styles to all platforms
mainly so people like @hgiesel can easily test the widget style overrides, but maybe you actually prefer them over the native ones, who knows :)
* Tweak webview button borders
* Add type annotations to eventFilter
* Adjust padding of QComboBox and its drop-down arrow
* Use isinstance for comparison
* Remove reimport of Any
* Revert "Merge branch 'redesign-test' into custom-qt-controls"
This reverts commit ff36297456b693a0d4b4b69f5f487ac1a01c1861, reversing
changes made to 6bb45355d143aa081d2d643933bd02ddc43206de.
* Add missing copyright header
* Left-align QTabWidget headers
* Exclude macOS from stylesheet overrides
* Fix failure to start on macOS (dae)
* Use standard macOS theme in dark mode (dae)
I believe this was originally behind a feature flag because the user
had to use a hack to get it to work
(https://forums.ankiweb.net/t/title-bar-dark-mode-fix-broken/1189),
and it did not work correctly when the system theme was changed.
Since the introduction of libankihelper and the app automatically
updating as the system theme changes, these issues no longer seem to
exist, and switching between light and dark appears to work consistently.
Pushed into this PR because it addresses the background color issue
mentioned in code review.
Closes#2054
* 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>
* Add animation toggle to preferences
and move settings affecting appearance together.
* Add class to body if animations unchecked
* Fix formatting in preferences.ftl
* Update duration(height) function for Collapsible transition
and add explanation.
* Fix formatting
* Increase duration baseline to 10 and decrease factor to 20
* Restore initial layout and rename option to "Reduce motion"
* Move checkboxes together and fix tab order (dae)
+ Remove separation of UI size
* 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.
* Add MessageBox class and associated funcs to aqt.utils and update some callers in aqt.sync and aqt.addons
* Cleanup imports in aqt.sync
* Fix return values for ask_user and ask_user_dialog
* Fix wrong argument name in aqt.utils.ask_user
* Add type annotations to **kwargs in utils.py
* Type annotation for callback in aqt.sync.full_sync
* MessageBox accepts StandardButton in addition to str, fix linting issues
* Assess default buttons in correct order and return correct button name in MessageBox
* Add explicit Optionals in aqt.utils
* Pass button index to callback in MessageBox
* Update type hints for aqt.utils.MessageBox
* Use Sequence for aqt.utils.MessageBox buttons arg
* default_button > default_yes in aqt.utils.ask_user
* Dark mode question icon in aqt.utils.MessageBox
* Remove overscroll-behavior: none for * (all elements)
* Revert "Remove overscroll-behavior: none for * (all elements)"
This reverts commit 189358908cecd03027e19d8fe47822735319ec17.
* Use body instead of *, but keep CSS rule
* Unify two CSS rules
* 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.
* Improve margins
* Remove right border on non-macOS systems
Would be interesting to know why this was implemented in the first place. Looks quite ugly on Linux.
* Add focus border
* Align height of toolbar icons with search bar
* Remove leftover f-strings
* call_add-on_update_after_initial_sync
* Add safeMode restriction
* check for anki update after other modal dialogs
* fix failing test
* make changes suggested in review
From [the documentation](https://docs.python.org/3.9/library/platform.html#platform.platform):
> Returns a single string identifying the underlying platform with as much useful information as possible.
The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended.
Changed in version 3.8: On macOS, the function now uses mac_ver(), if it returns a non-empty release string, to get the macOS version rather than the darwin version.
The main advantage of this change is that it provides the architecture of the platform, which is increasingly relevant as ARM systems are becoming more common.
The sidebar (QDockWidget) was not restored properly in some environments
when re-opening the browser if the browser was closed while maximized
under the condition that the window size in the normal window state was
very small.
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.
* 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.
* 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
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
* Add _bytes methods for all methods in the backend
Expose get_note in qt/aqt/mediasrv.py
* Satisfy formatter
* Rename _bytes function to _raw and have them bytes as input
* Fix backend generation
* Use lib/proto/deckOptions in deck-options
* Add exposed_backend to qt/aqt/mediasrv.py
* Move some more backend methods to exposed_backend_list
* Use protobufjs for congrats and i18n
* Use protobufjs for completeTag
* Use protobufjs services in change-notetype
* Reorder post handlers in alphabetical manner
* Satisfy tests
* Remove unused collection methods
* Rename access_backend to raw_backend_request
* Use _vendor.stringcase instead of creating a new function
* Remove SKIP_UNROLL_OUTPUT
* Directly call _run_command in non _raw methods
* Remove TranslateString, ChangeNotetype and CompleteTag from SKIP_UNROLL_INPUT
* Remove UpdateDeckConfigs from SKIP_UNROLL_INPUT
* Remove ChangeNotetype from SKIP_UNROLL_INPUT
* Remove SKIP_UNROLL_INPUT
* Fix typing issue with translate_string
- Adds typing support for Protobuf maps in genbackend.py
* Do not emit convenience method for protobuf TranslateString
* Implement custom study on backend
* Switch frontend to backend custom study
* Skip typecheck for new pb classes
* Build tag search string on backend
Also fixes escaping of special characters in tag names.
* `cram.cards` -> `cram.card_limit`
* Assign more meaningful names in `TagLimit`
* Broaden rustfmt glob
* Use `invalid_input()` helper
* Assign `FilteredDeckForUpdate` to temp var
* Implement `SearchBuilder`
* Rewrite `custom_study()` with `SearchBuilder`
* Replace match macros with `SearchBuilder`
* Remove `into_nodes_list` & `concatenate_searches`
* Make webview zoom optional
Also suppress mouse wheel zooming.
* Disable zoom for top and bottom bars in main view
* Factor in macos zoom by scrolling and refactor
* fix: AttributeError: 'QMouseEvent' object has no attribute 'pos'
```
Caught exception:
Traceback (most recent call last):
File "D:\Python\Python39\lib\site-packages\aqt\browser\sidebar\tree.py", line 328, in mouseReleaseEvent
if (index := self.currentIndex()) == self.indexAt(event.pos()):
d
```
* fix: AttributeError: 'QMouseEvent' object has no attribute 'pos'
* Move some AddCards specific code to NoteCreator.svelte
* Add new strings for Toggling the Visual / HTML editor
* Set LabelContainer vertical-align to text-top
- Makes them look more centered
* Remove appendInParentheses helper
* Make all ts/*.html files include only module.js and module.css
* Move any JS from .html to index files
* Remove .html files from ts modules
* Remove Python with Starlark implemenation
* Remove reference to non-existing file
* Remove deck-option.html as well
* fix change-notetype screen (dae)
* fix: try catch excepton on get_windows_dark_mode and global cache that check
* add commitor email to CONTRIBUTORS
* remove is_windows_dark_mode cache
* avoid logging the missing key (dae)
The check happens frequently, so this will fill up the user's console if we print it each time.
- The way mypy gathers site packages has changed slightly, so we had to
update extendsitepkgs.py to work with it.
- Not sure if there's a way to avoid the ignore in
operations/__init__.py. mypy is still ensuring a provided argument has
a .changes attribute, so thankfully we don't seem to have lost much here.
* Forbid inserting object and iframe tags via PlainTextInput
* Add optional browserMode parameter to Editor
* Create new ts modules for three editor instances
- note-creator for AddCards
- browser-editor for the editor in the Browser
- reviewer-editor for the EditCurrent
* Revert "Forbid inserting object and iframe tags via PlainTextInput"
This reverts commit ab90ae8194494d883a1863126496e2d8f332509e.
* Refactor browserMode to editorMode
* Move new editor variants inside /ts/editor directory
* Fix typo
* Fix cardtype icon, add flag-off icon, remove flag.svg
* This removes the old flag.svg, because mdi-icons also has
one icon called `flag.svg`, and there was undefined behavior
which flag icon was being picked, when requesting "flag.svg"
* Sort no-flag to beginning of subtree
* to match tags
* Allow customization of add-on config help path
This is useful for loading translated versions of the help file if available
* dir -> module
* Allow setting a callback instead to produce config docs
* Fix media playback not terminating when previewer is closed
https://forums.ankiweb.net/t/anki-2-1-50-beta/15608/78
* Fix _on_preview_closed being called twice unnecessarily
The function was being called twice when the preview button is clicked
while the previewer is open.
* Fix console error caused by leftover code
The following error was shown in the console when closing previewer:
`Uncaught TypeError: Cannot read property 'classList' of null`
* Toggle state of preview button via 'active' prop
* Support drag & drop in main window to import files
* Pass drag & drop events to super when not in deck browser
Seems this is required so that JS in the reviewer receives dragover
* Remove unused allowDrops
- Copy identical fields as before, but maintain a list of copied fields
and only add non-empty ones to it.
- Instead of setting remaining fields by their indices, assign remaining non-empty old fields to new fields sequentially
This results in less fields being lost when switching notetypes.
* Preload external css files to prevent flash of unstyled content
This is an implementation of the approach mentioned in the commit
message of 46b85d5.
* Tweak max_age value for css files
Ensure that css preloading works even on a slow PC.
We want to preserve the backend checks, because they may also detect
bugs. So we do the debouncing on the frontend instead, transitioning
into a temporary state until the background op completes.
https://forums.ankiweb.net/t/anki-2-1-50-beta/15608/74
When we updated to flask 2.0, the default caching time changed to
0. When setting the HTML of a new card side in the DOM, the browser
first removes the existing content (including styling), then sends a
HTTP request to us to check whether the file has changed or not. By the
time the answer has arrived, the browser has repainted without the
styling, and thus we get a flicker.
A side-effect of reverting to flask 1.x behaviour is that external changes
to media files will not be reflected in Anki for an hour, unless Anki
is restarted, or the caches are cleared manually with an add-on. An
alternative approach would be to pre-fetch the css files like we do with
images, but there are other things like fonts to think about as well.
Closes#1455
* Add "Show duplicates" to LabelContainer
* Avoid bubbling down the duplicate logic into EditorField
* Move duplicate link into its own slot
to center it between name/description and field-state.
* Revert "Move duplicate link into its own slot"
This reverts commit 3a4511042da7083a52d67b58550b13d873dcbea5.
* Justify dupes within FieldState
to achieve the same result as before while avoiding additional logic within EditorField.
Co-Authored-By: Henrik Giesel <hengiesel@gmail.com>
* Set QT_QPA_PLATFORM for Win on recent Qt versions
Erroneously dropped for Qt 5.15.1+.
* Enable original shortcut to create copy
* minor tweaks to comment to make it clearer (dae)
Kept the favicon, but have reverted the rest, as it unfortunately did
not seem to prevent the issue from occurring.
Original discussion: https://github.com/ankitects/anki/pull/1369
This reverts commit 6d0f7e7f05.
Fixes#983
This has been a long-standing issue that was infrequent enough on
developer machines that we weren't able to get to the bottom of it before
now. As luck would have it, the new ARM build had just the right timing
for this to occur every few invocations, and I was able to narrow it down
to the call that turns off the cache.
We don't really want the cache, so this is not a great solution. But I
ran into trouble when trying to figure out a better solution:
- Calling setHttpCacheType() earlier (eg immediately after creating the
page) fails.
- It even fails if you attempt to change the setting in the shared
default profile before any webviews are loaded:
```
def setupMainWindow(self) -> None:
QWebEngineProfile.defaultProfile().setHttpCacheType(QWebEngineProfile.HttpCacheType.NoCache)
```
- Creating a profile separately, and passing it into QWebEnginePage()
does work. But it introduces a warning each time a webview is deallocated,
and I fear it may lead to crashes:
```
Release of profile requested but WebEnginePage still not deleted. Expect troubles !
```
I tried various combinations of parents for the profile and page, and
turning web._page into an unretained property, but could not figure it out.
Some Googling pulls up a bunch of other people who seem to have hit similar
issues with PyQt. If anyone has any ideas, they'd be welcome; in the mean
time, I guess we're better off using up some of the user's disk
space than sometimes failing to load.
The profile-in-advance code I tried is below:
```
diff --git a/qt/aqt/webview.py b/qt/aqt/webview.py
index 1c96112d8..4f3e91284 100644
--- a/qt/aqt/webview.py
+++ b/qt/aqt/webview.py
@@ -23,9 +23,49 @@ serverbaseurl = re.compile(r"^.+:\/\/[^\/]+")
BridgeCommandHandler = Callable[[str], Any]
+def _create_profile(parent: QObject) -> QWebEngineProfile:
+ qwebchannel = ":/qtwebchannel/qwebchannel.js"
+ jsfile = QFile(qwebchannel)
+ if not jsfile.open(QIODevice.OpenModeFlag.ReadOnly):
+ print(f"Error opening '{qwebchannel}': {jsfile.error()}", file=sys.stderr)
+ jstext = bytes(cast(bytes, jsfile.readAll())).decode("utf-8")
+ jsfile.close()
+
+ script = QWebEngineScript()
+ script.setSourceCode(
+ jstext
+ + """
+ var pycmd, bridgeCommand;
+ new QWebChannel(qt.webChannelTransport, function(channel) {
+ bridgeCommand = pycmd = function (arg, cb) {
+ var resultCB = function (res) {
+ // pass result back to user-provided callback
+ if (cb) {
+ cb(JSON.parse(res));
+ }
+ }
+
+ channel.objects.py.cmd(arg, resultCB);
+ return false;
+ }
+ pycmd("domDone");
+ });
+ """
+ )
+ script.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
+ script.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
+ script.setRunsOnSubFrames(False)
+
+ profile = QWebEngineProfile(parent)
+ profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.NoCache)
+ profile.scripts().insert(script)
+ return profile
+
+
class AnkiWebPage(QWebEnginePage):
- def __init__(self, onBridgeCmd: BridgeCommandHandler) -> None:
- QWebEnginePage.__init__(self)
+ def __init__(self, onBridgeCmd: BridgeCommandHandler, parent: QObject) -> None:
+ profile = _create_profile(parent)
+ QWebEnginePage.__init__(self, profile, parent)
self._onBridgeCmd = onBridgeCmd
self._setupBridge()
self.open_links_externally = True
@@ -46,39 +86,6 @@ class AnkiWebPage(QWebEnginePage):
self._channel.registerObject("py", self._bridge)
self.setWebChannel(self._channel)
- qwebchannel = ":/qtwebchannel/qwebchannel.js"
- jsfile = QFile(qwebchannel)
- if not jsfile.open(QIODevice.OpenModeFlag.ReadOnly):
- print(f"Error opening '{qwebchannel}': {jsfile.error()}", file=sys.stderr)
- jstext = bytes(cast(bytes, jsfile.readAll())).decode("utf-8")
- jsfile.close()
-
- script = QWebEngineScript()
- script.setSourceCode(
- jstext
- + """
- var pycmd, bridgeCommand;
- new QWebChannel(qt.webChannelTransport, function(channel) {
- bridgeCommand = pycmd = function (arg, cb) {
- var resultCB = function (res) {
- // pass result back to user-provided callback
- if (cb) {
- cb(JSON.parse(res));
- }
- }
-
- channel.objects.py.cmd(arg, resultCB);
- return false;
- }
- pycmd("domDone");
- });
- """
- )
- script.setWorldId(QWebEngineScript.ScriptWorldId.MainWorld)
- script.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady)
- script.setRunsOnSubFrames(False)
- self.profile().scripts().insert(script)
-
def javaScriptConsoleMessage(
self,
level: QWebEnginePage.JavaScriptConsoleMessageLevel,
@@ -228,7 +235,7 @@ class AnkiWebView(QWebEngineView):
) -> None:
QWebEngineView.__init__(self, parent=parent)
self.set_title(title)
- self._page = AnkiWebPage(self._onBridgeCmd)
+ self._page = AnkiWebPage(self._onBridgeCmd, self)
self._page.setBackgroundColor(
self.get_window_bg_color(theme_manager.night_mode)
@@ -242,7 +249,6 @@ class AnkiWebView(QWebEngineView):
self.requiresCol = True
self.setPage(self._page)
- self._page.profile().setHttpCacheType(QWebEngineProfile.HttpCacheType.NoCache)
self.resetHandlers()
self.allowDrops = False
self._filterSet = False
```
This was motivated by the fact that recording was crashing on the native
M1 build. That ended up being mostly a PEBKAC problem - turns out the
Mac Mini has no built-in microphone 🤦.
I still thinks this has some value though - it doesn't crash in such
cases, and probably doesn't suffer from the problem shown in this thread
either:
https://forums.ankiweb.net/t/anki-crashes-when-trying-to-record-on-mac/14764
For now, this is only enabled when running on arm64. If it turns out to
be reliable, it could be offered as an option on amd64 as well.
* Update about.py
* Add cqg to list
for his contributions to the community (testing, support, suggestions).
* Add the AnKing to list
for his efforts to keep add-ons compatible with new versions and popularizing Anki in the medical community via YouTube, Reddit and other social media.
* Flip arrows of Bootstrap-styled <select>s for RTL langs
* Use the dir attribute to set document direction
* Remove unused variable and fix use of CSS var
* Remove unneeded old.note_type() call
Fixes TypeError thrown after deleting a notetype that's currently selected in the editor.
* Handle IndexError on notetype change
Occurs in the Add window when changing the notetype via NotetypeChooser from
- the notetype that's auto-selected after deleting the currently selected notetype
- to a notetype with fewer fields than the auto-selected one
* Add return to exception handler
to properly ignore the command.
The packaged builds of 2.1.50 use python -OO, which means our assertion
statements won't be run. This is not an issue for unit tests (as we
don't run them from a packaged build), or for type assertions (which are
added for mypy's benefit), but we do need to ensure that invariant checks
are still run.
* Allow theme change at runtime and add hook
* Save or restore default palette on theme change
* Update aqt widget styles on theme change
* styling fixes
- drop _light_palette, as default_palette serves the same purpose
- save default platform theme, and restore it when switching away
from nightmode
- update macOS light/dark mode on theme switch
- fix unreadable menus on Windows
* update night-mode classes on theme change
This is the easy part - CSS styling that uses standard_css or our
css variables should update automatically. The main remaining issue
is JS code that sets colors based on the theme at the time it's run -
eg the graph code, and the editor.
* switch night mode value on toggle
* expose current theme via a store; switch graphs to use it
https://github.com/ankitects/anki/issues/1471#issuecomment-972402492
* start using currentTheme in editor/components
This fixes basic editing - there are still components that need updating.
* add simple xcodeproj for code completion
* add helper to get currently-active system theme on macOS
* fix setCurrentTheme not being immediately available
* live update tag color
* style().name() doesn't work on Qt5
* automatic theme switching on Windows/Mac
* currentTheme -> pageTheme
* Replace `nightModeKey` with `pageTheme`
Co-authored-by: Damien Elmes <gpg@ankiweb.net>
* Enable access to old notetype name
* Set minimum height for ChangeNotetypeDialog
* Add bootstrap icons to change-notetype
* Move alert up and make it collapsible
* Tweak some CSS
- Add variables --sticky-bg and --sticky-border to StickyContainer
- Tweak base.css
* Add translatable string "(Nothing)"
* Rework ChangeNotetype screen
* Initially load option at newIndex and remaining options on focus
Optimization for big notetypes:
Should increase efficiency from O(n²) to O(n). Test on notetype with 500 templates shows significant improvement in load time (~10s down to ~1s).
* Try to satisfy rust test
* Change arrow direction depending on reading direction
+ add 0.5em top padding to main
* Create Alert.svelte
* Introduce CSS variable --pane-bg
* Revert "Initially load option at newIndex and remaining options on focus"
This reverts commit f42beee45c27dba9433d76217fb583b117fb5231.
* Final cleanup
* Refine padding/gutter
Older Anki versions like 2.1.35 used sip 5.2, which appears to
(presumably incorrectly) serialize QByteArrays as Unicode:
0: ( MARK
1: d DICT (MARK at 0)
2: p PUT 0
5: V UNICODE 'mainWindowGeom'
21: p PUT 1
24: c GLOBAL 'sip _unpickle_type'
44: p PUT 2
47: ( MARK
48: V UNICODE 'PyQt5.QtCore'
62: p PUT 3
65: V UNICODE 'QByteArray'
77: p PUT 4
80: ( MARK
81: c GLOBAL '_codecs encode'
97: p PUT 5
100: ( MARK
101: V UNICODE "[...]"
354: p PUT 6
357: V UNICODE 'latin1'
365: p PUT 7
368: t TUPLE (MARK at 100)
Our unpickle_type() was incorrectly ignoring any non-PyQt class when
unpickling, so it was choking on the reference to _codecs.