anki/qt/aqt/switch.py

181 lines
5.8 KiB
Python
Raw Normal View History

2021-03-29 12:19:48 +02:00
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import cast
2021-03-29 12:19:48 +02:00
from aqt import colors
from aqt.qt import *
from aqt.theme import theme_manager
class Switch(QAbstractButton):
"""A horizontal slider to toggle between two states which can be denoted by strings and/or QIcons.
2021-03-31 18:53:36 +02:00
The left state is the default and corresponds to isChecked()=False.
The suppoorted slots are toggle(), for an animated transition, and setChecked().
2021-03-29 12:19:48 +02:00
"""
def __init__(
self,
radius: int = 10,
left_label: str = "",
right_label: str = "",
Introduce new color palette using Sass maps (#2016) * 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
2022-09-16 06:11:18 +02:00
left_color: tuple[str, str] = colors.ACCENT_CARD,
right_color: tuple[str, str] = colors.ACCENT_NOTE,
2021-03-29 12:19:48 +02:00
parent: QWidget = None,
) -> None:
super().__init__(parent=parent)
self.setCheckable(True)
super().setChecked(False)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
2021-03-29 12:19:48 +02:00
self._left_label = left_label
self._right_label = right_label
self._left_color = left_color
self._right_color = right_color
self._path_radius = radius
self._knob_radius = radius - 2
self._label_padding = 4
self._left_knob_position = self._position = radius
self._right_knob_position = self.width - self._path_radius
self._left_label_position = self._label_padding / 2
self._right_label_position = 2 * self._knob_radius
2021-03-29 12:19:48 +02:00
@pyqtProperty(int) # type: ignore
def position(self) -> int:
return self._position
@position.setter # type: ignore
def position(self, position: int) -> None:
self._position = position
self.update()
@property
def start_position(self) -> int:
return (
self._left_knob_position if self.isChecked() else self._right_knob_position
)
2021-03-29 12:19:48 +02:00
@property
def end_position(self) -> int:
return (
self._right_knob_position if self.isChecked() else self._left_knob_position
)
2021-03-29 12:19:48 +02:00
@property
def label(self) -> str:
return self._right_label if self.isChecked() else self._left_label
2021-03-29 12:19:48 +02:00
@property
def path_color(self) -> QColor:
color = self._right_color if self.isChecked() else self._left_color
return theme_manager.qcolor(color)
@property
def label_width(self) -> int:
font = QFont()
font.setPixelSize(int(self._knob_radius))
font.setWeight(QFont.Weight.Bold)
fm = QFontMetrics(font)
return (
max(
fm.horizontalAdvance(self._left_label),
fm.horizontalAdvance(self._right_label),
)
+ 2 * self._label_padding
)
@property
def width(self) -> int:
return self.label_width + 2 * self._path_radius
@property
def height(self) -> int:
return 2 * self._path_radius
2021-03-29 12:19:48 +02:00
def sizeHint(self) -> QSize:
return QSize(
self.width,
self.height,
2021-03-29 12:19:48 +02:00
)
def setChecked(self, checked: bool) -> None:
super().setChecked(checked)
self._position = self.end_position
self.update()
def paintEvent(self, _event: QPaintEvent) -> None:
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setPen(Qt.PenStyle.NoPen)
2021-03-29 12:19:48 +02:00
self._paint_path(painter)
self._paint_label(painter)
self._paint_knob(painter)
2021-03-29 12:19:48 +02:00
def _current_path_rectangle(self) -> QRectF:
return QRectF(
0,
0,
self.width,
self.height,
)
def _current_label_rectangle(self) -> QRectF:
return QRectF(
self._left_label_position
if self.isChecked()
else self._right_label_position,
0,
self.label_width,
self.height,
2021-03-29 12:19:48 +02:00
)
def _current_knob_rectangle(self) -> QRectF:
return QRectF(
self.position - self._knob_radius, # type: ignore
2,
2021-03-29 12:19:48 +02:00
2 * self._knob_radius,
2 * self._knob_radius,
)
def _paint_path(self, painter: QPainter) -> None:
painter.setBrush(QBrush(self.path_color))
painter.drawRoundedRect(
self._current_path_rectangle(), self._path_radius, self._path_radius
)
2021-03-29 12:19:48 +02:00
def _paint_knob(self, painter: QPainter) -> None:
Introduce new color palette using Sass maps (#2016) * 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
2022-09-16 06:11:18 +02:00
color = theme_manager.qcolor(colors.BUTTON_GRADIENT_START)
painter.setPen(Qt.PenStyle.NoPen)
2021-05-24 03:31:56 +02:00
painter.setBrush(QBrush(color))
2021-03-29 12:19:48 +02:00
painter.drawEllipse(self._current_knob_rectangle())
def _paint_label(self, painter: QPainter) -> None:
painter.setPen(theme_manager.qcolor(colors.CANVAS))
2021-03-29 12:19:48 +02:00
font = painter.font()
font.setPixelSize(int(self._knob_radius))
font.setWeight(QFont.Weight.Bold)
2021-03-29 12:19:48 +02:00
painter.setFont(font)
painter.drawText(
self._current_label_rectangle(), Qt.AlignmentFlag.AlignCenter, self.label
)
2021-03-29 12:19:48 +02:00
def mouseReleaseEvent(self, event: QMouseEvent) -> None:
super().mouseReleaseEvent(event)
if event.button() == Qt.MouseButton.LeftButton:
2021-03-31 18:53:36 +02:00
self._animate_toggle()
2021-03-29 12:19:48 +02:00
def enterEvent(self, event: QEnterEvent) -> None:
self.setCursor(Qt.CursorShape.PointingHandCursor)
2021-03-29 12:19:48 +02:00
super().enterEvent(event)
2021-03-31 18:53:36 +02:00
def toggle(self) -> None:
super().toggle()
self._animate_toggle()
def _animate_toggle(self) -> None:
animation = QPropertyAnimation(self, cast(QByteArray, b"position"), self)
2021-03-31 18:53:36 +02:00
animation.setDuration(100)
animation.setStartValue(self.start_position)
animation.setEndValue(self.end_position)
# make triggered events execute first so the animation runs smoothly afterwards
QTimer.singleShot(50, animation.start)