diff --git a/src/tagstudio/previews/base_preview.py b/src/tagstudio/previews/base_preview.py index b8444bd5f6..98c2fc8518 100644 --- a/src/tagstudio/previews/base_preview.py +++ b/src/tagstudio/previews/base_preview.py @@ -17,13 +17,11 @@ class BasePreview: """A base preview renderer class. Attributes: - _fallback_icon (str): The name of the fallback icon resource to use, if needed. has_small_variant (bool): Whether `is_small` renders a different image than the preview. media_type_name (str): Used for identifying the MediaType. priority (int): Render priority over other Preview classes. """ - _fallback_icon: str = "" has_small_variant: bool = False media_type_name: str priority: int = 50 @@ -45,8 +43,3 @@ def render( dpi_scale: float, ) -> Image | None: raise NotImplementedError - - @classmethod - def icon_name(cls) -> str: - """Get the name of the fallback icon resource associated with this renderer.""" - return cls._fallback_icon or cls.media_type_name diff --git a/src/tagstudio/previews/file_renderer.py b/src/tagstudio/previews/file_renderer.py index b3de56cb3c..80af6dfb00 100644 --- a/src/tagstudio/previews/file_renderer.py +++ b/src/tagstudio/previews/file_renderer.py @@ -2,27 +2,26 @@ # SPDX-License-Identifier: MIT +import contextlib import hashlib import importlib import inspect import math import pkgutil -from copy import deepcopy from pathlib import Path +from typing import NamedTuple import structlog -from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFile, UnidentifiedImageError +from PIL import Image, ImageFile from tagstudio.core.enums import Theme from tagstudio.core.library.alchemy.library import Library from tagstudio.core.library.ignore import Ignore -from tagstudio.core.media_types import MediaTypeGroup, MediaTypes, slugify +from tagstudio.core.media_types import MediaTypes from tagstudio.core.query_lang.file_groups import SEARCH from tagstudio.core.utils.decompression import decompressed, get_inner_ext, is_compressed from tagstudio.core.utils.types import unwrap from tagstudio.previews.base_preview import RENDER, BasePreview -from tagstudio.previews.effects import apply_overlay_color -from tagstudio.previews.gradients import four_corner_gradient from tagstudio.qt.app_settings import ( DEFAULT_CACHED_THUMB_RES, MAX_CACHED_THUMB_RES, @@ -30,8 +29,6 @@ AppSettings, ) from tagstudio.qt.cache_manager import CacheManager -from tagstudio.qt.resource_manager import ResourceManager -from tagstudio.qt.views.styles.palette import UI_COLORS, ColorType, UiColor ImageFile.LOAD_TRUNCATED_IMAGES = True Image.MAX_IMAGE_PIXELS = None @@ -58,447 +55,98 @@ def _get_preview_renderers() -> list[type[BasePreview]]: and obj.__module__ == module.__name__ ): obj.register_types() - found.append(obj) + if getattr(MediaTypes, obj.media_type_name, None) is None: + logger.error( + "[FileRenderer] Preview Renderer's media type isn't registered", + name=obj.__name__, + media_type=obj.media_type_name, + ) + else: + found.append(obj) break found.sort(key=lambda cls: cls.priority, reverse=True) + for renderer in found: + logger.info( + "[FileRenderer] Loaded Preview Renderer", + name=renderer.__name__, + media_type=renderer.media_type_name, + priority=renderer.priority, + ) return found +class RenderResult(NamedTuple): + """A rendered image from a file with any statuses associated with it.""" + + image: Image.Image | None + is_ignored: bool = False + is_unlinked: bool = False + + class FileRenderer: - """A class for rendering image previews and thumbnails from files.""" + """A class for rendering preview images and thumbnails from files.""" - _rm: ResourceManager = ResourceManager() _cached_img_ext: str = ".webp" _failed_render_filenames: set[Path] = set() # Used to skip loading icon for default icon files _preview_renderers: list[type[BasePreview]] = _get_preview_renderers() # Map of media group keys to preview renderer priorities. - _media_group_priorities: dict[str, int] = {} - for pr in _preview_renderers: - _media_group_priorities[pr.media_type_name] = pr.priority - - # Map of media group name keys to preferred icons declared in preview renderers. - _media_group_icons: dict[str, str] = {} - for pr in _preview_renderers: - _media_group_icons[pr.media_type_name] = pr.icon_name() - - for pr in _preview_renderers: - logger.info( - "[FileRenderer] Loaded Preview Renderer", - name=pr.__name__, - media_type=pr.media_type_name, - priority=pr.priority, - ) + _media_group_priorities: dict[str, int] = { + renderer.media_type_name: renderer.priority for renderer in _preview_renderers + } def __init__(self, library: Library, settings: AppSettings) -> None: - super().__init__() self.lib = library self.settings = settings - # Cached thumbnail elements. - # Key: Size + Pixel Ratio Tuple - # (Ex. (512, 512, 1.25)) - self.thumb_masks: dict[tuple[int, int, float], Image.Image] = {} - self.raised_edges: dict[tuple[int, int, float], tuple[Image.Image, Image.Image]] = {} - - # Key: ("name", UiColor, 512, 512, 1.25) - self.icons: dict[tuple[str, UiColor, int, int, float], Image.Image] = {} - - def _get_resource_id(self, path: Path) -> str: - """Return the name of the icon resource to use for a file type. - - Special terms will return special resources. - - Args: - path (Path): The file path to assess. "$LOADING" will return the loading graphic. - """ - ext = get_inner_ext(path) or MediaTypes.get_ext(path) + @classmethod + def media_groups(cls, filepath: Path) -> list[str]: + """Return the keys of the media groups a file belongs to, most specific first.""" + ext = get_inner_ext(filepath) or MediaTypes.get_ext(filepath) + renderer = cls.find_renderer(filepath) groups = MediaTypes.find(ext, SEARCH) # Fallback icons use the SEARCH context - groups.sort( # Sort by priority and most specific dot-separated subgroup. + groups.sort( # Most specific first, then the group that renders it, then by priority key=lambda g: ( g.key.count("."), - self._media_group_priorities.get(g.key, BasePreview.priority), + renderer is not None and g.key == renderer.media_type_name, + cls._media_group_priorities.get(g.key, BasePreview.priority), ), reverse=True, ) - for group in groups: - slug = slugify(self._media_group_icons.get(group.key, group.key)) - if self._rm.get(slug, silent_fail=True): - return slug - - return "file_generic" - - # NOTE: This method will be replaced with frontend specific decorations (Qt painting) - def _get_mask(self, size: tuple[int, int], pixel_ratio: float) -> Image.Image: - """Return a thumbnail mask given a size and pixel ratio. - - If one is not already cached, a new one will be rendered. - - Args: - size (tuple[int, int]): The size of the graphic. - pixel_ratio (float): The screen pixel ratio. - """ - item: Image.Image | None = self.thumb_masks.get((*size, pixel_ratio)) - if not item: - item = self._render_mask(size, pixel_ratio) - self.thumb_masks[(*size, pixel_ratio)] = item - return item - - # NOTE: This method will be replaced with frontend specific decorations (Qt painting) - def _get_edge( - self, size: tuple[int, int], pixel_ratio: float - ) -> tuple[Image.Image, Image.Image]: - """Return a thumbnail edge given a size, pixel ratio, and radius scaling option. - - If one is not already cached, a new one will be rendered. - - Args: - size (tuple[int, int]): The size of the graphic. - pixel_ratio (float): The screen pixel ratio. - """ - item: tuple[Image.Image, Image.Image] | None = self.raised_edges.get((*size, pixel_ratio)) - if not item: - item = self._render_edge(size, pixel_ratio) - self.raised_edges[(*size, pixel_ratio)] = item - return item - - def _get_icon( - self, - name: str, - color: UiColor, - size: tuple[int, int], - theme: Theme, - dpi_scale: float = 1.0, - bg_image: Image.Image | None = None, - draw_edge: bool = True, - is_corner: bool = False, - ) -> Image.Image: - """Return an icon given a size, pixel ratio, and radius scaling option. - - Args: - name (str): The name of the icon resource. "thumb_loading" will not draw a border. - color (str): The color to use for the icon. - size (tuple[int,int]): The size of the icon. - theme (Theme): A theme enum to determine the light/dark theme. - dpi_scale (float): The screen pixel ratio. - bg_image (Image.Image): Optional background image to go behind the icon. - draw_edge (bool): Flag for is the raised edge should be drawn. - is_corner (bool): Flag for is the icon should render with the "corner" style - """ - draw_border: bool = True - if name == "thumb_loading": - draw_border = False - - item: Image.Image | None = self.icons.get((name, color, *size, dpi_scale)) - if not item: - item_flat: Image.Image = ( - self._render_corner_icon(name, color, size, dpi_scale, theme, bg_image) - if is_corner - else self._render_center_icon( - name, color, size, dpi_scale, theme, draw_border, bg_image - ) - ) - if draw_edge: - edge: tuple[Image.Image, Image.Image] = self._get_edge(size, dpi_scale) - item = self._apply_edge(item_flat, edge, theme, faded=True) - self.icons[(name, color, *size, dpi_scale)] = item - else: - item = item_flat - return item - - # NOTE: This method will be replaced with frontend specific decorations (Qt painting) - def _render_mask(self, size: tuple[int, int], pixel_ratio: float) -> Image.Image: - """Render a thumbnail mask graphic. - - Args: - size (tuple[int,int]): The size of the graphic. - pixel_ratio (float): The screen pixel ratio. - """ - smooth_factor: int = 2 - radius_factor: int = 8 - - im: Image.Image = Image.new( - mode="L", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="black", - ) - draw = ImageDraw.Draw(im) - draw.rounded_rectangle( - (0, 0) + tuple([d - 1 for d in im.size]), - radius=math.ceil(radius_factor * smooth_factor * pixel_ratio), - fill="white", - ) - im = im.resize( - size, - resample=Image.Resampling.BILINEAR, - ) - return im - - # NOTE: This method will be replaced with frontend specific decorations (Qt painting) - def _render_edge( - self, size: tuple[int, int], pixel_ratio: float - ) -> tuple[Image.Image, Image.Image]: - """Render a thumbnail edge graphic. - - Args: - size (tuple[int,int]): The size of the graphic. - pixel_ratio (float): The screen pixel ratio. - """ - smooth_factor: int = 2 - radius_factor: int = 8 - width: int = math.floor(pixel_ratio * 2) - - # Highlight - im_hl: Image.Image = Image.new( - mode="RGBA", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#00000000", - ) - draw = ImageDraw.Draw(im_hl) - draw.rounded_rectangle( - (width, width) + tuple([d - (width + 1) for d in im_hl.size]), - radius=math.ceil((radius_factor * smooth_factor * pixel_ratio) - (pixel_ratio * 3)), - fill=None, - outline="white", - width=width, - ) - im_hl = im_hl.resize(size, resample=Image.Resampling.BILINEAR) - - # Shadow - im_sh: Image.Image = Image.new( - mode="RGBA", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#00000000", - ) - draw = ImageDraw.Draw(im_sh) - draw.rounded_rectangle( - (0, 0) + tuple([d - 1 for d in im_sh.size]), - radius=math.ceil(radius_factor * smooth_factor * pixel_ratio), - fill=None, - outline="black", - width=width, - ) - im_sh = im_sh.resize(size, resample=Image.Resampling.BILINEAR) - - return (im_hl, im_sh) - - def _render_center_icon( - self, - name: str, - color: UiColor, - size: tuple[int, int], - pixel_ratio: float, - theme: Theme, - draw_border: bool = True, - bg_image: Image.Image | None = None, - ) -> Image.Image: - """Render a thumbnail icon. - - Args: - name (str): The name of the icon resource. - color (UiColor): The color to use for the icon. - size (tuple[int,int]): The size of the icon. - pixel_ratio (float): The screen pixel ratio. - theme (Theme): A theme enum to determine the light/dark theme. - draw_border (bool): Option to draw a border. - bg_image (Image.Image): Optional background image to go behind the icon. - """ - border_factor: int = 5 - smooth_factor: int = math.ceil(2 * pixel_ratio) - radius_factor: int = 8 - icon_ratio: float = 1.75 - - # Create larger blank image based on smooth_factor - im: Image.Image = Image.new( - "RGBA", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#FF000000", - ) - - # Create solid background color - bg: Image.Image - bg = Image.new( - "RGB", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#000000FF", - ) - - # Use a background image if provided - if bg_image: - bg_im = Image.Image.resize(bg_image, size=tuple([d * smooth_factor for d in size])) # pyright: ignore[reportArgumentType] - bg_im = ImageEnhance.Brightness(bg_im).enhance(0.3) # Reduce the brightness - bg.paste(bg_im) - - # Paste background color with rounded rectangle mask onto blank image - im.paste( - bg, - (0, 0), - mask=self._get_mask( - tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - (pixel_ratio * smooth_factor), - ), - ) - - # Draw rounded rectangle border - if draw_border: - draw = ImageDraw.Draw(im) - draw.rounded_rectangle( - (0, 0) + tuple([d - 1 for d in im.size]), - radius=math.ceil( - (radius_factor * smooth_factor * pixel_ratio) + (pixel_ratio * 1.5) - ), - fill=None if bg_image else "black", - outline="#FF0000", - width=math.floor( - (border_factor * smooth_factor * pixel_ratio) - (pixel_ratio * 1.5) - ), - ) - - # Resize image to final size - im = im.resize(size, resample=Image.Resampling.BILINEAR) - fg: Image.Image = Image.new("RGB", size=size, color="#00FF00") - - # Get icon by name - icon = self._rm.get(name) - assert isinstance(icon, Image.Image) or icon is None - if not icon: - icon = self._rm.file_generic - - # Resize icon to fit icon_ratio - icon = icon.resize((math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio))) - - # Paste icon centered - im.paste( - im=fg.resize((math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio))), - box=( - math.ceil((size[0] - (size[0] // icon_ratio)) // 2), - math.ceil((size[1] - (size[1] // icon_ratio)) // 2), - ), - mask=icon.getchannel(3), - ) - - # Apply color overlay - im = apply_overlay_color(im, color, theme) + return [group.key for group in groups] - return im - - def _render_corner_icon( - self, - name: str, - color: UiColor, - size: tuple[int, int], - pixel_ratio: float, - theme: Theme, - bg_image: Image.Image | None = None, - ) -> Image.Image: - """Render a thumbnail icon with the icon in the upper-left corner. + @staticmethod + def find_renderer(filepath: Path) -> type[BasePreview] | None: + """Return the preview renderer for a file, or for the file inside it if it's compressed.""" + renderer = FileRenderer._find_renderer(filepath) + if renderer is None and is_compressed(filepath): + renderer = FileRenderer._find_renderer(Path(filepath.stem)) + return renderer - Args: - name (str): The name of the icon resource. - color (UiColor): The color to use for the icon. - size (tuple[int,int]): The size of the icon. - pixel_ratio (float): The screen pixel ratio. - theme (Theme): A theme enum to determine the light/dark theme. - draw_border (bool): Option to draw a border. - bg_image (Image.Image): Optional background image to go behind the icon. - """ - smooth_factor: int = math.ceil(2 * pixel_ratio) - icon_ratio: float = 5 - padding_factor = 18 - - # Create larger blank image based on smooth_factor - im: Image.Image = Image.new( - "RGBA", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#00000000", - ) + @staticmethod + def previously_failed(filepath: Path, date_modified: float | None = None) -> bool: + """Return whether rendering a file failed before.""" + file_name = FileRenderer._cached_thumb_name(filepath, date_modified) + return file_name in FileRenderer._failed_render_filenames - bg: Image.Image - # Use a background image if provided - if bg_image: - bg = Image.Image.resize(bg_image, size=tuple([d * smooth_factor for d in size])) # pyright: ignore[reportArgumentType] - # Create solid background color - else: - bg = Image.new( - "RGB", - size=tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - color="#000000", + @staticmethod + def cached_thumbnail( + cache: CacheManager | None, filepath: Path, date_modified: float | None = None + ) -> Image.Image | None: + """Return a file's cached thumbnail, if it has one.""" + if not cache: + return None + cached_path = cache.get_file_path(FileRenderer._cached_thumb_name(filepath, date_modified)) + if not (cached_path and cached_path.is_file()): + return None + try: + return Image.open(cached_path) + except Exception as e: + logger.error( + "[FileRenderer] Couldn't open cached thumbnail!", path=cached_path, error=e ) - # Apply color overlay - bg = apply_overlay_color(im, color, theme) - - # Paste background color with rounded rectangle mask onto blank image - im.paste( - bg, - (0, 0), - mask=self._get_mask( - tuple([d * smooth_factor for d in size]), # pyright: ignore[reportArgumentType] - (pixel_ratio * smooth_factor), - ), - ) - - colors = UI_COLORS.get(color) or UI_COLORS[UiColor.DEFAULT] - primary_color = colors.get(ColorType.PRIMARY) - - # Resize image to final size - im = im.resize(size, resample=Image.Resampling.BILINEAR) - fg: Image.Image = Image.new("RGB", size=size, color=primary_color) - - # Get icon by name - icon = self._rm.get(name) - assert isinstance(icon, Image.Image) - if not icon: - icon = self._rm.file_generic - - # Resize icon to fit icon_ratio - icon = icon.resize((math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio))) - - # Paste icon - im.paste( - im=fg.resize((math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio))), - box=(size[0] // padding_factor, size[1] // padding_factor), - mask=icon.getchannel(3), - ) - - return im - - # NOTE: This method will be replaced with frontend specific decorations (Qt painting) - def _apply_edge( - self, - image: Image.Image, - edge: tuple[Image.Image, Image.Image], - theme: Theme, - faded: bool = False, - ) -> Image.Image: - """Apply a given edge effect to an image. - - Args: - image (Image.Image): The image to apply the edge to. - edge (tuple[Image.Image, Image.Image]): The edge images to apply. - Item 0 is the inner highlight, and item 1 is the outer shadow. - theme (Theme): A theme enum to determine the light/dark theme. - faded (bool): Whether to apply a faded version of the edge. - Used for light themes. - """ - opacity: float = 1.0 if not faded else 0.8 - shade_reduction: float = 0 if theme == Theme.DARK else 0.3 - im: Image.Image = image - im_hl, im_sh = deepcopy(edge) - - # Configure and apply a soft light overlay. - # This makes up the bulk of the effect. - im_hl.putalpha(ImageEnhance.Brightness(im_hl.getchannel(3)).enhance(opacity)) - im.paste(ImageChops.soft_light(im, im_hl), mask=im_hl.getchannel(3)) - - # Configure and apply a normal shading overlay. - # This helps with contrast. - im_sh.putalpha( - ImageEnhance.Brightness(im_sh.getchannel(3)).enhance(max(0, opacity - shade_reduction)) - ) - im.paste(im_sh, mask=im_sh.getchannel(3)) - - return im + return None @staticmethod def _cached_thumb_name(filepath: Path, date_modified: float | None = None) -> Path: @@ -516,252 +164,101 @@ def _cached_thumb_name(filepath: Path, date_modified: float | None = None) -> Pa def render( self, cache: CacheManager | None, - timestamp: float, filepath: Path | str, size: tuple[int, int], dpi_scale: float, theme: Theme = Theme.DARK, - is_loading: bool = False, is_thumb: bool = False, date_modified: float | None = None, - ): - """Render a thumbnail or preview image. + ) -> RenderResult: + """Render a thumbnail or preview image of a file. Args: cache (CacheManager | None): A cache manager instance. - timestamp (float): The timestamp for which this job was dispatched. filepath (str | Path): The path of the file to render a thumbnail for. size (tuple[int, int]): The unmodified base size of the thumbnail. dpi_scale (float): The screen pixel ratio. theme (Theme): A theme enum to determine the light/dark theme. - is_loading (bool): Is this a loading graphic? is_thumb (bool): Is this specifically a thumbnail? Use for specifying small variants. date_modified (float | None): The date modified timestamp of the file. Used for caches. - update_on_ratio_change (bool): Should an updated ratio signal be sent? """ - render_mask_and_edge: bool = True - scaled_size = math.ceil(max(size[0], size[1]) * dpi_scale) - theme_color: UiColor = UiColor.THEME_LIGHT if theme == Theme.LIGHT else UiColor.THEME_DARK if isinstance(filepath, str): filepath = Path(filepath) - def render_default(size: tuple[int, int], dpi_scale: float) -> Image.Image: - im = self._get_icon( - name=self._get_resource_id(filepath), - color=theme_color, - size=size, - theme=theme, - dpi_scale=dpi_scale, - ) - return im - - def render_unlinked( - size: tuple[int, int], dpi_scale: float, cached_im: Image.Image | None = None - ) -> Image.Image: - im = self._get_icon( - name="broken_link_icon", - color=UiColor.RED, - size=size, - theme=theme, - dpi_scale=dpi_scale, - bg_image=cached_im, - draw_edge=not cached_im, - is_corner=False, + is_unlinked = not filepath.exists() + is_ignored = False + with contextlib.suppress(TypeError): + is_ignored = Ignore.matcher.is_ignored( + filepath.relative_to(unwrap(self.lib.library_dir)) ) - return im - - def render_icon_overlay( - size: tuple[int, int], im: Image.Image, icon: Image.Image - ) -> Image.Image: - icon_ratio: float = 5 - padding_factor = 18 - - im_ = im - icon = icon.resize((math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio))) - im_.paste( - im=icon.resize( - (math.ceil(size[0] // icon_ratio), math.ceil(size[1] // icon_ratio)) - ), - box=(size[0] // padding_factor, size[1] // padding_factor), - mask=icon.getchannel(3), - ) - - return im_ - - def fetch_cached_image(file_name: Path): - image: Image.Image | None = None - if not cache: - return image - cached_path = cache.get_file_path(file_name) - - if cached_path and cached_path.is_file(): - try: - image = Image.open(cached_path) - if not image: - raise UnidentifiedImageError # pyright: ignore[reportUnreachable] - except Exception as e: - logger.error( - "[FileRenderer] Couldn't open cached thumbnail!", path=cached_path, error=e - ) - return image - def render_fallback_preview() -> Image.Image: - """Render a fallback preview image. - - Will be an existing cached thumbnail if one exists, or the default preview icon, or else - the unlinked icon if the file is unlinked and there's no cached thumbnail. - """ - if not filepath.exists(): - cached_name = FileRenderer._cached_thumb_name(filepath, date_modified) - return fetch_cached_image(cached_name) or render_unlinked((512, 512), 2) - if filepath.is_dir(): - return render_unlinked((512, 512), 2) - return render_default((512, 512), 2) - - image: Image.Image | None = None - # Try to get a non-loading thumbnail for the grid. - if not is_loading and is_thumb and filepath and filepath != Path("."): - # Attempt to retrieve cached image from disk - is_unlinked = not filepath.exists() - file_name = FileRenderer._cached_thumb_name(filepath, date_modified) - image = fetch_cached_image(file_name) - - if not image and self.settings.generate_thumbs: - settings_res = self.settings.cached_thumb_resolution - thumb_res = ( - settings_res - if settings_res >= MIN_CACHED_THUMB_RES and settings_res <= MAX_CACHED_THUMB_RES - else DEFAULT_CACHED_THUMB_RES - ) - - # Render from file, return result, and try to save a cached version. - # TODO: Audio waveforms are dynamically sized based on the base_size, so hardcoding - # the resolution breaks that. - image = self._render( - cache=cache, - filepath=filepath, - size=(thumb_res, thumb_res), - dpi_scale=1, - theme=theme, - is_small=is_thumb, - cache_filename=file_name, - ) - if not image: - FileRenderer._failed_render_filenames.add(file_name) - - # If the normal renderer failed, fallback the defaults - # (with native non-cached sizing!) - if not image: - image = ( - render_unlinked((scaled_size, scaled_size), dpi_scale) - if is_unlinked or filepath.is_dir() - else render_default((scaled_size, scaled_size), dpi_scale) - ) - render_mask_and_edge = False - - # Apply the mask and edge + if is_thumb: + image = self._get_thumbnail(cache, filepath, size, dpi_scale, theme, date_modified) + else: + image = self._render(filepath, size, dpi_scale, theme, date_modified) if image: - image = self._resize_image(image, (scaled_size, scaled_size)) - if render_mask_and_edge: - mask = self._get_mask((scaled_size, scaled_size), dpi_scale) - edge: tuple[Image.Image, Image.Image] = self._get_edge( - (scaled_size, scaled_size), dpi_scale - ) - image = self._apply_edge( - four_corner_gradient(image, (scaled_size, scaled_size), mask), edge, theme - ) + image = image.convert("RGBA") + return RenderResult(image, is_ignored, is_unlinked) - # Check if the file is supposed to be ignored and render an overlay if needed - try: - if image and Ignore.matcher.is_ignored( - filepath.relative_to(unwrap(self.lib.library_dir)) - ): - image = render_icon_overlay((scaled_size, scaled_size), image, self._rm.ignored) - except TypeError: - pass - - # Cached thumbnails of unlinked files get an unlinked icon overlay - if image and render_mask_and_edge and is_unlinked: - image = render_icon_overlay( - (scaled_size, scaled_size), image, self._rm.unlinked_stat - ) - - # A loading graphic, or a placeholder for a preview - elif is_loading: - if not is_thumb: - renderer = FileRenderer._find_renderer(filepath) - if renderer is None and is_compressed(filepath): - renderer = FileRenderer._find_renderer(Path(filepath.stem)) - file_name = FileRenderer._cached_thumb_name(filepath, date_modified) - if ( - not renderer - or not filepath.is_file() - or file_name in FileRenderer._failed_render_filenames - ): - image = render_fallback_preview() - elif renderer.has_small_variant: - # The thumb uses a different variant, so stay blank until the preview renders - image = Image.new("RGBA", (scaled_size, scaled_size)) - else: - image = fetch_cached_image(file_name) - if not image: - # Initialize "Loading" thumbnail - loading_thumb: Image.Image = self._get_icon( - "thumb_loading", theme_color, (scaled_size, scaled_size), theme, dpi_scale - ) - image = loading_thumb.resize( - (scaled_size, scaled_size), resample=Image.Resampling.BILINEAR - ) - - # A full preview image (never cached) - elif not is_thumb: - image = self._render(cache, filepath, size, dpi_scale, theme) - file_name = FileRenderer._cached_thumb_name(filepath, date_modified) - if image: - FileRenderer._failed_render_filenames.discard(file_name) - else: - FileRenderer._failed_render_filenames.add(file_name) - image = render_fallback_preview() - image = image.convert("RGBA") + def _get_thumbnail( + self, + cache: CacheManager | None, + filepath: Path, + size: tuple[int, int], + dpi_scale: float, + theme: Theme, + date_modified: float | None, + ) -> Image.Image | None: + """Return a file's thumbnail from the cache, rendering and caching it first if needed. - # If the image couldn't be rendered, use a default media image. + Args: + cache (CacheManager | None): A cache manager instance. + filepath (Path): The path of the file to render a thumbnail for. + size (tuple[int, int]): The unmodified base size of the thumbnail. + dpi_scale (float): The screen pixel ratio. + theme (Theme): A theme enum to determine the light/dark theme. + date_modified (float | None): The date modified timestamp of the file. Used for caches. + """ + image = FileRenderer.cached_thumbnail(cache, filepath, date_modified) + if not image and self.settings.generate_thumbs: + res = self.settings.cached_thumb_resolution + if not MIN_CACHED_THUMB_RES <= res <= MAX_CACHED_THUMB_RES: + res = DEFAULT_CACHED_THUMB_RES + + image = self._render( + filepath, (res, res), 1, theme, date_modified, is_small=True, cache=cache + ) if not image: - image = Image.new("RGBA", (128, 128), color="#FF00FF") - - return ( - image, - (math.ceil(scaled_size / dpi_scale), math.ceil(image.size[1] / dpi_scale)), - timestamp, - ) + return None + scaled_size = math.ceil(max(size) * dpi_scale) + return self._resize_image(image, (scaled_size, scaled_size)) def _render( self, - cache: CacheManager | None, - filepath: str | Path, + filepath: Path, size: tuple[int, int], dpi_scale: float, - theme: Theme = Theme.DARK, + theme: Theme, + date_modified: float | None, is_small: bool = False, - cache_filename: Path | None = None, + cache: CacheManager | None = None, ) -> Image.Image | None: - """Render a thumbnail or preview image. + """Render a file preview image. Args: - cache (CacheManager | None): A cache manager instance. - filepath (str | Path): The path of the file to render a thumbnail for. - size (tuple[int, int]): The unmodified base size of the thumbnail. + filepath (Path): The path of the file to render. + size (tuple[int, int]): The unmodified base size of the image. dpi_scale (float): The screen pixel ratio. theme (Theme): A theme enum to determine the light/dark theme. + date_modified (float | None): The date modified timestamp of the file. Used for caches. is_small (bool): Is this specifically a thumbnail? Use for specifying small variants. - cache_filename (Path | None): An optional filename to use to save to the cache. - + cache (CacheManager | None): A cache manager to save the rendered image to, if any. """ - filepath = Path(filepath) if isinstance(filepath, str) else filepath - scaled_size = math.ceil(max(size[0], size[1]) * dpi_scale) + file_name = FileRenderer._cached_thumb_name(filepath, date_modified) + scaled_size = math.ceil(max(size) * dpi_scale) image: Image.Image | None = None - is_savable_type: bool = True - if filepath and filepath.is_file(): + if filepath.is_file(): try: renderer = FileRenderer._find_renderer(filepath) if renderer: @@ -779,12 +276,16 @@ def _render( if image: image = self._resize_image(image, (scaled_size, scaled_size)) - if cache_filename and is_savable_type and image and cache: - cache.save_image(image, cache_filename, mode="RGBA") + if image and cache: + cache.save_image(image, file_name, mode="RGBA") except Exception as e: logger.error("[FileRenderer] Couldn't render thumbnail", filepath=filepath, error=e) image = None + if image: + FileRenderer._failed_render_filenames.discard(file_name) + else: + FileRenderer._failed_render_filenames.add(file_name) return image @staticmethod @@ -792,17 +293,8 @@ def _find_renderer(filepath: Path) -> type[BasePreview] | None: """Return the highest priority preview renderer for a file's extension, if any.""" ext = MediaTypes.get_ext(filepath) if filepath.suffix else filepath.stem.lower() for renderer in FileRenderer._preview_renderers: - media_type: MediaTypeGroup | None = getattr(MediaTypes, renderer.media_type_name, None) - if media_type is None: - logger.error( - f"[FileRenderer] " - f"Attribute '{renderer.media_type_name}' not registered with MediaTypes", - ) - return None - - if media_type.contains(ext, RENDER): + if getattr(MediaTypes, renderer.media_type_name).contains(ext, RENDER): return renderer - return None @staticmethod @@ -825,7 +317,8 @@ def _render_decompressed( image.load() # Read the image data before the temporary file is deleted return image - def _resize_image(self, image: Image.Image, size: tuple[int, int]) -> Image.Image: + @staticmethod + def _resize_image(image: Image.Image, size: tuple[int, int]) -> Image.Image: orig_x, orig_y = image.size new_x, new_y = size diff --git a/src/tagstudio/previews/gradients.py b/src/tagstudio/previews/gradients.py deleted file mode 100644 index 004a385298..0000000000 --- a/src/tagstudio/previews/gradients.py +++ /dev/null @@ -1,62 +0,0 @@ -# SPDX-FileCopyrightText: (c) TagStudio Contributors -# SPDX-License-Identifier: GPL-3.0-only - - -from PIL import Image - -from tagstudio.core.utils.types import unwrap - - -def four_corner_gradient( - image: Image.Image, size: tuple[int, int], mask: Image.Image | None = None -) -> Image.Image: - if image.size != size: - # Four-Corner Gradient Background. - tl = unwrap(image.getpixel((0, 0))) - tr = unwrap(image.getpixel(((image.size[0] - 1), 0))) - bl = unwrap(image.getpixel((0, (image.size[1] - 1)))) - br = unwrap(image.getpixel(((image.size[0] - 1), (image.size[1] - 1)))) - bg = Image.new(mode="RGB", size=(2, 2)) - bg.paste(tl, (0, 0, 2, 2)) - bg.paste(tr, (1, 0, 2, 2)) - bg.paste(bl, (0, 1, 2, 2)) - bg.paste(br, (1, 1, 2, 2)) - bg = bg.resize(size, resample=Image.Resampling.BICUBIC) - bg.paste( - image, - box=( - (size[0] - image.size[0]) // 2, - (size[1] - image.size[1]) // 2, - ), - ) - - final = Image.new("RGBA", bg.size, (0, 0, 0, 0)) - if mask: - final.paste(bg, mask=mask.getchannel(0)) - else: - final = bg - - else: - final = Image.new("RGBA", size, (0, 0, 0, 0)) - if mask: - final.paste(image, mask=mask.getchannel(0)) - else: - final = image - - if final.mode != "RGBA": - final = final.convert("RGBA") - - return final - - -def linear_gradient( - size: tuple[int, int], - colors: list[str], - interpolation: Image.Resampling = Image.Resampling.BICUBIC, -) -> Image.Image: - seed: Image.Image = Image.new(mode="RGBA", size=(len(colors), 1), color="#000000") - for i, color in enumerate(colors): - c_im: Image.Image = Image.new(mode="RGBA", size=(1, 1), color=color) - seed.paste(c_im, (i, 0)) - gradient: Image.Image = seed.resize(size, resample=interpolation) - return gradient diff --git a/src/tagstudio/previews/renderers/font.py b/src/tagstudio/previews/renderers/font.py index 00ef761a75..f79c49491a 100644 --- a/src/tagstudio/previews/renderers/font.py +++ b/src/tagstudio/previews/renderers/font.py @@ -17,8 +17,7 @@ from tagstudio.core.media_types import MediaTypes from tagstudio.previews.base_preview import RENDER, BasePreview from tagstudio.previews.effects import apply_overlay_color -from tagstudio.qt.helpers.text_wrapper import wrap_full_text -from tagstudio.qt.views.styles.color_overlay import auto_theme_overlay +from tagstudio.previews.text_wrapper import wrap_full_text from tagstudio.qt.views.styles.palette import UiColor logger = structlog.get_logger(__name__) @@ -48,7 +47,7 @@ def render( return ( font_small_thumb(filepath, theme, size) if is_small - else font_full_preview(filepath, size) + else font_full_preview(filepath, theme, size) ) @@ -110,6 +109,7 @@ def font_small_thumb(filepath: Path, theme: Theme, size: tuple[int, int]) -> Ima box=(margin, margin + ((size[1] - new_y) // 2)), ) im = bg + # TODO: Replace UiColor system, remove Qt-side import here. im = apply_overlay_color(im, UiColor.BLUE, theme) except OSError as e: @@ -118,11 +118,12 @@ def font_small_thumb(filepath: Path, theme: Theme, size: tuple[int, int]) -> Ima return im -def font_full_preview(filepath: Path, size: tuple[int, int]) -> Image | None: +def font_full_preview(filepath: Path, theme: Theme, size: tuple[int, int]) -> Image | None: """Render a large font preview ("Alphabet") thumbnail from a font file. Args: filepath (Path): The path of the file. + theme (Theme): The system color theme. size (tuple[int,int]): The size of the thumbnail. """ # Scale the sample font sizes to the preview image @@ -145,8 +146,8 @@ def font_full_preview(filepath: Path, size: tuple[int, int]) -> Image | None: y_offset += (len(text_wrapped.split("\n")) + lines_of_padding) * draw.textbbox( (0, 0), "A", font=font )[-1] - # TODO: Separate from any Qt stuff - im = auto_theme_overlay(bg, use_alpha=False) + im = new_image("RGBA", size, color="#00000000") + im.paste("#FFFFFF" if theme == Theme.DARK else "#000000", mask=bg) except OSError as e: logger.error("Couldn't render thumbnail", filepath=filepath, error=type(e).__name__) return im diff --git a/src/tagstudio/previews/renderers/powerpoint.py b/src/tagstudio/previews/renderers/powerpoint.py index 5c87743680..f6b04d254c 100644 --- a/src/tagstudio/previews/renderers/powerpoint.py +++ b/src/tagstudio/previews/renderers/powerpoint.py @@ -17,7 +17,6 @@ class PowerPointPreview(BasePreview): - _fallback_icon = "presentation" media_type_name = "microsoft.office.powerpoint" @override diff --git a/src/tagstudio/previews/renderers/stl.py b/src/tagstudio/previews/renderers/stl.py index 23c74a2bae..1c28d51f8c 100644 --- a/src/tagstudio/previews/renderers/stl.py +++ b/src/tagstudio/previews/renderers/stl.py @@ -52,7 +52,6 @@ class STLRenderError(ValueError): class STLPreview(BasePreview): media_type_name = "model.stl" - _fallback_icon = "model" @override @classmethod diff --git a/src/tagstudio/qt/helpers/text_wrapper.py b/src/tagstudio/previews/text_wrapper.py similarity index 100% rename from src/tagstudio/qt/helpers/text_wrapper.py rename to src/tagstudio/previews/text_wrapper.py diff --git a/src/tagstudio/qt/controllers/item_thumb.py b/src/tagstudio/qt/controllers/item_thumb.py index 363db35a0a..8b77e3a768 100644 --- a/src/tagstudio/qt/controllers/item_thumb.py +++ b/src/tagstudio/qt/controllers/item_thumb.py @@ -8,6 +8,7 @@ import structlog from PySide6.QtCore import QEvent, QMimeData, QPoint, QRect, QRectF, QSignalBlocker, Qt, QUrl from PySide6.QtGui import ( + QBrush, QColor, QContextMenuEvent, QDrag, @@ -19,6 +20,7 @@ QPaintEvent, QPen, QPixmap, + QTransform, ) from PySide6.QtWidgets import QApplication, QMenu, QWidget @@ -33,6 +35,7 @@ from tagstudio.qt.views.item_thumb_view import ItemThumbView from tagstudio.qt.views.styles.palette import Palette from tagstudio.qt.views.styles.stylesheets import ( + OUTLINE_WIDTH, RADIUS, item_thumb_faded_select_color, item_thumb_filename_style, @@ -220,8 +223,8 @@ def set_filename_visibility(self, set_visible: bool): file_label.setHidden(False) self.setFixedHeight( self._thumb_size[1] - + ItemThumbView.FILE_LABEL_HEIGHT + ItemThumbView.FILE_LABEL_SPACING + + file_label.sizeHint().height() ) else: file_label.setHidden(True) @@ -245,11 +248,6 @@ def set_image(self, image: QPixmap, file_path: Path) -> None: self.rendered_path = file_path self.update() - def clear_image(self) -> None: - self._image = None - self.rendered_path = None - self.update() - def set_item(self, entry: Entry): self.set_item_id(entry.id) self._item_path = unwrap(self._lib.library_dir) / entry.path @@ -305,36 +303,68 @@ def paintEvent(self, event: QPaintEvent) -> None: painter = QPainter(self) rect = self._image_rect() if self._image is not None: - painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) - painter.drawPixmap(rect, self._image) + self._paint_decorated_image(painter, QRectF(rect)) if self._image_hovered or self._selected: painter.setRenderHint(QPainter.RenderHint.Antialiasing) - width = 3 - path = QPainterPath() - path.addRoundedRect( - QRectF(width / 2, width / 2, rect.width() - width, rect.height() - width), - RADIUS, - RADIUS, + inset = OUTLINE_WIDTH / 2 + outline = QPainterPath() + outline.addRoundedRect( + QRectF(rect).adjusted(inset, inset, -inset, -inset), + RADIUS - inset, + RADIUS - inset, ) + color: QColor = self._hover_color if self._selected: painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_HardLight) - painter.setPen(QPen(self._select_color_faded, width)) - painter.fillPath(path, self._select_color_faded) - painter.drawPath(path) - - painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) - color: QColor = self._hover_color if self._image_hovered else self._select_color - painter.setPen(QPen(color, width)) - painter.drawPath(path) - else: - painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) - painter.setPen(QPen(self._hover_color, width)) - painter.drawPath(path) + painter.setPen(QPen(self._select_color_faded, OUTLINE_WIDTH)) + painter.setBrush(self._select_color_faded) + painter.drawPath(outline) + if not self._image_hovered: + color = self._select_color + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) + painter.setPen(QPen(color, OUTLINE_WIDTH)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawPath(outline) painter.end() + def _paint_decorated_image(self, painter: QPainter, rect: QRectF) -> None: + """Paint the image with rounded corners and a raised edge decoration.""" + image = unwrap(self._image) + image_size = image.deviceIndependentSize() + brush = QBrush(image) + brush.setTransform( + QTransform.fromScale( + rect.width() / image_size.width(), rect.height() / image_size.height() + ) + ) + painter.save() + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(brush) + painter.drawRoundedRect(rect.adjusted(1, 1, -1, -1), RADIUS - 1, RADIUS - 1) + + highlight = QPainterPath() + highlight.addRoundedRect(rect.adjusted(1, 1, -1, -1), RADIUS - 1, RADIUS - 1) + highlight.addRoundedRect(rect.adjusted(2, 2, -2, -2), RADIUS - 2, RADIUS - 2) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Screen) + painter.setOpacity(0.875) + painter.fillPath(highlight, brush) + painter.setOpacity(1) + + shadow = QPainterPath() + shadow.addRoundedRect(rect, RADIUS, RADIUS) + shadow.addRoundedRect(rect.adjusted(1, 1, -1, -1), RADIUS - 1, RADIUS - 1) + is_dark = QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver) + painter.fillPath(shadow, QColor(0, 0, 0, 255 if is_dark else 115)) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Multiply) + painter.fillPath(shadow, brush) + painter.restore() + @override def enterEvent(self, event: QEnterEvent) -> None: self._set_image_hovered(self._image_rect().contains(event.position().toPoint())) diff --git a/src/tagstudio/qt/controllers/main_window.py b/src/tagstudio/qt/controllers/main_window.py index acee695663..b7c886beb2 100644 --- a/src/tagstudio/qt/controllers/main_window.py +++ b/src/tagstudio/qt/controllers/main_window.py @@ -9,10 +9,9 @@ from typing import override import structlog -from PIL import Image, ImageQt from PySide6 import QtCore, QtGui from PySide6.QtCore import QMetaObject, QSize, QStringListModel, Qt -from PySide6.QtGui import QAction, QPixmap +from PySide6.QtGui import QAction from PySide6.QtWidgets import ( QCheckBox, QComboBox, @@ -554,18 +553,14 @@ def setup_search_bar(self): self.search_bar_layout.setContentsMargins(WIN_PAD, 0, 0, 0) self.back_button = QPushButton(self.central_widget) - back_icon: Image.Image = self.rm.bxs_left_arrow - back_icon = auto_theme_overlay(back_icon, use_alpha=False) - self.back_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(back_icon))) + self.back_button.setIcon(auto_theme_overlay(self.rm.bxs_left_arrow, use_alpha=False)) self.back_button.setObjectName("back_button") self.back_button.setMinimumSize(QSize(32, 32)) self.back_button.setMaximumSize(QSize(32, 16777215)) self.search_bar_layout.addWidget(self.back_button) self.forward_button = QPushButton(self.central_widget) - forward_icon: Image.Image = self.rm.bxs_right_arrow - forward_icon = auto_theme_overlay(forward_icon, use_alpha=False) - self.forward_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(forward_icon))) + self.forward_button.setIcon(auto_theme_overlay(self.rm.bxs_right_arrow, use_alpha=False)) self.forward_button.setIconSize(QSize(16, 16)) self.forward_button.setObjectName("forward_button") self.forward_button.setMinimumSize(QSize(32, 32)) diff --git a/src/tagstudio/qt/controllers/preview_thumb.py b/src/tagstudio/qt/controllers/preview_thumb.py index c159910765..2b75cb3eb4 100644 --- a/src/tagstudio/qt/controllers/preview_thumb.py +++ b/src/tagstudio/qt/controllers/preview_thumb.py @@ -15,7 +15,7 @@ from PIL import Image, UnidentifiedImageError from PIL.Image import DecompressionBombError from PySide6.QtCore import QBuffer, QByteArray, QRectF, QSize, Qt, QThreadPool, Signal -from PySide6.QtGui import QBrush, QMovie, QPainter, QPixmap, QResizeEvent +from PySide6.QtGui import QBrush, QColor, QMovie, QPainter, QPixmap, QResizeEvent from PySide6.QtMultimedia import QMediaPlayer from PySide6.QtWidgets import QWidget from rawpy import LibRawFileUnsupportedError, LibRawIOError # pyright: ignore @@ -32,7 +32,7 @@ ) from tagstudio.qt.mixed.file_attributes import FileAttributeData from tagstudio.qt.mixed.media_player import MediaPlayer -from tagstudio.qt.qt_file_renderer import QtFileRenderer +from tagstudio.qt.qt_file_renderer import QtFileRenderer, paint_fallback_icon_border from tagstudio.qt.utils.file_opener import open_file from tagstudio.qt.views.preview_thumb_view import PreviewThumbView from tagstudio.qt.views.styles.stylesheets import RADIUS @@ -82,6 +82,7 @@ def __init__(self, driver: QtDriver): self._rendered_res: tuple[int, int] = (0, 0) self._should_render_on_resize: bool = False self._source_pixmap: QPixmap = QPixmap() + self._border_color: QColor | None = None self.setMinimumSize(*self._preview_size) self.setLayout(PreviewThumbView(driver)) @@ -175,12 +176,13 @@ def _animation_loaded_callback( self._display_image(filepath, is_new_file=False) def _file_renderer_updated_callback( - self, timestamp: float, img: QPixmap, _size: QSize, path: Path + self, timestamp: float, img: QPixmap, path: Path, border_color: QColor | None ) -> None: if path != self._current_file or timestamp < self._render_timestamp: return self._source_pixmap = img + self._border_color = border_color self._image_ratio = img.width() / img.height() self._update_image_size((self.size().width(), self.size().height()), refresh_icon=True) @@ -204,6 +206,8 @@ def _update_icon(self) -> None: painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(QBrush(scaled)) painter.drawRoundedRect(QRectF(pixmap.rect()), RADIUS * ratio, RADIUS * ratio) + if self._border_color is not None: + paint_fallback_icon_border(painter, QRectF(pixmap.rect()), self._border_color, ratio) painter.end() pixmap.setDevicePixelRatio(ratio) button.setIcon(pixmap) @@ -318,7 +322,7 @@ def _render_placeholder(self, filepath: Path) -> None: filepath, _DEFAULT_PREVIEW_SIZE, self.devicePixelRatio(), - is_loading=True, + is_placeholder=True, date_modified=self._date_modified, ) diff --git a/src/tagstudio/qt/controllers/suggest_box.py b/src/tagstudio/qt/controllers/suggest_box.py index b7e9f089dc..76370d931f 100644 --- a/src/tagstudio/qt/controllers/suggest_box.py +++ b/src/tagstudio/qt/controllers/suggest_box.py @@ -5,7 +5,7 @@ from typing import Any, override import structlog -from PIL import Image, ImageQt +from PIL import Image from PySide6.QtCore import Signal from PySide6.QtGui import QAction, QPixmap, QShowEvent, Qt from PySide6.QtWidgets import QGraphicsOpacityEffect, QWidget @@ -133,8 +133,7 @@ def _connect_callbacks(self) -> None: def set_hint_icon(self, icon: Image.Image | None) -> None: if icon: - pixmap = QPixmap.fromImage(ImageQt.ImageQt(auto_theme_overlay(icon))) - self.layout().hint_icon_action.setIcon(pixmap) + self.layout().hint_icon_action.setIcon(auto_theme_overlay(icon)) else: self.layout().hint_icon_action.setIcon(QPixmap()) diff --git a/src/tagstudio/qt/controllers/thumb_grid.py b/src/tagstudio/qt/controllers/thumb_grid.py index 4589c7c04d..5ae22a335f 100644 --- a/src/tagstudio/qt/controllers/thumb_grid.py +++ b/src/tagstudio/qt/controllers/thumb_grid.py @@ -7,8 +7,8 @@ from typing import TYPE_CHECKING, override import structlog -from PySide6.QtCore import QSize, QThreadPool, QTimer, Signal -from PySide6.QtGui import QPixmap +from PySide6.QtCore import QThreadPool, QTimer, Signal +from PySide6.QtGui import QColor, QPixmap from PySide6.QtWidgets import QScrollArea, QWidget from tagstudio.core.library.alchemy.enums import ItemType @@ -183,10 +183,7 @@ def _assign_entry(self, thumb: ItemThumb, entry: Entry) -> None: self._show_loading_image(thumb) def _show_loading_image(self, thumb: ItemThumb) -> None: - if self._loading_image is None: - thumb.clear_image() - else: - thumb.set_image(self._loading_image, Path()) + thumb.set_image(unwrap(self._loading_image), Path()) def _assign_badges(self, thumb: ItemThumb, entry_id: int) -> None: for tag_id in self._driver.entry_state.badge_tag_ids: @@ -240,27 +237,14 @@ def _on_entries_fetched( def _reset_renders(self) -> None: self._render_cutoff = time.time() self._renders.clear() - self._loading_image = None + size = self._driver.main_window.thumb_size + self._loading_image = self._renderer.loading_image((size, size), self.devicePixelRatio()) self._driver.thumb_job_queue.queue.clear() self._pending_durations.clear() - self._request_loading_image() - - def _request_loading_image(self) -> None: - size = self._driver.main_window.thumb_size - self._driver.thumb_job_queue.put( - ( - self._renderer.render, - ( - self._driver.cache_manager, - self._render_cutoff, - Path(), - (size, size), - self._driver.main_window.devicePixelRatio(), - True, - True, - ), - ) - ) + for _, thumb in self.layout().assigned_items(): + entry = self._entries.get(thumb.item_id) + if entry is None or thumb.rendered_path != self._path(entry): + thumb.set_image(self._loading_image, Path()) def _request_renders(self) -> None: """Queue renders for thumbnails, starting at the first visible one.""" @@ -307,21 +291,13 @@ def _trim_render_queue(self) -> None: queue.clear() self._pending_durations.clear() self._renders = {path: image for path, image in self._renders.items() if image is not None} - if self._loading_image is None: - self._request_loading_image() - def _on_rendered(self, timestamp: float, image: QPixmap, _size: QSize, file_path: Path) -> None: + def _on_rendered( + self, timestamp: float, image: QPixmap, file_path: Path, _border_color: QColor | None + ) -> None: if timestamp < self._render_cutoff: return - if file_path == Path(): - self._loading_image = image - for _, thumb in self.layout().assigned_items(): - entry = self._entries.get(thumb.item_id) - if entry is None or thumb.rendered_path != self._path(entry): - thumb.set_image(image, Path()) - return - self._renders[file_path] = image self._previous_size_renders.pop(file_path, None) if (thumb := self._thumb_for(self._entry_paths.get(file_path))) is not None: diff --git a/src/tagstudio/qt/mixed/landing.py b/src/tagstudio/qt/mixed/landing.py index eb68c357b0..14db9a3deb 100644 --- a/src/tagstudio/qt/mixed/landing.py +++ b/src/tagstudio/qt/mixed/landing.py @@ -105,17 +105,10 @@ def update_logo_color(self, style: typing.Literal["mono", "color"] = "mono"): style (str): = The style of the logo. Either "mono" or "color". """ if style == "mono": - logo_im = auto_theme_overlay(LandingWidget.mono_logo) + self.landing_pixmap = auto_theme_overlay(LandingWidget.mono_logo) elif style == "color": - logo_im = LandingWidget.color_logo + self.landing_pixmap = QPixmap.fromImage(ImageQt.ImageQt(LandingWidget.color_logo)) - logo_final: Image.Image = Image.new( - mode="RGBA", size=LandingWidget.mono_logo.size, color="#00000000" - ) - - logo_final.paste(logo_im, (0, 0), mask=LandingWidget.mono_logo) - - self.landing_pixmap = QPixmap.fromImage(ImageQt.ImageQt(logo_im)) self.landing_pixmap.setDevicePixelRatio(self._pixel_ratio) self.landing_pixmap = self.landing_pixmap.scaledToWidth( self._logo_width, Qt.TransformationMode.SmoothTransformation diff --git a/src/tagstudio/qt/mixed/media_player.py b/src/tagstudio/qt/mixed/media_player.py index 522b743fbc..309d9309cc 100644 --- a/src/tagstudio/qt/mixed/media_player.py +++ b/src/tagstudio/qt/mixed/media_player.py @@ -8,7 +8,6 @@ from typing import override import structlog -from PIL import ImageQt from PySide6.QtCore import QEvent, QObject, QRectF, QSize, Qt, QUrl, QVariantAnimation from PySide6.QtGui import ( QAction, @@ -17,7 +16,6 @@ QLinearGradient, QMouseEvent, QPen, - QPixmap, QResizeEvent, ) from PySide6.QtMultimedia import QAudioOutput, QMediaDevices, QMediaPlayer @@ -36,7 +34,7 @@ from tagstudio.i18n.translations import Translations from tagstudio.qt.controllers.clickable_slider import ClickableSlider -from tagstudio.qt.views.styles.color_overlay import light_overlay +from tagstudio.qt.views.styles.color_overlay import apply_overlay if typing.TYPE_CHECKING: from tagstudio.qt.qt_driver import QtDriver @@ -56,18 +54,11 @@ class MediaPlayer(QGraphicsView): def __init__(self, driver: QtDriver) -> None: super().__init__() self.driver = driver - self.play_icon = QPixmap.fromImage( - ImageQt.ImageQt(light_overlay(self.driver.rm.bxs_right_arrow, use_alpha=False)) - ) - self.pause_icon = QPixmap.fromImage( - ImageQt.ImageQt(light_overlay(self.driver.rm.pause_icon, use_alpha=False)) - ) - self.mute_icon = QPixmap.fromImage( - ImageQt.ImageQt(light_overlay(self.driver.rm.mute_icon, use_alpha=False)) - ) - self.volume_icon = QPixmap.fromImage( - ImageQt.ImageQt(light_overlay(self.driver.rm.volume_icon, use_alpha=False)) - ) + white = QColor(Qt.GlobalColor.white) + self.play_icon = apply_overlay(self.driver.rm.bxs_right_arrow, white) + self.pause_icon = apply_overlay(self.driver.rm.pause_icon, white) + self.mute_icon = apply_overlay(self.driver.rm.mute_icon, white) + self.volume_icon = apply_overlay(self.driver.rm.volume_icon, white) slider_style = """ QSlider { diff --git a/src/tagstudio/qt/qt_file_renderer.py b/src/tagstudio/qt/qt_file_renderer.py index 838eda2fdb..d510c57885 100644 --- a/src/tagstudio/qt/qt_file_renderer.py +++ b/src/tagstudio/qt/qt_file_renderer.py @@ -1,22 +1,114 @@ # SPDX-FileCopyrightText: (c) TagStudio Contributors # SPDX-License-Identifier: GPL-3.0-only +import math +from functools import cache, lru_cache from pathlib import Path -from PIL import ImageQt -from PySide6.QtCore import QObject, QSize, Signal -from PySide6.QtGui import QGuiApplication, QPixmap, Qt +from PIL import Image, ImageQt +from PySide6.QtCore import QObject, QRectF, Signal +from PySide6.QtGui import QColor, QGuiApplication, QImage, QPainter, QPen, QPixmap, Qt +from tagstudio.core.enums import Theme from tagstudio.core.library.alchemy.library import Library -from tagstudio.previews.file_renderer import FileRenderer -from tagstudio.qt.app_settings import AppSettings, Theme +from tagstudio.core.media_types import slugify +from tagstudio.previews.file_renderer import FileRenderer, RenderResult +from tagstudio.qt.app_settings import AppSettings from tagstudio.qt.cache_manager import CacheManager +from tagstudio.qt.resource_manager import ResourceManager +from tagstudio.qt.views.styles.palette import ColorType, UiColor, get_ui_color +from tagstudio.qt.views.styles.stylesheets import OUTLINE_WIDTH, RADIUS + + +def _letterbox(image: QImage) -> QImage: + """Center a non-square image over a gradient blended from its corner colors.""" + width, height = image.width(), image.height() + side = max(width, height) + colors = [image.pixelColor(x, y) for y in (0, height - 1) for x in (0, width - 1)] + corners = Image.new("RGB", (2, 2)) + corners.putdata([(c.red(), c.green(), c.blue()) for c in colors]) + background = ImageQt.ImageQt(corners.resize((side, side), Image.Resampling.BICUBIC)).copy() + + painter = QPainter(background) + painter.drawImage((side - width) // 2, (side - height) // 2, image) + painter.end() + return background + + +def paint_fallback_icon_border( + painter: QPainter, rect: QRectF, color: QColor, pixel_ratio: float +) -> None: + """Paint the thick rounded border for fallback icons.""" + width = (OUTLINE_WIDTH + 2) * pixel_ratio + inset = width / 2 + radius = RADIUS * pixel_ratio - inset + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(QPen(color, width)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(rect.adjusted(inset, inset, -inset, -inset), radius, radius) + + +@cache +def _resource_image(name: str) -> QImage: + return ImageQt.ImageQt(ResourceManager().get(name)).copy() + + +def _media_icon(filepath: Path) -> str: + """The icon resource name for the most specific media group of a file.""" + resources = ResourceManager() + for group in FileRenderer.media_groups(filepath): + if resources.get(slugify(group), silent_fail=True): + return slugify(group) + return "file_generic" + + +@lru_cache(maxsize=32) +def _icon(name: str, color: UiColor, theme: Theme, side: int, pixel_ratio: float) -> QImage: + """A default icon centered on a background.""" + is_dark = theme == Theme.DARK + background = get_ui_color(ColorType.DARK_ACCENT if is_dark else ColorType.PRIMARY, color) + foreground = get_ui_color(ColorType.BORDER if is_dark else ColorType.LIGHT_ACCENT, color) + + glyph_side = int(side / 1.75) + glyph = _resource_image(name).scaled( + glyph_side, + glyph_side, + Qt.AspectRatioMode.IgnoreAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + glyph = glyph.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied) + painter = QPainter(glyph) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceIn) + painter.fillRect(glyph.rect(), QColor(foreground)) + painter.end() + + image = QImage(side, side, QImage.Format.Format_ARGB32_Premultiplied) + image.fill(Qt.GlobalColor.transparent) + painter = QPainter(image) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(background)) + painter.drawRoundedRect(QRectF(image.rect()), RADIUS * pixel_ratio, RADIUS * pixel_ratio) + painter.drawImage((side - glyph_side) // 2, (side - glyph_side) // 2, glyph) + painter.end() + return image + + +def _with_corner_icon(image: QImage, name: str) -> QImage: + """Draw an icon in the upper left corner of an image.""" + image = image.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied) + side = min(image.width(), image.height()) + painter = QPainter(image) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + painter.drawImage(QRectF(side / 18, side / 18, side / 5, side / 5), _resource_image(name)) + painter.end() + return image class QtFileRenderer(QObject): """A Qt-specific wrapper for rendering image previews and thumbnails from files.""" - updated = Signal(float, QPixmap, QSize, Path) + updated = Signal(float, QPixmap, Path, object) # Timestamp, image, path, border color def __init__(self, library: Library, settings: AppSettings) -> None: super().__init__() @@ -26,6 +118,46 @@ def __init__(self, library: Library, settings: AppSettings) -> None: if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark else Theme.LIGHT ) + self._theme_color = UiColor.THEME_DARK if self.theme == Theme.DARK else UiColor.THEME_LIGHT + + def _border_color(self, color: UiColor) -> QColor: + color_type = ColorType.PRIMARY if self.theme == Theme.DARK else ColorType.LIGHT_ACCENT + return QColor(get_ui_color(color_type, color)) + + def loading_image(self, size: tuple[int, int], pixel_ratio: float) -> QPixmap: + """The image to show while a thumbnail or preview renders.""" + side = math.ceil(max(size[0], size[1]) * pixel_ratio) + pixmap = QPixmap.fromImage( + _icon("thumb_loading", self._theme_color, self.theme, side, pixel_ratio) + ) + pixmap.setDevicePixelRatio(pixel_ratio) + return pixmap + + def _placeholder( + self, + cache: CacheManager | None, + filepath: Path, + side: int, + pixel_ratio: float, + date_modified: float | None, + ) -> QImage | None: + """What to show while a file's preview renders, or `None` if it won't render.""" + renderer = FileRenderer.find_renderer(filepath) + if ( + renderer is None + or not filepath.is_file() + or FileRenderer.previously_failed(filepath, date_modified) + ): + return None + if renderer.has_small_variant: + # The thumbnail looks different, so stay blank until the preview renders + blank = QImage(side, side, QImage.Format.Format_ARGB32_Premultiplied) + blank.fill(Qt.GlobalColor.transparent) + return blank + cached = FileRenderer.cached_thumbnail(cache, filepath, date_modified) + if cached is None: + return _icon("thumb_loading", self._theme_color, self.theme, side, pixel_ratio) + return ImageQt.ImageQt(cached) def render( self, @@ -34,28 +166,55 @@ def render( filepath: Path | str, size: tuple[int, int], pixel_ratio: float, - is_loading: bool = False, + is_placeholder: bool = False, is_thumb: bool = False, date_modified: float | None = None, ): + filepath = Path(filepath) + side = math.ceil(max(size[0], size[1]) * pixel_ratio) + result = RenderResult(None) + if not is_placeholder: + result = self.renderer.render( + cache=cache, + filepath=filepath, + size=size, + dpi_scale=pixel_ratio, + theme=self.theme, + is_thumb=is_thumb, + date_modified=date_modified, + ) - image, size, timestamp = self.renderer.render( - cache=cache, - timestamp=timestamp, - filepath=filepath, - size=size, - dpi_scale=pixel_ratio, - theme=self.theme, - is_loading=is_loading, - is_thumb=is_thumb, - date_modified=date_modified, - ) + image = None if result.image is None else ImageQt.ImageQt(result.image) + if is_placeholder: + image = self._placeholder(cache, filepath, side, pixel_ratio, date_modified) - qim = ImageQt.ImageQt(image) - pixmap = QPixmap.fromImage(qim) - pixmap.setDevicePixelRatio(pixel_ratio) + border_color = None + if image is None: + is_missing = result.is_unlinked or not filepath.is_file() + cached = None + if is_missing and not is_thumb: + cached = FileRenderer.cached_thumbnail(cache, filepath, date_modified) + if cached is not None: + image = ImageQt.ImageQt(cached) + else: + color = UiColor.RED if is_missing else self._theme_color + name = "broken_link_icon" if is_missing else _media_icon(filepath) + image = _icon(name, color, self.theme, side, pixel_ratio) + border_color = self._border_color(color) + if is_thumb: + image = image.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied) + painter = QPainter(image) + paint_fallback_icon_border( + painter, QRectF(image.rect()), border_color, pixel_ratio + ) + painter.end() + elif is_thumb and image.width() != image.height(): + image = _letterbox(image) - if pixmap: - self.updated.emit(timestamp, pixmap, QSize(size[0], size[1]), filepath) - else: - self.updated.emit(timestamp, QPixmap(), QSize(*size), filepath) + if result.is_unlinked and border_color is None: + image = _with_corner_icon(image, "unlinked_stat") + elif result.is_ignored: + image = _with_corner_icon(image, "ignored") + pixmap = QPixmap.fromImage(image) + pixmap.setDevicePixelRatio(pixel_ratio) + self.updated.emit(timestamp, pixmap, filepath, border_color) diff --git a/src/tagstudio/qt/views/item_thumb_view.py b/src/tagstudio/qt/views/item_thumb_view.py index 3031fc6f0e..3581006d99 100644 --- a/src/tagstudio/qt/views/item_thumb_view.py +++ b/src/tagstudio/qt/views/item_thumb_view.py @@ -36,8 +36,7 @@ class _BadgeStyle(NamedTuple): class ItemThumbView(QVBoxLayout): - FILE_LABEL_HEIGHT = 12 - FILE_LABEL_SPACING = 4 + FILE_LABEL_SPACING = 3 def __init__(self, badge_tag_ids: Iterable[int]) -> None: super().__init__() diff --git a/src/tagstudio/qt/views/library_info_window_view.py b/src/tagstudio/qt/views/library_info_window_view.py index 7c5a2b05d5..953465675a 100644 --- a/src/tagstudio/qt/views/library_info_window_view.py +++ b/src/tagstudio/qt/views/library_info_window_view.py @@ -291,9 +291,7 @@ def __init__(self, library: Library, driver: QtDriver): self.dupe_file_icon = QLabel() dupe_file_image: Image.Image = self.driver.rm.dupe_file_stat - dupe_file_pixmap = QPixmap.fromImage( - ImageQt.ImageQt(auto_theme_overlay(dupe_file_image, use_alpha=False)) - ) + dupe_file_pixmap = auto_theme_overlay(dupe_file_image, use_alpha=False) dupe_file_pixmap.setDevicePixelRatio(self.devicePixelRatio()) dupe_file_pixmap = dupe_file_pixmap.scaledToWidth( math.floor((row_height - icon_margin) * self.devicePixelRatio()), diff --git a/src/tagstudio/qt/views/pagination_view.py b/src/tagstudio/qt/views/pagination_view.py index 0f6c668c6f..186aae6d81 100644 --- a/src/tagstudio/qt/views/pagination_view.py +++ b/src/tagstudio/qt/views/pagination_view.py @@ -4,9 +4,8 @@ from typing import override -from PIL import Image, ImageQt from PySide6.QtCore import QSize -from PySide6.QtGui import QIntValidator, QPixmap, Qt +from PySide6.QtGui import QIntValidator, Qt from PySide6.QtWidgets import QHBoxLayout, QLabel, QLineEdit, QPushButton, QWidget from tagstudio.qt.resource_manager import ResourceManager @@ -38,8 +37,7 @@ def __init__(self) -> None: # [<] ---------------------------------- self.prev_button = QPushButton() - prev_icon: Image.Image = auto_theme_overlay(_rm.bxs_left_arrow, use_alpha=False) - self.prev_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(prev_icon))) + self.prev_button.setIcon(auto_theme_overlay(_rm.bxs_left_arrow, use_alpha=False)) self.prev_button.setIconSize(QSize(12, 12)) self.prev_button.setMinimumSize(self.BUTTON_SIZE) self.prev_button.setMaximumSize(self.BUTTON_SIZE) @@ -86,8 +84,7 @@ def __init__(self) -> None: # ---------------------------------- [>] self.next_button = QPushButton() - next_icon: Image.Image = auto_theme_overlay(_rm.bxs_right_arrow, use_alpha=False) - self.next_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(next_icon))) + self.next_button.setIcon(auto_theme_overlay(_rm.bxs_right_arrow, use_alpha=False)) self.next_button.setIconSize(QSize(12, 12)) self.next_button.setMinimumSize(self.BUTTON_SIZE) self.next_button.setMaximumSize(self.BUTTON_SIZE) diff --git a/src/tagstudio/qt/views/styles/color_overlay.py b/src/tagstudio/qt/views/styles/color_overlay.py index feef8e1331..f64775b8e0 100644 --- a/src/tagstudio/qt/views/styles/color_overlay.py +++ b/src/tagstudio/qt/views/styles/color_overlay.py @@ -2,26 +2,22 @@ # SPDX-License-Identifier: GPL-3.0-only -from PIL import Image +from PIL import Image, ImageQt from PySide6.QtCore import QByteArray, QRectF, QSize, Qt -from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPixmap +from PySide6.QtGui import QColor, QGuiApplication, QImage, QPainter, QPixmap from PySide6.QtSvg import QSvgRenderer -from tagstudio.previews.gradients import linear_gradient - # TODO: Consolidate the built-in QT theme values with the values # here, in enums.py, and in palette.py. -_THEME_DARK_FG: str = "#FFFFFF77" -_THEME_LIGHT_FG: str = "#000000DD" -_THEME_DARK_BG: str = "#000000DD" -_THEME_LIGHT_BG: str = "#FFFFFF55" +_THEME_DARK_FG = QColor(255, 255, 255, 120) +_THEME_LIGHT_FG = QColor(0, 0, 0, 220) def theme_foreground_color() -> QColor: """Return a translucent foreground color for icons and hint text in the current theme.""" if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark: - return QColor(255, 255, 255, 0x77) - return QColor(0, 0, 0, 0x77) + return QColor(255, 255, 255, 120) + return QColor(0, 0, 0, 120) def svg_to_pixmap( @@ -45,70 +41,33 @@ def svg_to_pixmap( def auto_theme_overlay( image: Image.Image, inverse: bool = False, use_alpha: bool = True -) -> Image.Image: +) -> QPixmap: """Overlay the current foreground theme color onto an image. Args: image (Image): The PIL Image object to apply an overlay to. inverse (bool): Option to invert the overlay color relative to the current theme. - use_alpha (bool): Option to retain the base image's alpha value when applying the overlay. + use_alpha (bool): Option to use the theme's translucent foreground color. """ - dark_fg: str = _THEME_DARK_FG[:-2] if not use_alpha else _THEME_DARK_FG - light_fg: str = _THEME_LIGHT_FG[:-2] if not use_alpha else _THEME_LIGHT_FG - - overlay_color = ( - dark_fg if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark else light_fg - ) + is_dark = QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark if inverse: - overlay_color = light_fg if overlay_color == dark_fg else dark_fg - - im = Image.new(mode="RGBA", size=image.size, color=overlay_color) - return _apply_overlay(image, im) - - -def light_overlay(image: Image.Image, use_alpha: bool = True) -> Image.Image: - """Overlay the light theme foreground color onto an image. - - Args: - image (Image): The PIL Image object to apply an overlay to. - use_alpha (bool): Option to retain the base image's alpha value when applying the overlay. - """ - overlay_color: str = _THEME_DARK_FG[:-2] if not use_alpha else _THEME_DARK_FG - im = Image.new(mode="RGBA", size=image.size, color=overlay_color) - return _apply_overlay(image, im) - - -def dark_overlay(image: Image.Image, use_alpha: bool = True) -> Image.Image: - """Overlay the dark theme foreground color onto an image. + is_dark = not is_dark + color = QColor(_THEME_DARK_FG if is_dark else _THEME_LIGHT_FG) + if not use_alpha: + color.setAlpha(255) + return apply_overlay(image, color) - Args: - image (Image): The PIL Image object to apply an overlay to. - use_alpha (bool): Option to retain the base image's alpha value when applying the overlay. - """ - overlay_color: str = _THEME_LIGHT_FG[:-2] if not use_alpha else _THEME_LIGHT_FG - im = Image.new(mode="RGBA", size=image.size, color=overlay_color) - return _apply_overlay(image, im) - - -def gradient_overlay(image: Image.Image, gradient: list[str]) -> Image.Image: - """Overlay a color gradient onto an image. - - Args: - image (Image): The PIL Image object to apply an overlay to. - gradient (list[str): A list of string hex color codes for use as - the colors of the gradient. - """ - im: Image.Image = _apply_overlay(image, linear_gradient(image.size, gradient)) - return im - -def _apply_overlay(image: Image.Image, overlay: Image.Image) -> Image.Image: - """Apply an overlay on top of an image using the image's alpha channel as a mask. +def apply_overlay(image: Image.Image, color: QColor) -> QPixmap: + """Apply a color overlay on top of an image using the image's alpha channel as a mask. Args: image (Image): The PIL Image object to apply an overlay to. - overlay (Image): The PIL Image object to act as the overlay contents. + color (QColor): The color of the overlay. """ - im: Image.Image = Image.new(mode="RGBA", size=image.size, color="#00000000") - im.paste(overlay, (0, 0), mask=image) - return im + overlaid = ImageQt.ImageQt(image).convertToFormat(QImage.Format.Format_ARGB32_Premultiplied) + painter = QPainter(overlaid) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceIn) + painter.fillRect(overlaid.rect(), color) + painter.end() + return QPixmap.fromImage(overlaid) diff --git a/src/tagstudio/qt/views/styles/stylesheets.py b/src/tagstudio/qt/views/styles/stylesheets.py index 74bbe3a716..290244fc5c 100644 --- a/src/tagstudio/qt/views/styles/stylesheets.py +++ b/src/tagstudio/qt/views/styles/stylesheets.py @@ -25,6 +25,9 @@ RADIUS = 6 # Standard corner radius INNER_RADIUS = RADIUS // 2 # Inner/small corder radius + +OUTLINE_WIDTH = 2 # Hover/selection outlines + PAD = 6 # Standard padding value HALF_PAD = PAD // 2 WIN_PAD = 12 # Padding used for window edge margins @@ -502,7 +505,7 @@ def autofill_scroll_top_focus_style(object_name: str = "") -> str: border-top-left-radius: {RADIUS}px; border-top-right-radius: {RADIUS}px; border: solid; - border-width: 2px 2px 0px 2px; + border-width: {OUTLINE_WIDTH}px {OUTLINE_WIDTH}px 0px {OUTLINE_WIDTH}px; border-color: rgba{Palette.accent().toTuple()}; }} """ @@ -530,7 +533,7 @@ def autofill_line_edit_style(is_invalid: bool = False) -> str: QLineEdit::focus{{ padding: 4px 4px; border: solid; - border-width: 2px; + border-width: {OUTLINE_WIDTH}px; border-color: {focus_border_color}; }} """ @@ -551,12 +554,12 @@ def autofill_line_edit_top_style() -> str: border-top-right-radius: 0px; border-bottom-left-radius: {RADIUS}px; border-bottom-right-radius: {RADIUS}px; - padding: 0px 0px 2px {RADIUS}px; + padding: 0px 0px {OUTLINE_WIDTH}px {RADIUS}px; }} QLineEdit::focus{{ padding: 4px 4px; border: solid; - border-width: 0px 2px 2px 2px; + border-width: 0px {OUTLINE_WIDTH}px {OUTLINE_WIDTH}px {OUTLINE_WIDTH}px; border-color: rgba{Palette.accent().toTuple()}; }} """ diff --git a/src/tagstudio/qt/views/tiles/tile_view.py b/src/tagstudio/qt/views/tiles/tile_view.py index 23c99ced24..c79f8fa11c 100644 --- a/src/tagstudio/qt/views/tiles/tile_view.py +++ b/src/tagstudio/qt/views/tiles/tile_view.py @@ -2,9 +2,7 @@ # SPDX-License-Identifier: GPL-3.0-only -from PIL import ImageQt from PySide6.QtCore import QSize, Qt -from PySide6.QtGui import QPixmap from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget from tagstudio.qt.resource_manager import ResourceManager @@ -21,9 +19,6 @@ class TileView(QVBoxLayout): """The layout used for a Tile widget.""" _rm = ResourceManager() - copy_icon = auto_theme_overlay(_rm.copy, inverse=True) - edit_icon = auto_theme_overlay(_rm.edit, inverse=True) - trash_icon = auto_theme_overlay(_rm.trash, inverse=True) def __init__(self) -> None: super().__init__() @@ -53,7 +48,7 @@ def __init__(self) -> None: self.copy_button.setMinimumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.copy_button.setMaximumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.copy_button.setFlat(True) - self.copy_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(self.copy_icon))) + self.copy_button.setIcon(auto_theme_overlay(self._rm.copy, inverse=True)) self.copy_button.setIconSize(QSize(_ICON_SIZE, _ICON_SIZE)) self.copy_button.setCursor(Qt.CursorShape.PointingHandCursor) self.title_layout.addWidget(self.copy_button) @@ -63,7 +58,7 @@ def __init__(self) -> None: self.edit_button.setMinimumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.edit_button.setMaximumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.edit_button.setFlat(True) - self.edit_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(self.edit_icon))) + self.edit_button.setIcon(auto_theme_overlay(self._rm.edit, inverse=True)) self.edit_button.setIconSize(QSize(_ICON_SIZE, _ICON_SIZE)) self.edit_button.setCursor(Qt.CursorShape.PointingHandCursor) self.title_layout.addWidget(self.edit_button) @@ -73,7 +68,7 @@ def __init__(self) -> None: self.remove_button.setMinimumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.remove_button.setMaximumSize(_BUTTON_SIZE, _BUTTON_SIZE) self.remove_button.setFlat(True) - self.remove_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(self.trash_icon))) + self.remove_button.setIcon(auto_theme_overlay(self._rm.trash, inverse=True)) self.remove_button.setIconSize(QSize(_ICON_SIZE, _ICON_SIZE)) self.remove_button.setCursor(Qt.CursorShape.PointingHandCursor) self.title_layout.addWidget(self.remove_button)