anki/qt/aqt/preferences.py

389 lines
15 KiB
Python
Raw Normal View History

2019-02-05 04:59:03 +01:00
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import re
from typing import Any, cast
import anki.lang
import aqt
import aqt.forms
import aqt.operations
from anki.collection import OpChanges
from anki.consts import new_card_scheduling_labels
from aqt import AnkiQt, gui_hooks
from aqt.operations.collection import set_preferences
from aqt.profiles import VideoDriver
2019-12-20 10:19:03 +01:00
from aqt.qt import *
from aqt.theme import Theme
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
from aqt.utils import (
HelpPage,
disable_help_button,
is_win,
openHelp,
showInfo,
showWarning,
tr,
)
2019-12-20 10:19:03 +01:00
class Preferences(QDialog):
2021-02-01 14:28:21 +01:00
def __init__(self, mw: AnkiQt) -> None:
QDialog.__init__(self, mw, Qt.WindowType.Window)
self.mw = mw
self.prof = self.mw.pm.profile
self.form = aqt.forms.preferences.Ui_Preferences()
self.form.setupUi(self)
disable_help_button(self)
self.form.buttonBox.button(QDialogButtonBox.StandardButton.Help).setAutoDefault(
False
)
self.form.buttonBox.button(
QDialogButtonBox.StandardButton.Close
).setAutoDefault(False)
qconnect(
self.form.buttonBox.helpRequested, lambda: openHelp(HelpPage.PREFERENCES)
)
self.silentlyClose = True
self.setup_collection()
self.setup_profile()
self.setup_global()
self.show()
2021-02-01 14:28:21 +01:00
def accept(self) -> None:
# avoid exception if main window is already closed
if not self.mw.col:
return
def after_collection_update() -> None:
self.update_profile()
self.update_global()
self.mw.pm.save()
self.done(0)
aqt.dialogs.markClosed("Preferences")
self.update_collection(after_collection_update)
2021-02-01 14:28:21 +01:00
def reject(self) -> None:
self.accept()
# Preferences stored in the collection
######################################################################
def setup_collection(self) -> None:
self.prefs = self.mw.col.get_preferences()
form = self.form
scheduling = self.prefs.scheduling
version = scheduling.scheduler_version
form.dayLearnFirst.setVisible(version == 2)
form.legacy_timezone.setVisible(version >= 2)
form.newSpread.setVisible(version < 3)
2021-05-27 15:09:49 +02:00
form.sched2021.setVisible(version >= 2)
form.lrnCutoff.setValue(int(scheduling.learn_ahead_secs / 60.0))
form.newSpread.addItems(list(new_card_scheduling_labels(self.mw.col).values()))
form.newSpread.setCurrentIndex(scheduling.new_review_mix)
form.dayLearnFirst.setChecked(scheduling.day_learn_first)
form.dayOffset.setValue(scheduling.rollover)
form.legacy_timezone.setChecked(not scheduling.new_timezone)
2021-05-27 15:09:49 +02:00
form.sched2021.setChecked(version == 3)
reviewing = self.prefs.reviewing
form.timeLimit.setValue(int(reviewing.time_limit_secs / 60.0))
form.showEstimates.setChecked(reviewing.show_intervals_on_buttons)
form.showProgress.setChecked(reviewing.show_remaining_due_counts)
form.showPlayButtons.setChecked(not reviewing.hide_audio_play_buttons)
form.interrupt_audio.setChecked(reviewing.interrupt_audio_when_answering)
editing = self.prefs.editing
form.useCurrent.setCurrentIndex(
0 if editing.adding_defaults_to_current_deck else 1
)
form.paste_strips_formatting.setChecked(editing.paste_strips_formatting)
form.ignore_accents_in_search.setChecked(editing.ignore_accents_in_search)
form.pastePNG.setChecked(editing.paste_images_as_png)
form.default_search_text.setText(editing.default_search_text)
Backups (#1685) * 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>
2022-03-07 06:11:31 +01:00
form.backup_explanation.setText(
anki.lang.with_collapsed_whitespace(tr.preferences_backup_explanation())
)
form.daily_backups.setValue(self.prefs.backups.daily)
form.weekly_backups.setValue(self.prefs.backups.weekly)
form.monthly_backups.setValue(self.prefs.backups.monthly)
Backup improvements (#1728) * 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
2022-03-21 10:40:42 +01:00
form.minutes_between_backups.setValue(self.prefs.backups.minimum_interval_mins)
Backups (#1685) * 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>
2022-03-07 06:11:31 +01:00
def update_collection(self, on_done: Callable[[], None]) -> None:
form = self.form
scheduling = self.prefs.scheduling
scheduling.new_review_mix = cast(Any, form.newSpread.currentIndex())
scheduling.learn_ahead_secs = form.lrnCutoff.value() * 60
scheduling.day_learn_first = form.dayLearnFirst.isChecked()
scheduling.rollover = form.dayOffset.value()
scheduling.new_timezone = not form.legacy_timezone.isChecked()
reviewing = self.prefs.reviewing
reviewing.show_remaining_due_counts = form.showProgress.isChecked()
reviewing.show_intervals_on_buttons = form.showEstimates.isChecked()
reviewing.time_limit_secs = form.timeLimit.value() * 60
reviewing.hide_audio_play_buttons = not self.form.showPlayButtons.isChecked()
reviewing.interrupt_audio_when_answering = self.form.interrupt_audio.isChecked()
editing = self.prefs.editing
editing.adding_defaults_to_current_deck = not form.useCurrent.currentIndex()
editing.paste_images_as_png = self.form.pastePNG.isChecked()
editing.paste_strips_formatting = self.form.paste_strips_formatting.isChecked()
editing.default_search_text = self.form.default_search_text.text()
editing.ignore_accents_in_search = (
self.form.ignore_accents_in_search.isChecked()
)
Backups (#1685) * 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>
2022-03-07 06:11:31 +01:00
self.prefs.backups.daily = form.daily_backups.value()
self.prefs.backups.weekly = form.weekly_backups.value()
self.prefs.backups.monthly = form.monthly_backups.value()
Backup improvements (#1728) * 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
2022-03-21 10:40:42 +01:00
self.prefs.backups.minimum_interval_mins = form.minutes_between_backups.value()
Backups (#1685) * 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>
2022-03-07 06:11:31 +01:00
def after_prefs_update(changes: OpChanges) -> None:
self.mw.apply_collection_options()
if scheduling.scheduler_version > 1:
want_v3 = form.sched2021.isChecked()
if self.mw.col.v3_scheduler() != want_v3:
self.mw.col.set_v3_scheduler(want_v3)
gui_hooks.operation_did_execute(OpChanges(study_queues=True), None)
on_done()
set_preferences(parent=self, preferences=self.prefs).success(
after_prefs_update
).run_in_background()
2021-05-27 15:09:49 +02:00
# Preferences stored in the profile
######################################################################
def setup_profile(self) -> None:
"Setup options stored in the user profile."
self.setup_network()
def update_profile(self) -> None:
self.update_network()
# Profile: network
######################################################################
def setup_network(self) -> None:
2021-03-26 04:48:26 +01:00
self.form.media_log.setText(tr.sync_media_log_button())
qconnect(self.form.media_log.clicked, self.on_media_log)
self.form.syncOnProgramOpen.setChecked(self.mw.pm.auto_syncing_enabled())
self.form.syncMedia.setChecked(self.mw.pm.media_syncing_enabled())
self.form.autoSyncMedia.setChecked(self.mw.pm.auto_sync_media_minutes() != 0)
if not self.prof.get("syncKey"):
self._hide_sync_auth_settings()
else:
2019-12-23 01:34:10 +01:00
self.form.syncUser.setText(self.prof.get("syncUser", ""))
qconnect(self.form.syncDeauth.clicked, self.sync_logout)
2021-03-26 04:48:26 +01:00
self.form.syncDeauth.setText(tr.sync_log_out_button())
Rework syncing code, and replace local sync server (#2329) 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.
2023-01-18 03:43:46 +01:00
self.form.custom_sync_url.setText(self.mw.pm.custom_sync_url())
self.form.network_timeout.setValue(self.mw.pm.network_timeout())
2021-02-01 14:28:21 +01:00
def on_media_log(self) -> None:
self.mw.media_syncer.show_sync_log()
def _hide_sync_auth_settings(self) -> None:
self.form.syncDeauth.setVisible(False)
2013-10-03 23:09:36 +02:00
self.form.syncUser.setText("")
2019-12-23 01:34:10 +01:00
self.form.syncLabel.setText(
2021-03-26 04:48:26 +01:00
tr.preferences_synchronizationnot_currently_enabled_click_the_sync()
2019-12-23 01:34:10 +01:00
)
def sync_logout(self) -> None:
2020-02-15 08:48:35 +01:00
if self.mw.media_syncer.is_syncing():
showWarning("Can't log out while sync in progress.")
return
2019-12-23 01:34:10 +01:00
self.prof["syncKey"] = None
2020-02-15 08:48:35 +01:00
self.mw.col.media.force_resync()
self._hide_sync_auth_settings()
def update_network(self) -> None:
2019-12-23 01:34:10 +01:00
self.prof["autoSync"] = self.form.syncOnProgramOpen.isChecked()
self.prof["syncMedia"] = self.form.syncMedia.isChecked()
2020-07-01 06:01:24 +02:00
self.mw.pm.set_auto_sync_media_minutes(
self.form.autoSyncMedia.isChecked() and 15 or 0
)
if self.form.fullSync.isChecked():
2021-06-27 07:12:22 +02:00
self.mw.col.mod_schema(check=False)
Rework syncing code, and replace local sync server (#2329) 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.
2023-01-18 03:43:46 +01:00
self.mw.pm.set_custom_sync_url(self.form.custom_sync_url.text())
self.mw.pm.set_network_timeout(self.form.network_timeout.value())
# Global preferences
######################################################################
def setup_global(self) -> None:
"Setup options global to all profiles."
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
self.form.reduce_motion.setChecked(self.mw.pm.reduce_motion())
qconnect(self.form.reduce_motion.stateChanged, self.mw.pm.set_reduce_motion)
self.form.minimalist_mode.setChecked(self.mw.pm.minimalist_mode())
qconnect(self.form.minimalist_mode.stateChanged, self.mw.pm.set_minimalist_mode)
self.form.spacebar_rates_card.setChecked(self.mw.pm.spacebar_rates_card())
qconnect(
self.form.spacebar_rates_card.stateChanged,
self.mw.pm.set_spacebar_rates_card,
)
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
hide_choices = [tr.preferences_full_screen_only(), tr.preferences_always()]
self.form.hide_top_bar.setChecked(self.mw.pm.hide_top_bar())
qconnect(self.form.hide_top_bar.stateChanged, self.mw.pm.set_hide_top_bar)
qconnect(
self.form.hide_top_bar.stateChanged,
self.form.topBarComboBox.setVisible,
)
self.form.topBarComboBox.addItems(hide_choices)
self.form.topBarComboBox.setCurrentIndex(self.mw.pm.top_bar_hide_mode())
self.form.topBarComboBox.setVisible(self.form.hide_top_bar.isChecked())
qconnect(
self.form.topBarComboBox.currentIndexChanged,
self.mw.pm.set_top_bar_hide_mode,
)
self.form.hide_bottom_bar.setChecked(self.mw.pm.hide_bottom_bar())
qconnect(self.form.hide_bottom_bar.stateChanged, self.mw.pm.set_hide_bottom_bar)
qconnect(
self.form.hide_bottom_bar.stateChanged,
self.form.bottomBarComboBox.setVisible,
)
self.form.bottomBarComboBox.addItems(hide_choices)
self.form.bottomBarComboBox.setCurrentIndex(self.mw.pm.bottom_bar_hide_mode())
self.form.bottomBarComboBox.setVisible(self.form.hide_bottom_bar.isChecked())
qconnect(
self.form.bottomBarComboBox.currentIndexChanged,
self.mw.pm.set_bottom_bar_hide_mode,
)
self.form.uiScale.setValue(int(self.mw.pm.uiScale() * 100))
themes = [
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
tr.preferences_theme_follow_system(),
tr.preferences_theme_light(),
tr.preferences_theme_dark(),
]
self.form.theme.addItems(themes)
self.form.theme.setCurrentIndex(self.mw.pm.theme().value)
qconnect(self.form.theme.currentIndexChanged, self.on_theme_changed)
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
self.form.styleComboBox.addItems(["Anki"] + (["Native"] if not is_win else []))
self.form.styleComboBox.setCurrentIndex(self.mw.pm.get_widget_style())
qconnect(
self.form.styleComboBox.currentIndexChanged,
self.mw.pm.set_widget_style,
)
self.form.styleLabel.setVisible(not is_win)
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
self.form.styleComboBox.setVisible(not is_win)
self.form.legacy_import_export.setChecked(self.mw.pm.legacy_import_export())
qconnect(self.form.resetWindowSizes.clicked, self.on_reset_window_sizes)
self.setup_language()
self.setup_video_driver()
self.setupOptions()
def update_global(self) -> None:
restart_required = False
self.update_video_driver()
2019-12-23 01:34:10 +01:00
newScale = self.form.uiScale.value() / 100
2019-12-19 00:58:16 +01:00
if newScale != self.mw.pm.uiScale():
self.mw.pm.setUiScale(newScale)
restart_required = True
self.mw.pm.set_legacy_import_export(self.form.legacy_import_export.isChecked())
if restart_required:
2021-03-26 04:48:26 +01:00
showInfo(tr.preferences_changes_will_take_effect_when_you())
self.updateOptions()
def on_theme_changed(self, index: int) -> None:
self.mw.set_theme(Theme(index))
def on_reset_window_sizes(self) -> None:
regexp = re.compile(r"(Geom(etry)?|State|Splitter|Header)(\d+.\d+)?$")
for key in list(self.prof.keys()):
if regexp.search(key):
del self.prof[key]
showInfo(tr.preferences_reset_window_sizes_complete())
# legacy - one of Henrik's add-ons is currently wrapping them
def setupOptions(self) -> None:
pass
def updateOptions(self) -> None:
pass
# Global: language
######################################################################
def setup_language(self) -> None:
f = self.form
f.lang.addItems([x[0] for x in anki.lang.langs])
f.lang.setCurrentIndex(self.current_lang_index())
qconnect(f.lang.currentIndexChanged, self.on_language_index_changed)
def current_lang_index(self) -> int:
codes = [x[1] for x in anki.lang.langs]
PEP8 for rest of pylib (#1451) * PEP8 dbproxy.py * PEP8 errors.py * PEP8 httpclient.py * PEP8 lang.py * PEP8 latex.py * Add decorator to deprectate key words * Make replacement for deprecated attribute optional * Use new helper `_print_replacement_warning()` * PEP8 media.py * PEP8 rsbackend.py * PEP8 sound.py * PEP8 stdmodels.py * PEP8 storage.py * PEP8 sync.py * PEP8 tags.py * PEP8 template.py * PEP8 types.py * Fix DeprecatedNamesMixinForModule The class methods need to be overridden with instance methods, so every module has its own dicts. * Use `# pylint: disable=invalid-name` instead of id * PEP8 utils.py * Only decorate `__getattr__` with `@no_type_check` * Fix mypy issue with snakecase Importing it from `anki._vendor` raises attribute errors. * Format * Remove inheritance of DeprecatedNamesMixin There's almost no shared code now and overriding classmethods with instance methods raises mypy issues. * Fix traceback frames of deprecation warnings * remove fn/TimedLog (dae) Neither Anki nor add-ons appear to have been using it * fix some issues with stringcase use (dae) - the wheel was depending on the PyPI version instead of our vendored version - _vendor:stringcase should not have been listed in the anki py_library. We already include the sources in py_srcs, and need to refer to them directly. By listing _vendor:stringcase as well, we were making a top-level stringcase library available, which would have only worked for distributing because the wheel definition was also incorrect. - mypy errors are what caused me to mistakenly add the above - they were because the type: ignore at the top of stringcase.py was causing mypy to completely ignore the file, so it was not aware of any attributes it contained.
2021-10-25 06:50:13 +02:00
lang = anki.lang.current_lang
if lang in anki.lang.compatMap:
lang = anki.lang.compatMap[lang]
else:
lang = lang.replace("-", "_")
try:
return codes.index(lang)
except:
return codes.index("en_US")
def on_language_index_changed(self, idx: int) -> None:
code = anki.lang.langs[idx][1]
self.mw.pm.setLang(code)
2021-03-26 04:48:26 +01:00
showInfo(tr.preferences_please_restart_anki_to_complete_language(), parent=self)
# Global: video driver
######################################################################
def setup_video_driver(self) -> None:
self.video_drivers = VideoDriver.all_for_platform()
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
names = [video_driver_name_for_platform(d) for d in self.video_drivers]
self.form.video_driver.addItems(names)
self.form.video_driver.setCurrentIndex(
self.video_drivers.index(self.mw.pm.video_driver())
)
Revamp Preferences, implement Minimalist Mode and Qt widget gallery to test GUI changes (#2289) * Create widget gallery dialog * Add WidgetGallery to debug dialog * Use enum for its intended purpose * Rename "reduced-motion" to "reduce-motion" * Add another border-radius value and make former large radius a bit smaller. * Revamp preferences, add minimalist mode Also: - create additional and missing widget styles and tweak existing ones - use single profile entry to set widget styles and reduce choices to Anki and Native * Indent QTabBar style definitions * Add missing styles for QPushButton states * Fix QTableView background * Remove unused layout from Preferences * Fix QTabView focused tab style * Highlight QCheckBox and QRadioButton when focused * Fix toolbar styles * Reorder preferences * Add setting to hide bottom toolbar * Move toolbar settings above minimalist modes * Remove unused lines * Implement proper full-screen mode * Sort imports * Tweak deck overview appearance in minimalist mode * Undo TitledContainer changes since nobody asked for that * Remove dynamic toolbar background from minimalist mode * Tweak buttons in minimalist mode * Fix some issues * Reduce theme check interval to 5s on Linux * Increase hide timer interval to 2s * Collapse toolbars with slight delay when moving to review state This should ensure the bottom toolbar collapses too. * Allow users to make hiding exclusive to full screen * Rename full screen option * Fix hide mode dropdown ignoring checkbox state on startup * Fix typing issue * Refine background image handling Giving the toolbar body the main webview height ensures background-size: cover behaves exactly the same. To prevent an override of other background properties, users are advised to only set background-images via the background-image property, not the background shorthand. * Fix top toolbar getting huge when switching modes The issue was caused by the min-height hack to align the background images. A call to web.adjustHeightToFit would set the toolbar to the same height as the main webview, as the function makes use of document.offsetHeight. * Prevent scrollbar from appearing on bottom toolbar resize * Cleanup * Put review tab before editing; fix some tab orders * Rename 'network' to 'syncing' * Fix bottom toolbar disappearing on UI > 100 * Improve Preferences layout by adding vertical spacers to the bottom also make the hiding of video_driver and its label more obvious in preferences.py. * Fix bottom toolbar animating on startup Also fix bottom toolbar not appearing when unchecking hide mode in reviewer. * Hide/Show menubar in fullscreen mode along with toolbar * Attempt to fix broken native theme on macOS * Format * Improve native theme on other systems by not forcing palette with the caveat that theme switching can get weird. * Fix theme switching in native style * Remove redundant condition * Add back check for Qt5 to prevent theme issues * Add check for macOS before setting fusion theme * Do not force scrollbar styles on macOS * Remove all of that crazy theme logic * Use canvas instead of button-bg for ColorRole.Button * Make sure Anki style is always based on Fusion otherwise we can't guarantee the same look on all systems. * Explicitly apply default style when Anki style is not selected This should fix the style not switching back after it was selected. * Remove reduncant default_palette * Revert 8af4c1cc2 On Mac with native theme, both Qt5 and Qt6 look correct already. On the Anki theme, without this change, we get the fusion-style scrollbars instead of the rounded ones. * Rename AnkiStyles enum to WidgetStyle * Fix theme switching shades on same theme * Format * Remove unused placeholderText that caused an error when opening the widget gallery on Qt5. * Check for full screen windowState using bitwise operator to prevent error in Qt5. Credit: https://stackoverflow.com/a/65425151 * Hide style option on Windows also exclude native option from dropdown just in case. * Format * Minor naming tweak
2023-01-18 12:24:16 +01:00
if qtmajor > 5:
self.form.video_driver_label.setVisible(False)
self.form.video_driver.setVisible(False)
def update_video_driver(self) -> None:
new_driver = self.video_drivers[self.form.video_driver.currentIndex()]
if new_driver != self.mw.pm.video_driver():
self.mw.pm.set_video_driver(new_driver)
2021-03-26 04:48:26 +01:00
showInfo(tr.preferences_changes_will_take_effect_when_you())
def video_driver_name_for_platform(driver: VideoDriver) -> str:
if driver == VideoDriver.ANGLE:
2021-03-26 04:48:26 +01:00
return tr.preferences_video_driver_angle()
elif driver == VideoDriver.Software:
if is_mac:
2021-03-26 04:48:26 +01:00
return tr.preferences_video_driver_software_mac()
else:
2021-03-26 04:48:26 +01:00
return tr.preferences_video_driver_software_other()
else:
if is_mac:
2021-03-26 04:48:26 +01:00
return tr.preferences_video_driver_opengl_mac()
else:
2021-03-26 04:48:26 +01:00
return tr.preferences_video_driver_opengl_other()