Compare commits

..

1 Commits

Author SHA1 Message Date
Travis Abendshien
f7f4da8acd refactor: port #455 functionality to main
Co-Authored-By: Tyrannicodin <tyrannicodin@gmail.com>
2025-03-11 23:49:59 -07:00
220 changed files with 5895 additions and 13348 deletions

18
.envrc.recommended Normal file
View File

@@ -0,0 +1,18 @@
# If you wish to use this file, copy or symlink it to `.envrc` for direnv to read it.
# This will use the flake development shell.
if ! has nix_direnv_version || ! nix_direnv_version 3.0.6; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.6/direnvrc" "sha256-RYcUJaRMf8oF5LznDrlCXbkOQrywm0HDv1VjYGaJGdM="
fi
if [ -f .venv/bin/activate ]; then
# If the file is watched when it does not exist,
# direnv will execute again when it gets created.
watch_file .venv/bin/activate
fi
watch_file nix/shell.nix
watch_file pyproject.toml
use flake
# vi: ft=bash

View File

@@ -101,7 +101,7 @@ jobs:
suffix: _portable
file-end: .exe
runs-on: windows-2022
runs-on: windows-2019
steps:
- name: Checkout repo

View File

@@ -12,9 +12,9 @@ jobs:
uses: actions/checkout@v4
- name: Execute Ruff format
uses: astral-sh/ruff-action@v3
uses: chartboost/ruff-action@v1
with:
version: 0.11.0
version: 0.8.1
args: format --check
ruff-check:
@@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v4
- name: Execute Ruff check
uses: astral-sh/ruff-action@v3
uses: chartboost/ruff-action@v1
with:
version: 0.11.8
version: 0.8.1
args: check

View File

@@ -1,26 +1,7 @@
---
repos:
- repo: local
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.6.4
hooks:
- id: mypy
name: mypy
entry: mypy
language: system
types_or: [python, pyi]
require_serial: true
- id: ruff
name: ruff
entry: ruff check
language: system
types_or: [python, pyi, jupyter]
args: [--force-exclude]
require_serial: true
- id: ruff-format
name: ruff-format
entry: ruff format
language: system
types_or: [python, pyi, jupyter]
args: [--force-exclude, --check]
require_serial: true
- id: ruff

View File

@@ -5,805 +5,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [9.5.2] - 2025-03-31
### Added
#### Search
- feat(ui): add setting to not display full filepaths by [@HermanKassler](https://github.com/HermanKassler) in [#841](https://github.com/TagStudioDev/TagStudio/pull/841)
- feat: add filename and path sorting by [@Computerdores](https://github.com/Computerdores) in [#842](https://github.com/TagStudioDev/TagStudio/pull/842)
#### Settings
- feat: new settings menu + settings backend by [@Computerdores](https://github.com/Computerdores) in [#859](https://github.com/TagStudioDev/TagStudio/pull/859)
#### UI
- feat(ui): merge media controls by [@csponge](https://github.com/csponge) in [#805](https://github.com/TagStudioDev/TagStudio/pull/805)
- fix: Remove border from video preview top and left by [@zfbx](https://github.com/zfbx) in [#900](https://github.com/TagStudioDev/TagStudio/pull/900)
- feat(ui): add more default icons and file type equivalencies by [@CyanVoxel](https://github.com/CyanVoxel) in [#882](https://github.com/TagStudioDev/TagStudio/pull/882)
- ui: recent libraries list improvements by [@CyanVoxel](https://github.com/CyanVoxel) in [#881](https://github.com/TagStudioDev/TagStudio/pull/881)
#### Misc
- feat: provide a .desktop file by [@xarvex](https://github.com/xarvex) in [#870](https://github.com/TagStudioDev/TagStudio/pull/870)
### Fixed
- fix: catch NotImplementedError for Float16 JPEG-XL files by [@CyanVoxel](https://github.com/CyanVoxel) in [#849](https://github.com/TagStudioDev/TagStudio/pull/849)
- fix(nix/package): account for GTK platform by [@xarvex](https://github.com/xarvex) in [#868](https://github.com/TagStudioDev/TagStudio/pull/868)
- fix: do not set palette for Linux-like systems that offer theming by [@xarvex](https://github.com/xarvex) in [#869](https://github.com/TagStudioDev/TagStudio/pull/869)
- fix(flake): remove pinned input, only consume in Nix shell by [@xarvex](https://github.com/xarvex) in [#872](https://github.com/TagStudioDev/TagStudio/pull/872)
- fix: stop ffmpeg cmd windows, refactor ffmpeg_checker by [@CyanVoxel](https://github.com/CyanVoxel) in [#855](https://github.com/TagStudioDev/TagStudio/pull/855)
- fix: hide mnemonics on macOS by [@CyanVoxel](https://github.com/CyanVoxel) in [#856](https://github.com/TagStudioDev/TagStudio/pull/856)
- fix: use UNION instead of UNION ALL by [@CyanVoxel](https://github.com/CyanVoxel) in [#877](https://github.com/TagStudioDev/TagStudio/pull/877)
- fix: remove unescaped ampersand from "about.description" by [@CyanVoxel](https://github.com/CyanVoxel) in [#885](https://github.com/TagStudioDev/TagStudio/pull/885)
- fix(ui): display 0 frame webp files in preview panel by [@CyanVoxel](https://github.com/CyanVoxel) in [64dc88a](https://github.com/TagStudioDev/TagStudio/commit/64dc88afa90bb11f3c9b74a2522f947370ce21db)
- fix: close pdf file object in thumb renderer by [@Computerdores](https://github.com/Computerdores) in [#893](https://github.com/TagStudioDev/TagStudio/pull/893)
- perf: improve responsiveness of GIF entries by [@Computerdores](https://github.com/Computerdores) in [#894](https://github.com/TagStudioDev/TagStudio/pull/894)
- fix(ui): seamlessly loop videos by [@CyanVoxel](https://github.com/CyanVoxel) in [#902](https://github.com/TagStudioDev/TagStudio/pull/902)
### Internal Changes
- refactor!: change layout; import and build change by [@xarvex](https://github.com/xarvex) and [@CyanVoxel](https://github.com/CyanVoxel) in [#844](https://github.com/TagStudioDev/TagStudio/pull/844)
- fix: log all problems in translation test by [@Computerdores](https://github.com/Computerdores) in [#839](https://github.com/TagStudioDev/TagStudio/pull/839)
- refactor: split translation keys for about screen by [@CyanVoxel](https://github.com/CyanVoxel) in [#845](https://github.com/TagStudioDev/TagStudio/pull/845)
- feat(ci): development tooling refresh and split documentation by [@xarvex](https://github.com/xarvex) in [#867](https://github.com/TagStudioDev/TagStudio/pull/867)
- refactor: type hints and improvements in file_opener.py by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#876](https://github.com/TagStudioDev/TagStudio/pull/876)
- build: update spec file to use proper pathex and datas paths by [@Leonard2](https://github.com/Leonard2) in [#895](https://github.com/TagStudioDev/TagStudio/pull/895)
- refactor: fix various missing and broken type hints@VasigaranAndAngel in [#901](https://github.com/TagStudioDev/TagStudio/pull/901)
- refactor: fix type hints and overrides in flowlayout.py by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#880](https://github.com/TagStudioDev/TagStudio/pull/880)
### Documentation
- docs: fix typos and grammar by [@Gawidev](https://github.com/Gawidev) in [#879](https://github.com/TagStudioDev/TagStudio/pull/879)
- docs: update `ThumbRenderer` source by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#896](https://github.com/TagStudioDev/TagStudio/pull/896)
### Translations
- Added Japanese (50%)
- [@needledetector](https://github.com/needledetector)
- Updated Turkish (93%)
- [@Nyghl](https://github.com/Nyghl)
- Updated Filipino (57%)
- [@searinminecraft](https://github.com/searinminecraft)
- Updated Tamil (92%)
- [@TamilNeram](https://github.com/TamilNeram)
- Updated Portuguese (Brazil) (83%)
- [@viniciushelder](https://github.com/viniciushelder)
- Updated German (95%)
- [@DontBlameMe99](https://github.com/DontBlameMe99), [@Computerdores](https://github.com/Computerdores)
- Updated Russian (85%)
- werdi, [@Dott-rus](https://github.com/Dott-rus)
- Updated Hungarian (100%)
- Szíjártó Levente Pál
- Updated Spanish (96%)
- Joan, [@Nginearing](https://github.com/Nginearing)
- Updated French (100%)
- [@kitsumed](https://github.com/kitsumed)
- Updated Toki Pona (80%)
- [@Math-Bee](https://github.com/Math-Bee)
## [9.5.1] - 2025-03-06
### Fixed
- Fixed translations crashing the program and preventing it from being reopened ([#827](https://github.com/TagStudioDev/TagStudio/issues/827))
- fix: restore `translate_formatted()` method as `format()` by [@CyanVoxel](https://github.com/CyanVoxel) in [#830](https://github.com/TagStudioDev/TagStudio/pull/830)
- tests: add tests for translations by [@Computerdores](https://github.com/Computerdores) in [#833](https://github.com/TagStudioDev/TagStudio/pull/833)
- fix(translations): fix invalid placeholders by [@CyanVoxel](https://github.com/CyanVoxel) in [#835](https://github.com/TagStudioDev/TagStudio/pull/835)
- Removed empty parentheses from the "About" screen title
- fix: separate about screen title from translations by [@CyanVoxel](https://github.com/CyanVoxel) in [#836](https://github.com/TagStudioDev/TagStudio/pull/836)
### Translations
- Updated French (99%)
- [@alessdangelo](https://github.com/alessdangelo), [@Bamowen](https://github.com/Bamowen), [@kitsumed](https://github.com/kitsumed)
- Updated German (98%)
- [@Thesacraft](https://github.com/Thesacraft)
- Updated Portuguese (Brazil) (88%)
- [@viniciushelder](https://github.com/viniciushelder)
- Updated Russian (73%)
- werdei
- Updated Spanish (95%)
- [@JCC1998](https://github.com/JCC1998)
### Documentation
- docs: fix category typo by [@salem404](https://github.com/salem404) in [#834](https://github.com/TagStudioDev/TagStudio/pull/834)
## [9.5.0] - 2025-03-03
### Added
#### Overhauled Search Engine
##### Boolean Operators
- feat: implement query language by [@Computerdores](https://github.com/Computerdores) in [#606](https://github.com/TagStudioDev/TagStudio/pull/606)
- feat: optimize AND queries by [@Computerdores](https://github.com/Computerdores) in [#679](https://github.com/TagStudioDev/TagStudio/pull/679)
##### Filetype, Mediatype, and Glob Path + Smartcase Searches
- fix: remove wildcard requirement for tags by [@Tyrannicodin](https://github.com/Tyrannicodin) in [#481](https://github.com/TagStudioDev/TagStudio/pull/481)
- feat: add filetype and mediatype searches by [@python357-1](https://github.com/python357-1) in [#575](https://github.com/TagStudioDev/TagStudio/pull/575)
- feat: make path search use globs by [@python357-1](https://github.com/python357-1) in [#582](https://github.com/TagStudioDev/TagStudio/pull/582)
- feat: implement search equivalence of "jpg" and "jpeg" filetypes by [@Computerdores](https://github.com/Computerdores) in [#649](https://github.com/TagStudioDev/TagStudio/pull/649)
- feat: add smartcase and globless path searches by [@CyanVoxel](https://github.com/CyanVoxel) in [#743](https://github.com/TagStudioDev/TagStudio/pull/743)
##### Sortable Results
- feat: sort by "date added" in library by [@Computerdores](https://github.com/Computerdores) in [#674](https://github.com/TagStudioDev/TagStudio/pull/674)
##### Autocomplete
- feat: add autocomplete for search engine by [@python357-1](https://github.com/python357-1) in [#586](https://github.com/TagStudioDev/TagStudio/pull/586)
#### Replaced "Tag Fields" with Tag Categories
Instead of tags needing to be added to a tag field type such as "Meta Tags", "Content Tags", or just the "Tags" field, tags are now added directly to file entries with no intermediary step. While tag field types offered a way to further organize tags, it was cumbersome, inflexible, and simply not fully fleshed out. Tag Categories offer all of the previous (intentional) functionality while greatly increasing the ease of use and customization.
- feat!: tag categories by [@CyanVoxel](https://github.com/CyanVoxel) in [#655](https://github.com/TagStudioDev/TagStudio/pull/655)
[![Screenshot 2025-01-04 at 04 23 43](https://private-user-images.githubusercontent.com/46939827/400138597-0b92eca5-db8f-4e3e-954b-1b4f3795f073.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MDAxMzg1OTctMGI5MmVjYTUtZGI4Zi00ZTNlLTk1NGItMWI0ZjM3OTVmMDczLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWY4ZWEzOWRkZjkwOGZmYjZmZDUzMjU1MjJhNDNkNzYzZmM4YjZkMTUyNWIzMjNhMGY1NWNhYmU4ODNiNzlhMzYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.cE_WO9AHsigusAbtaQV0QtN4FjYJz0lyHLLwFFDBO-0)](https://private-user-images.githubusercontent.com/46939827/400138597-0b92eca5-db8f-4e3e-954b-1b4f3795f073.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MDAxMzg1OTctMGI5MmVjYTUtZGI4Zi00ZTNlLTk1NGItMWI0ZjM3OTVmMDczLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWY4ZWEzOWRkZjkwOGZmYjZmZDUzMjU1MjJhNDNkNzYzZmM4YjZkMTUyNWIzMjNhMGY1NWNhYmU4ODNiNzlhMzYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.cE_WO9AHsigusAbtaQV0QtN4FjYJz0lyHLLwFFDBO-0)
#### Thumbnails and File Previews
##### New Thumbnail Support
- feat: add svg thumbnail support (port [#442](https://github.com/TagStudioDev/TagStudio/pull/442)) by [@Tyrannicodin](https://github.com/Tyrannicodin) and [@CyanVoxel](https://github.com/CyanVoxel) in [#540](https://github.com/TagStudioDev/TagStudio/pull/540)
- feat: add pdf thumbnail support (port [#378](https://github.com/TagStudioDev/TagStudio/pull/378)) by [@Heiholf](https://github.com/Heiholf) and [@CyanVoxel](https://github.com/CyanVoxel) in [#543](https://github.com/TagStudioDev/TagStudio/pull/543)
- feat: add ePub thumbnail support (port [#387](https://github.com/TagStudioDev/TagStudio/pull/387)) by [@Heiholf](https://github.com/Heiholf) and [@CyanVoxel](https://github.com/CyanVoxel) in [#539](https://github.com/TagStudioDev/TagStudio/pull/539)
- feat: add OpenDocument thumbnail support (port [#366](https://github.com/TagStudioDev/TagStudio/pull/366)) by [@Joshua-Beatty](https://github.com/Joshua-Beatty) and [@CyanVoxel](https://github.com/CyanVoxel) in [#545](https://github.com/TagStudioDev/TagStudio/pull/545)
- feat: add JXL thumbnail and animated APNG + WEBP support (port [#344](https://github.com/TagStudioDev/TagStudio/pull/344) and partially port [#357](https://github.com/TagStudioDev/TagStudio/pull/357)) by [@BPplays](https://github.com/BPplays) and [@CyanVoxel](https://github.com/CyanVoxel) in [#549](https://github.com/TagStudioDev/TagStudio/pull/549)
- fix: catch ImportError for pillow_jxl module by [@CyanVoxel](https://github.com/CyanVoxel) in [a2f9685](https://github.com/TagStudioDev/TagStudio/commit/a2f9685bc0d744ea6f5334c6d2926aad3f6d375a)
##### Audio Playback
- feat: audio playback by [@csponge](https://github.com/csponge) in [#576](https://github.com/TagStudioDev/TagStudio/pull/576)
- feat(ui): add audio volume slider by [@SkeleyM](https://github.com/SkeleyM) in [#691](https://github.com/TagStudioDev/TagStudio/pull/691)
##### Thumbnail Caching
- feat(ui): add thumbnail caching by [@CyanVoxel](https://github.com/CyanVoxel) in [#694](https://github.com/TagStudioDev/TagStudio/pull/694)
#### Tags
##### Delete Tags _(Finally!)_
- feat: remove and create tags from tag database panel by [@DandyDev01](https://github.com/DandyDev01) in [#569](https://github.com/TagStudioDev/TagStudio/pull/569)
##### Custom User-Created Tag Colors
Create your own custom tag colors via the new Tag Color Manager! Tag colors are assigned a namespace (group) and include a name, primary color, and optional secondary color. By default the secondary color is used for the tag text color, but this can also be toggled to apply to the border color as well!
- feat(ui)!: user-created tag colors@CyanVoxel in [#801](https://github.com/TagStudioDev/TagStudio/pull/801)
[![](https://private-user-images.githubusercontent.com/46939827/413668576-b591f1fe-1c44-4d82-b6e5-d166590aeab1.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg1NzYtYjU5MWYxZmUtMWM0NC00ZDgyLWI2ZTUtZDE2NjU5MGFlYWIxLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTdiZjM4NzczYTFhYmFhNjgwMWJlYjgwNTkzYjA3ZWFlNTkwNzBiYTlhNTAzM2Y0MWM1MWQ0MzY1YmEyNmE4NjAmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.EOEVWLDMx5CT-Gg5UhBmdMIYT49IZPKrrA9VL7N-pBQ)](https://private-user-images.githubusercontent.com/46939827/413668576-b591f1fe-1c44-4d82-b6e5-d166590aeab1.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg1NzYtYjU5MWYxZmUtMWM0NC00ZDgyLWI2ZTUtZDE2NjU5MGFlYWIxLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTdiZjM4NzczYTFhYmFhNjgwMWJlYjgwNTkzYjA3ZWFlNTkwNzBiYTlhNTAzM2Y0MWM1MWQ0MzY1YmEyNmE4NjAmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.EOEVWLDMx5CT-Gg5UhBmdMIYT49IZPKrrA9VL7N-pBQ) [![](https://private-user-images.githubusercontent.com/46939827/413668612-96e81b08-6993-4a5e-96d0-3b05b50fbe44.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg2MTItOTZlODFiMDgtNjk5My00YTVlLTk2ZDAtM2IwNWI1MGZiZTQ0LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWJkNTUxODJiMDZhN2I2MDAxYzZlNzIyOTAzYTgwZDg3ZDFlYWM3ODM1YWY0Mzg5MDJjNDY0NzJhYjU4ZTAzMmEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.rqM3YOwrYdBCiwbBbEvalj7Tsfl-XWqgD1K9PeE46tI)](https://private-user-images.githubusercontent.com/46939827/413668612-96e81b08-6993-4a5e-96d0-3b05b50fbe44.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg2MTItOTZlODFiMDgtNjk5My00YTVlLTk2ZDAtM2IwNWI1MGZiZTQ0LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWJkNTUxODJiMDZhN2I2MDAxYzZlNzIyOTAzYTgwZDg3ZDFlYWM3ODM1YWY0Mzg5MDJjNDY0NzJhYjU4ZTAzMmEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.rqM3YOwrYdBCiwbBbEvalj7Tsfl-XWqgD1K9PeE46tI)
##### New Tag Colors + UI
- feat: expanded tag color system by [@CyanVoxel](https://github.com/CyanVoxel) in [#709](https://github.com/TagStudioDev/TagStudio/pull/709)
- fix(ui): use correct pink tag color by [@CyanVoxel](https://github.com/CyanVoxel) in [431efe4](https://github.com/TagStudioDev/TagStudio/commit/431efe4fe93213141c763e59ca9887215766fd42)
- fix(ui): use consistent tag outline colors by [@CyanVoxel](https://github.com/CyanVoxel) in [020a73d](https://github.com/TagStudioDev/TagStudio/commit/020a73d095c74283d6c80426d3c3db8874409952)
[![Screenshot 2025-01-04 at 04 23 43](https://private-user-images.githubusercontent.com/46939827/408753168-c8f82d89-ad7e-4be6-830e-b91cdc58e4c6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MDg3NTMxNjgtYzhmODJkODktYWQ3ZS00YmU2LTgzMGUtYjkxY2RjNThlNGM2LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTk1OWNhZGNkOTRiZGJhNGQxNGU1MjJhYTViYTc0OTNiNTA4NDUxODA4OTYxZDUwNzYxZDhmYWZkNzM4NTE3N2QmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.HLnwHyp3BYg8vXo3BtvqBoOqtpQTI1eykqa-L3chLUk)](https://private-user-images.githubusercontent.com/46939827/408753168-c8f82d89-ad7e-4be6-830e-b91cdc58e4c6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTU5ODIsIm5iZiI6MTc0NjY1NTY4MiwicGF0aCI6Ii80NjkzOTgyNy80MDg3NTMxNjgtYzhmODJkODktYWQ3ZS00YmU2LTgzMGUtYjkxY2RjNThlNGM2LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIyMDgwMlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTk1OWNhZGNkOTRiZGJhNGQxNGU1MjJhYTViYTc0OTNiNTA4NDUxODA4OTYxZDUwNzYxZDhmYWZkNzM4NTE3N2QmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.HLnwHyp3BYg8vXo3BtvqBoOqtpQTI1eykqa-L3chLUk)
##### New Tag Alias UI
- fix: preview panel aliases not staying up to date with database by [@DandyDev01](https://github.com/DandyDev01) in [#641](https://github.com/TagStudioDev/TagStudio/pull/641)
- fix: subtags/parent tags & aliases update the UI for building a tag by [@DandyDev01](https://github.com/DandyDev01) in [#534](https://github.com/TagStudioDev/TagStudio/pull/534)
#### Translations
TagStudio now has official translation support! Head to the new settings panel and select from one of the initial languages included. Note that many languages currently have incomplete translations.
Translation hosting generously provided by [Weblate](https://weblate.org/en/). Check out our [project page](https://hosted.weblate.org/projects/tagstudio/) to help translate TagStudio! Thank you to everyone who's helped contribute to the translations so far!
- translations: add string tokens for en.json by [@Bamowen](https://github.com/Bamowen) in [#507](https://github.com/TagStudioDev/TagStudio/pull/507)
- feat: translations by [@Computerdores](https://github.com/Computerdores) in [#662](https://github.com/TagStudioDev/TagStudio/pull/662)
- feat(ui): add language setting by [@CyanVoxel](https://github.com/CyanVoxel) in [#803](https://github.com/TagStudioDev/TagStudio/pull/803)
Initial Languages:
- Chinese (Traditional) (68%)
- [@brisu](https://github.com/brisu)
- Dutch (35%)
- [@Pheubel](https://github.com/Pheubel)
- Filipino (43%)
- [@searinminecraft](https://github.com/searinminecraft)
- French (100%)
- [@Bamowen](https://github.com/Bamowen), [@alessdangelo](https://github.com/alessdangelo), [@kitsumed](https://github.com/kitsumed), Obscaeris
- German (98%)
- [@Ryussei](https://github.com/Ryussei), [@Computerdores](https://github.com/Computerdores), Aaron M, [@JoeJoeTV](https://github.com/JoeJoeTV), [@Kurty00](https://github.com/Kurty00)
- Hungarian (100%)
- [@smileyhead](https://github.com/smileyhead)
- Norwegian Bokmål (16%)
- [@comradekingu](https://github.com/comradekingu)
- Polish (97%)
- Anonymous
- Portuguese (Brazil) (64%)
- [@LoboMetalurgico](https://github.com/LoboMetalurgico), [@SpaceFox1](https://github.com/SpaceFox1), [@DaviMarquezeli](https://github.com/DaviMarquezeli), [@viniciushelder](https://github.com/viniciushelder), Alexander Lennart Formiga Johnsson
- Russian (22%)
- [@The-Stolas](https://github.com/The-Stolas)
- Spanish (57%)
- [@gallegonovato](https://github.com/gallegonovato), [@Nginearing](https://github.com/Nginearing), [@noceno](https://github.com/noceno)
- Swedish (24%)
- [@adampawelec](https://github.com/adampawelec), [@mashed5894](https://github.com/mashed5894)
- Tamil (22%)
- [@VasigaranAndAngel](https://github.com/VasigaranAndAngel)
- Toki Pona (32%)
- [@goldstargloww](https://github.com/goldstargloww)
- Turkish (22%)
- [@Nyghl](https://github.com/Nyghl)
#### Miscellaneous
- feat: about section by [@mashed5894](https://github.com/mashed5894) in [#712](https://github.com/TagStudioDev/TagStudio/pull/712)
- feat(ui): add configurable splash screens by [@CyanVoxel](https://github.com/CyanVoxel) in [#703](https://github.com/TagStudioDev/TagStudio/pull/703)
- feat(ui): show filenames in thumbnail grid by [@CyanVoxel](https://github.com/CyanVoxel) in [#633](https://github.com/TagStudioDev/TagStudio/pull/633)
- feat(about): clickable links to docs/discord/etc in about modal by [@SkeleyM](https://github.com/SkeleyM) in [#799](https://github.com/TagStudioDev/TagStudio/pull/799)
### Fixed
- fix(ui): display all tags in panel during empty search by [@samuellieberman](https://github.com/samuellieberman) in [#328](https://github.com/TagStudioDev/TagStudio/pull/328)
- fix: avoid `KeyError` in `add_folders_to_tree()` (fix [#346](https://github.com/TagStudioDev/TagStudio/issues/346)) by [@CyanVoxel](https://github.com/CyanVoxel) in [#347](https://github.com/TagStudioDev/TagStudio/pull/347)
- fix: error on closing library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#484](https://github.com/TagStudioDev/TagStudio/pull/484)
- fix: resolution info [#550](https://github.com/TagStudioDev/TagStudio/issues/550) by [@Roc25](https://github.com/Roc25) in [#551](https://github.com/TagStudioDev/TagStudio/pull/551)
- fix: remove queued thumnail jobs when closing library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#583](https://github.com/TagStudioDev/TagStudio/pull/583)
- fix: use absolute ffprobe path on macos (Fix [#511](https://github.com/TagStudioDev/TagStudio/issues/511)) by [@CyanVoxel](https://github.com/CyanVoxel) in [#629](https://github.com/TagStudioDev/TagStudio/pull/629)
- fix(ui): prevent duplicate parent tags in UI by [@SkeleyM](https://github.com/SkeleyM) in [#665](https://github.com/TagStudioDev/TagStudio/pull/665)
- fix: fix -o flag not working if path has whitespace around it by [@python357-1](https://github.com/python357-1) in [#670](https://github.com/TagStudioDev/TagStudio/pull/670)
- fix: better file opening compatibility with non-ascii filenames by [@SkeleyM](https://github.com/SkeleyM) in [#667](https://github.com/TagStudioDev/TagStudio/pull/667)
- fix: restore environment before launching external programs by [@mashed5894](https://github.com/mashed5894) in [#707](https://github.com/TagStudioDev/TagStudio/pull/707)
- fix: have pydub use known ffmpeg + ffprobe locations by [@CyanVoxel](https://github.com/CyanVoxel) in [#724](https://github.com/TagStudioDev/TagStudio/pull/724)
- fix: add ".DS_Store" to `GLOBAL_IGNORE_SET` by [@CyanVoxel](https://github.com/CyanVoxel) in [b72a2f2](https://github.com/TagStudioDev/TagStudio/commit/b72a2f233141db4db6aa6be8796b626ebd3f0756)
- fix: don't add "._" files to libraries by [@CyanVoxel](https://github.com/CyanVoxel) in [eb1f634](https://github.com/TagStudioDev/TagStudio/commit/eb1f634d386cd8a5ecee1e6ff6a0b7d8811550fa)
### Changed
#### SQLite Save File Format
This was the main focus of this update, and where the majority of development time and resources have been spent since v9.4. These changes include everything that was done to migrate from the JSON format to SQLite starting from the initial SQLite PR, while re-implementing every feature from v9.4 as the initial SQLite PR was based on v9.3.x at the time.
- refactor!: use SQLite and SQLAlchemy for database backend by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#332](https://github.com/TagStudioDev/TagStudio/pull/332)
- feat: make search results more ergonomic by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#498](https://github.com/TagStudioDev/TagStudio/pull/498)
- feat: store `Entry` suffix separately by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#503](https://github.com/TagStudioDev/TagStudio/pull/503)
- feat: port thumbnail ([#390](https://github.com/TagStudioDev/TagStudio/pull/390)) and related features to v9.5 by [@CyanVoxel](https://github.com/CyanVoxel) in [#522](https://github.com/TagStudioDev/TagStudio/pull/522)
- fix: don't check db version with new library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#536](https://github.com/TagStudioDev/TagStudio/pull/536)
- fix(ui): update ui when removing fields by [@DandyDev01](https://github.com/DandyDev01) in [#560](https://github.com/TagStudioDev/TagStudio/pull/560)
- feat(parity): backend for aliases and parent tags by [@DandyDev01](https://github.com/DandyDev01) in [#596](https://github.com/TagStudioDev/TagStudio/pull/596)
- fix: "open in explorer" opens correct folder by [@KirilBourakov](https://github.com/KirilBourakov) in [#603](https://github.com/TagStudioDev/TagStudio/pull/603)
- fix: ui/ux parity fixes for thumbnails and files by [@CyanVoxel](https://github.com/CyanVoxel) in [#608](https://github.com/TagStudioDev/TagStudio/pull/608)
- feat(parity): migrate json libraries to sqlite by [@CyanVoxel](https://github.com/CyanVoxel) in [#604](https://github.com/TagStudioDev/TagStudio/pull/604)
- fix: clear all setting values when opening a library by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#622](https://github.com/TagStudioDev/TagStudio/pull/622)
- fix: remove/rework windows path tests by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#625](https://github.com/TagStudioDev/TagStudio/pull/625)
- fix: add check to see if library is loaded in filter_items by [@Roc25](https://github.com/Roc25) in [#547](https://github.com/TagStudioDev/TagStudio/pull/547)
- fix: multiple macro errors by [@Computerdores](https://github.com/Computerdores) in [#612](https://github.com/TagStudioDev/TagStudio/pull/612)
- fix: don't allow blank tag alias values in db by [@CyanVoxel](https://github.com/CyanVoxel) in [#628](https://github.com/TagStudioDev/TagStudio/pull/628)
- feat: Reimplement drag drop files on sql migration by [@seakrueger](https://github.com/seakrueger) in [#528](https://github.com/TagStudioDev/TagStudio/pull/528)
- fix: stop sqlite db from being updated while running tests by [@python357-1](https://github.com/python357-1) in [#648](https://github.com/TagStudioDev/TagStudio/pull/648)
- fix: enter/return adds top result tag by [@SkeleyM](https://github.com/SkeleyM) in [#651](https://github.com/TagStudioDev/TagStudio/pull/651)
- fix: show correct unlinked files count by [@SkeleyM](https://github.com/SkeleyM) in [#653](https://github.com/TagStudioDev/TagStudio/pull/653)
- feat: implement parent tag search by [@Computerdores](https://github.com/Computerdores) in [#673](https://github.com/TagStudioDev/TagStudio/pull/673)
- fix: only close add tag menu with no search by [@SkeleyM](https://github.com/SkeleyM) in [#685](https://github.com/TagStudioDev/TagStudio/pull/685)
- fix: drag and drop no longer resets by [@SkeleyM](https://github.com/SkeleyM) in [#710](https://github.com/TagStudioDev/TagStudio/pull/710)
- feat(ui): port "create and add tag" to main branch by [@SkeleyM](https://github.com/SkeleyM) in [#711](https://github.com/TagStudioDev/TagStudio/pull/711)
- fix: don't add default title field, use proper phrasing for adding files by [@CyanVoxel](https://github.com/CyanVoxel) in [#701](https://github.com/TagStudioDev/TagStudio/pull/701)
- fix: preview panel + main window fixes and optimizations by [@CyanVoxel](https://github.com/CyanVoxel) in [#700](https://github.com/TagStudioDev/TagStudio/pull/700)
- fix: sort tag results by [@mashed5894](https://github.com/mashed5894) in [#721](https://github.com/TagStudioDev/TagStudio/pull/721)
- fix: restore opening last library on startup by [@SkeleyM](https://github.com/SkeleyM) in [#729](https://github.com/TagStudioDev/TagStudio/pull/729)
- fix(ui): don't always create tag on enter by [@SkeleyM](https://github.com/SkeleyM) in [#731](https://github.com/TagStudioDev/TagStudio/pull/731)
- fix: use tag aliases in tag search by [@CyanVoxel](https://github.com/CyanVoxel) in [#726](https://github.com/TagStudioDev/TagStudio/pull/726)
- fix: keep initial id order in `get_entries_full()` by [@CyanVoxel](https://github.com/CyanVoxel) in [#736](https://github.com/TagStudioDev/TagStudio/pull/736)
- fix: always catch db mismatch by [@CyanVoxel](https://github.com/CyanVoxel) in [#738](https://github.com/TagStudioDev/TagStudio/pull/738)
- fix: relink unlinked entry to existing entry without sql error by [@mashed5894](https://github.com/mashed5894) in [#730](https://github.com/TagStudioDev/TagStudio/issues/730)
- fix: refactor and fix bugs with missing_files.py by [@CyanVoxel](https://github.com/CyanVoxel) in [#739](https://github.com/TagStudioDev/TagStudio/pull/739)
- fix: dragging files references correct entry IDs [@CyanVoxel](https://github.com/CyanVoxel) in [44ff17c](https://github.com/TagStudioDev/TagStudio/commit/44ff17c0b3f05570e356c112f005dbc14c7cc05d)
- ui: port splash screen from Alpha-v9.4 by [@CyanVoxel](https://github.com/CyanVoxel) in [af760ee](https://github.com/TagStudioDev/TagStudio/commit/af760ee61a523c84bab0fb03a68d7465866d0e05)
- fix: tags created from tag database now add aliases by [@CyanVoxel](https://github.com/CyanVoxel) in [2903dd2](https://github.com/TagStudioDev/TagStudio/commit/2903dd22c45c02498687073d075bb88886de6b62)
- fix: check for tag name parity during JSON migration by [@CyanVoxel](https://github.com/CyanVoxel) in [#748](https://github.com/TagStudioDev/TagStudio/pull/748)
- feat(ui): re-implement tag display names on sql by [@CyanVoxel](https://github.com/CyanVoxel) in [#747](https://github.com/TagStudioDev/TagStudio/pull/747)
- fix(ui): restore Windows accent color on PySide 6.8.0.1 by [@CyanVoxel](https://github.com/CyanVoxel) in [#755](https://github.com/TagStudioDev/TagStudio/pull/755)
- fix(ui): (mostly) fix right-click search option on tags by [@CyanVoxel](https://github.com/CyanVoxel) in [#756](https://github.com/TagStudioDev/TagStudio/pull/756)
- feat: copy/paste fields and tags by [@mashed5894](https://github.com/mashed5894) in [#722](https://github.com/TagStudioDev/TagStudio/pull/722)
- perf: optimize query methods and reduce preview panel updates by [@CyanVoxel](https://github.com/CyanVoxel) in [#794](https://github.com/TagStudioDev/TagStudio/pull/794)
- feat: port file trashing ([#409](https://github.com/TagStudioDev/TagStudio/pull/409)) to v9.5 by [@CyanVoxel](https://github.com/CyanVoxel) in [#792](https://github.com/TagStudioDev/TagStudio/pull/792)
- fix: prevent future library versions from being opened by [@CyanVoxel](https://github.com/CyanVoxel) in [bcf3b2f](https://github.com/TagStudioDev/TagStudio/commit/bcf3b2f96bc8b876ca4b0c1d1882ce14a190f249)
#### UI/UX
- feat(ui): pre-select default tag name in `BuildTagPanel` by [@Cool-Game-Dev](https://github.com/Cool-Game-Dev) in [#592](https://github.com/TagStudioDev/TagStudio/pull/592)
- feat(ui): keyboard navigation for editing tags by [@Computerdores](https://github.com/Computerdores) in [#407](https://github.com/TagStudioDev/TagStudio/pull/407)
- feat(ui): use tag query as default new tag name by [@CyanVoxel](https://github.com/CyanVoxel) in [29c0dfd](https://github.com/TagStudioDev/TagStudio/commit/29c0dfdb2d88e8f473e27c7f1fe7ede6e5bd0feb)
- feat(ui): shortcut to add tags to selected entries; change click behavior of tags to edit by [@CyanVoxel](https://github.com/CyanVoxel) in [#749](https://github.com/TagStudioDev/TagStudio/pull/749)
- fix(ui): use consistent dark mode colors for all systems by [@CyanVoxel](https://github.com/CyanVoxel) in [#752](https://github.com/TagStudioDev/TagStudio/pull/752)
- fix(ui): use camera white balance for raw images by [@CyanVoxel](https://github.com/CyanVoxel) in [6ee5304](https://github.com/TagStudioDev/TagStudio/commit/6ee5304b52f217af0f5df543fcb389649203d6b2)
- Mixed field editing has been limited due to various bugs in both the JSON and SQL implementations. This will be re-implemented in a future release.
- fix(ui): improve tagging ux by [@CyanVoxel](https://github.com/CyanVoxel) in [#633](https://github.com/TagStudioDev/TagStudio/pull/633)
- fix(ui): hide library actions when no library is open by [@CyanVoxel](https://github.com/CyanVoxel) in [#787](https://github.com/TagStudioDev/TagStudio/pull/787)
- refactor(ui): recycle tag list in TagSearchPanel by [@CyanVoxel](https://github.com/CyanVoxel) in [#788](https://github.com/TagStudioDev/TagStudio/pull/788)
- feat(ui): add tag view limit dropdown
- fix(ui): expand usage of esc and enter for modals by [@CyanVoxel](https://github.com/CyanVoxel) in [#793](https://github.com/TagStudioDev/TagStudio/pull/793)
#### Performance
- feat: improve performance of "Delete Missing Entries" by [@Toby222](https://github.com/Toby222) and [@Computerdores](https://github.com/Computerdores) in [#696](https://github.com/TagStudioDev/TagStudio/pull/696)
#### Internal Changes
- refactor: combine open launch args by [@UnusualEgg](https://github.com/UnusualEgg) in [#364](https://github.com/TagStudioDev/TagStudio/pull/364)
- feat: add date_created, date_modified, and date_added columns to entries table by [@CyanVoxel](https://github.com/CyanVoxel) in [#740](https://github.com/TagStudioDev/TagStudio/pull/740)
## [9.5.0 Pre-Release 4] - 2025-02-17
### Added
#### Custom User-Created Tag Colors ([@CyanVoxel](https://github.com/CyanVoxel) in [#801](https://github.com/TagStudioDev/TagStudio/pull/801))
Create your own custom tag colors via the new Tag Color Manager! Tag colors are assigned a namespace (group) and include a name, primary color, and optional secondary color. By default the secondary color is used for the tag text color, but this can also be toggled to apply to the border color as well!
[![Screenshot 2025-02-16 at 17 34 22](https://private-user-images.githubusercontent.com/46939827/413668576-b591f1fe-1c44-4d82-b6e5-d166590aeab1.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg1NzYtYjU5MWYxZmUtMWM0NC00ZDgyLWI2ZTUtZDE2NjU5MGFlYWIxLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTBhYzUwZmExZjRlMWI4YzJjZTZmNDRiMjFiN2ZlZjg4ZjE3MWM4NzBkNmJlZWNjMzg2OWU5YTE2OWVmZTA2YTEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.nEs6bk1euKTEkIqDipNJBrXHbHegb3PHWoW3tKI02_8)](https://private-user-images.githubusercontent.com/46939827/413668576-b591f1fe-1c44-4d82-b6e5-d166590aeab1.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg1NzYtYjU5MWYxZmUtMWM0NC00ZDgyLWI2ZTUtZDE2NjU5MGFlYWIxLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTBhYzUwZmExZjRlMWI4YzJjZTZmNDRiMjFiN2ZlZjg4ZjE3MWM4NzBkNmJlZWNjMzg2OWU5YTE2OWVmZTA2YTEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.nEs6bk1euKTEkIqDipNJBrXHbHegb3PHWoW3tKI02_8)
[![Screenshot 2025-02-16 at 17 32 56](https://private-user-images.githubusercontent.com/46939827/413668612-96e81b08-6993-4a5e-96d0-3b05b50fbe44.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg2MTItOTZlODFiMDgtNjk5My00YTVlLTk2ZDAtM2IwNWI1MGZiZTQ0LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTlhOGU2NjA2ZjRhMjNjZGYxZDE1ZWYzZmVjN2RjM2Q0YzA1NTcwZGE5OGFkMjc2MDIzMTk1YTFlYjY2NTQxNmImWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.VD2trGcVKQVKUpzVog1UhZUM0JRcEHUhwGCiHpZ8zF0)](https://private-user-images.githubusercontent.com/46939827/413668612-96e81b08-6993-4a5e-96d0-3b05b50fbe44.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTM2Njg2MTItOTZlODFiMDgtNjk5My00YTVlLTk2ZDAtM2IwNWI1MGZiZTQ0LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTlhOGU2NjA2ZjRhMjNjZGYxZDE1ZWYzZmVjN2RjM2Q0YzA1NTcwZGE5OGFkMjc2MDIzMTk1YTFlYjY2NTQxNmImWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.VD2trGcVKQVKUpzVog1UhZUM0JRcEHUhwGCiHpZ8zF0)
#### Translations
TagStudio now has official translation support! Head to the new settings panel and select from one of the initial languages included. Note that many languages currently have incomplete translations.
Translation hosting generously provided by [Weblate](https://weblate.org/en/). Check out our [project page](https://hosted.weblate.org/projects/tagstudio/) to help translate TagStudio! Thank you to everyone who's helped contribute to the translations so far!
- translations: add string tokens for en.json by [@Bamowen](https://github.com/Bamowen) in [#507](https://github.com/TagStudioDev/TagStudio/pull/507)
- feat: translations by [@Computerdores](https://github.com/Computerdores) in [#662](https://github.com/TagStudioDev/TagStudio/pull/662)
- feat(ui): add language setting by [@CyanVoxel](https://github.com/CyanVoxel) in [#803](https://github.com/TagStudioDev/TagStudio/pull/803)
Initial Languages:
- Chinese (Traditional) (68%)
- [@brisu](https://github.com/brisu)
- Dutch (35%)
- [@Pheubel](https://github.com/Pheubel)
- Filipino (15%)
- [@searinminecraft](https://github.com/searinminecraft)
- French (89%)
- [@Bamowen](https://github.com/Bamowen), [@alessdangelo](https://github.com/alessdangelo), [@kitsumed](https://github.com/kitsumed), Obscaeris
- German (73%)
- [@Ryussei](https://github.com/Ryussei), [@Computerdores](https://github.com/Computerdores), Aaron M
- Hungarian (89%)
- [@smileyhead](https://github.com/smileyhead)
- Norwegian Bokmål (16%)
- [@comradekingu](https://github.com/comradekingu)
- Polish (76%)
- Anonymous
- Portuguese (Brazil) (22%)
- [@LoboMetalurgico](https://github.com/LoboMetalurgico), [@SpaceFox1](https://github.com/SpaceFox1)
- Russian (22%)
- [@The-Stolas](https://github.com/The-Stolas)
- Spanish (46%)
- [@gallegonovato](https://github.com/gallegonovato), [@Nginearing](https://github.com/Nginearing), [@noceno](https://github.com/noceno)
- Swedish (24%)
- [@adampawelec](https://github.com/adampawelec), [@mashed5894](https://github.com/mashed5894)
- Tamil (22%)
- [@VasigaranAndAngel](https://github.com/VasigaranAndAngel)
- Toki Pona (32%)
- [@goldstargloww](https://github.com/goldstargloww)
- Turkish (22%)
- [@Nyghl](https://github.com/Nyghl)
### Fixed
- feat(about): clickable links to docs/discord/etc in about modal by [@SkeleyM](https://github.com/SkeleyM) in [#799](https://github.com/TagStudioDev/TagStudio/pull/799)
### Internal Changes
This release increases the internal `DB_VERSION` to 8. Libraries created with this version of TagStudio can still be opened in earlier v9.5.0 pre-release versions, however the behavior of custom color borders will not be identical to the behavior in this PR. Otherwise it should still be possible to use any custom colors created in this version in these earlier pre-releases (but not really recommended).
## [9.5.0 Pre-Release 3] - 2025-02-10
### Added
##### [#743](https://github.com/TagStudioDev/TagStudio/pull/743) by [@CyanVoxel](https://github.com/CyanVoxel)
Added "Smartcase" and Globless Path Search
- `path: temp`: Returns all paths that have "temp" **(Case insensitive)** somewhere in the name.
- `path: Temp`: Returns all paths that have "Temp" **(Case sensitive)** somewhere in the name.
Glob Patterns w/ Smartcase
- `path: *temp*`: Returns all paths that have "temp" **(Case insensitive)** somewhere in the name.
- `path: *Temp*`: Returns all paths that have "Temp" **(Case sensitive)** somewhere in the name.
- `path: temp*`: Returns all paths that start with "temp" **(Case insensitive)** somewhere in the name.
- `path: Temp*`: Returns all paths that start with "Temp" **(Case sensitive)** somewhere in the name.
- `path: *temp`: Returns all paths that end with "temp" **(Case insensitive)** somewhere in the name.
- `path: *TEmP`: Returns all paths that end with "TEmP" **(Case sensitive)** somewhere in the name.
##### [#788](https://github.com/TagStudioDev/TagStudio/pull/788) by [@CyanVoxel](https://github.com/CyanVoxel)
- Added a "View Limit" dropdown to tag search boxes to limit the number of on-screen tags. Previously this limit was hardcoded to 100, but now options range from 25 to unlimited.
[![](https://private-user-images.githubusercontent.com/46939827/411701461-7f7da065-888d-4fe5-a4e7-f99447bcce98.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTE3MDE0NjEtN2Y3ZGEwNjUtODg4ZC00ZmU1LWE0ZTctZjk5NDQ3YmNjZTk4LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWVlZjVhZjYyNWQwY2FmMjhmMWI1MzI5ZDdjYWMxMmM0N2M0Nzc4MmY1YjE0NWY4MjVhZmIyMDI1NzQzY2M0YmQmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.a3xUaH5r3HsDgOb6-lo3T-xSRRSy7dDOrln5i62KFP8)](https://private-user-images.githubusercontent.com/46939827/411701461-7f7da065-888d-4fe5-a4e7-f99447bcce98.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTQ3MTYsIm5iZiI6MTc0NjY1NDQxNiwicGF0aCI6Ii80NjkzOTgyNy80MTE3MDE0NjEtN2Y3ZGEwNjUtODg4ZC00ZmU1LWE0ZTctZjk5NDQ3YmNjZTk4LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNDY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWVlZjVhZjYyNWQwY2FmMjhmMWI1MzI5ZDdjYWMxMmM0N2M0Nzc4MmY1YjE0NWY4MjVhZmIyMDI1NzQzY2M0YmQmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.a3xUaH5r3HsDgOb6-lo3T-xSRRSy7dDOrln5i62KFP8)
### Changed
- fix(ui): expand usage of esc and enter for modals by [@CyanVoxel](https://github.com/CyanVoxel) in [#793](https://github.com/TagStudioDev/TagStudio/pull/793)
- perf: optimize query methods and reduce preview panel updates by [@CyanVoxel](https://github.com/CyanVoxel) in [#794](https://github.com/TagStudioDev/TagStudio/pull/794)
##### [#788](https://github.com/TagStudioDev/TagStudio/pull/788) by [@CyanVoxel](https://github.com/CyanVoxel)
- Improved performance of tag search boxes, including the tag manager
### Fixed
- fix(ui): hide library actions when no library is open by [@CyanVoxel](https://github.com/CyanVoxel) in [#787](https://github.com/TagStudioDev/TagStudio/pull/787)
- feat: port file trashing ([#409](https://github.com/TagStudioDev/TagStudio/pull/409)) to v9.5 by [@CyanVoxel](https://github.com/CyanVoxel) in [#792](https://github.com/TagStudioDev/TagStudio/pull/792)
### Docs
- Added references to alternative POSIX shells, as well as pyenv to CONTRIBUTING.md by [@ChloeZamorano](https://github.com/ChloeZamorano) in [#791](https://github.com/TagStudioDev/TagStudio/pull/791)
## [9.5.0 Pre-Release 2] - 2025-02-03
### Added
##### [#784](https://github.com/TagStudioDev/TagStudio/pull/784) by [@CyanVoxel](https://github.com/CyanVoxel)
- Add Ctrl+M shortcut to open the "Tag Manager"
### Fixed
- fix: don't wrap field names too early by [@CyanVoxel](https://github.com/CyanVoxel) in [2215403](https://github.com/TagStudioDev/TagStudio/commit/2215403201e3b416a43ead0a322688180af6d71b) and [90a826d](https://github.com/TagStudioDev/TagStudio/commit/90a826d12804b3386a0b9003abb20f23f88ab3be)
- fix: save all tag attributes from "Create & Add" modal by [@SkeleyM](https://github.com/SkeleyM) in [#762](https://github.com/TagStudioDev/TagStudio/pull/762)
- fix: allow tag names with colons in search by [@SkeleyM](https://github.com/SkeleyM) in [#765](https://github.com/TagStudioDev/TagStudio/pull/765)
- fix: catch `ParsingError` by [@CyanVoxel](https://github.com/CyanVoxel) in [#779](https://github.com/TagStudioDev/TagStudio/pull/779)
- fix: patch incorrect description type & invalid disambiguation_id refs by [@CyanVoxel](https://github.com/CyanVoxel) in [#782](https://github.com/TagStudioDev/TagStudio/pull/782)
##### [#784](https://github.com/TagStudioDev/TagStudio/pull/784) by [@CyanVoxel](https://github.com/CyanVoxel)
- Reset tag search box and focus each time a tag search panel is opened
- Include tag parents in tag search results (v9.4 parity)
- Lowercase tag names now get properly sorted with uppercase ones
- Don't include tag display names in "closeness" factor when searching
- Escape "&" characters inside tag names so Qt doesn't treat them as mnemonics
- Set minimum tag width
- Fix "Add Tags" panel missing its window title when accessing from the keyboard shortcut
### Changed
##### [#784](https://github.com/TagStudioDev/TagStudio/pull/784) by [@CyanVoxel](https://github.com/CyanVoxel)
- The "use for disambiguation" button has been moved to the right-hand side of parent tags in order to prevent accidental clicks involving the left-hand "remove tag" button
- Add "Create & Add" button to the bottom of all non-whitespace searches, even if they return some tags
- The awkward "+" button next to tags in the "Add Tags" panel has been removed in favor of clicking on tags themselves
- Improved visual feedback for highlighting, keyboard focusing, and clicking tags
- The clickable area of the "-" button on tags has been increased and has visual feedback when you hover and click it
- You can now tab into the tag search list and add tags with a spacebar press (previously possible but very janky)
- In tag search panels, pressing the Esc key will return your focus to the search bar and highlight your previous query. If the search box is already highlighted, pressing Esc will close the modal
- In modals such as the "Add Tag" and "Edit Tag" panels, pressing Esc will cancel the operation and close the modal
### Internal Changes
- refactor: wrap migration_iterator lambda in a try/except block by [@CyanVoxel](https://github.com/CyanVoxel) in [#773](https://github.com/TagStudioDev/TagStudio/pull/773)
### Docs
- docs: update field and library pages by [@CyanVoxel](https://github.com/CyanVoxel) in [f5ff4d7](https://github.com/TagStudioDev/TagStudio/commit/f5ff4d78c1ad53134e9c64698886aee68c0f1dc1)
- docs: add information about "tag manager" by [@CyanVoxel](https://github.com/CyanVoxel) in [9bdbafa](https://github.com/TagStudioDev/TagStudio/commit/9bdbafa40c4274922f6533b5b5fcee9a4fe43030)
- docs: add note about glob searching in the readme by [@CyanVoxel](https://github.com/CyanVoxel) in [6e402ac](https://github.com/TagStudioDev/TagStudio/commit/6e402ac34d2d60e71fbd36ad234fe3914d5eb8e0)
- docs: add library_search page by [@CyanVoxel](https://github.com/CyanVoxel) in [5be7dfc](https://github.com/TagStudioDev/TagStudio/commit/5be7dfc314b21042c18b2f08893f2b452d12394a)
- docs: docs: add more links to index.md by [@CyanVoxel](https://github.com/CyanVoxel) in [d795889](https://github.com/TagStudioDev/TagStudio/commit/d7958892b7762586837204d686a6a2a993e3c26e)
- docs: fix typo for "category" in usage.md by [@pinheadtf2](https://github.com/pinheadtf2) in [#760](https://github.com/TagStudioDev/TagStudio/pull/760)
- fix(docs): fix screenshot sometimes not rendering by [@SkeleyM](https://github.com/SkeleyM) in [#775](https://github.com/TagStudioDev/TagStudio/pull/775)
## [9.5.0 Pre-Release 1] - 2025-01-31
### Added
#### Overhauled Search Engine
##### Boolean Operators
- feat: implement query language by [@Computerdores](https://github.com/Computerdores) in [#606](https://github.com/TagStudioDev/TagStudio/pull/606)
- feat: optimize AND queries by [@Computerdores](https://github.com/Computerdores) in [#679](https://github.com/TagStudioDev/TagStudio/pull/679)
##### Filetype, Mediatype, and Glob Path Searches
- fix: remove wildcard requirement for tags by [@Tyrannicodin](https://github.com/Tyrannicodin) in [#481](https://github.com/TagStudioDev/TagStudio/pull/481)
- feat: add filetype and mediatype searches by [@python357-1](https://github.com/python357-1) in [#575](https://github.com/TagStudioDev/TagStudio/pull/575)
- feat: make path search use globs by [@python357-1](https://github.com/python357-1) in [#582](https://github.com/TagStudioDev/TagStudio/pull/582)
- feat: implement search equivalence of "jpg" and "jpeg" filetypes by [@Computerdores](https://github.com/Computerdores) in [#649](https://github.com/TagStudioDev/TagStudio/pull/649)
##### Sortable Results
- feat: sort by "date added" in library by [@Computerdores](https://github.com/Computerdores) in [#674](https://github.com/TagStudioDev/TagStudio/pull/674)
##### Autocomplete
- feat: add autocomplete for search engine by [@python357-1](https://github.com/python357-1) in [#586](https://github.com/TagStudioDev/TagStudio/pull/586)
#### Replaced "Tag Fields" with Tag Categories
Instead of tags needing to be added to a tag field type such as "Meta Tags", "Content Tags", or just the "Tags" field, tags are now added directly to file entries with no intermediary step. While tag field types offered a way to further organize tags, it was cumbersome, inflexible, and simply not fully fleshed out. Tag Categories offer all of the previous (intentional) functionality while greatly increasing the ease of use and customization.
- feat!: tag categories by [@CyanVoxel](https://github.com/CyanVoxel) in [#655](https://github.com/TagStudioDev/TagStudio/pull/655)
[![Screenshot 2025-01-04 at 04 23 43](https://private-user-images.githubusercontent.com/46939827/400138597-0b92eca5-db8f-4e3e-954b-1b4f3795f073.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTUwODcsIm5iZiI6MTc0NjY1NDc4NywicGF0aCI6Ii80NjkzOTgyNy80MDAxMzg1OTctMGI5MmVjYTUtZGI4Zi00ZTNlLTk1NGItMWI0ZjM3OTVmMDczLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNTMwN1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTM1M2EwNGFjYmJiM2QwZjg2YzNmNTVjMGYwZDJkZGJkZTg5NjZjNDFhNTYyNDE0OGNlOWFhNzRkMzE3MjBkNzEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.B5NRZmHygdHlMy2ZnZtHjfOs83jjEliwfxoe3eMBnEQ)](https://private-user-images.githubusercontent.com/46939827/400138597-0b92eca5-db8f-4e3e-954b-1b4f3795f073.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTUwODcsIm5iZiI6MTc0NjY1NDc4NywicGF0aCI6Ii80NjkzOTgyNy80MDAxMzg1OTctMGI5MmVjYTUtZGI4Zi00ZTNlLTk1NGItMWI0ZjM3OTVmMDczLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNTMwN1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTM1M2EwNGFjYmJiM2QwZjg2YzNmNTVjMGYwZDJkZGJkZTg5NjZjNDFhNTYyNDE0OGNlOWFhNzRkMzE3MjBkNzEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.B5NRZmHygdHlMy2ZnZtHjfOs83jjEliwfxoe3eMBnEQ)
#### Thumbnails and File Previews
##### New Thumbnail Support
- feat: add svg thumbnail support (port [#442](https://github.com/TagStudioDev/TagStudio/pull/442)) by [@Tyrannicodin](https://github.com/Tyrannicodin) and [@CyanVoxel](https://github.com/CyanVoxel) in [#540](https://github.com/TagStudioDev/TagStudio/pull/540)
- feat: add pdf thumbnail support (port [#378](https://github.com/TagStudioDev/TagStudio/pull/378)) by [@Heiholf](https://github.com/Heiholf) and [@CyanVoxel](https://github.com/CyanVoxel) in [#543](https://github.com/TagStudioDev/TagStudio/pull/543)
- feat: add ePub thumbnail support (port [#387](https://github.com/TagStudioDev/TagStudio/pull/387)) by [@Heiholf](https://github.com/Heiholf) and [@CyanVoxel](https://github.com/CyanVoxel) in [#539](https://github.com/TagStudioDev/TagStudio/pull/539)
- feat: add OpenDocument thumbnail support (port [#366](https://github.com/TagStudioDev/TagStudio/pull/366)) by [@Joshua-Beatty](https://github.com/Joshua-Beatty) and [@CyanVoxel](https://github.com/CyanVoxel) in [#545](https://github.com/TagStudioDev/TagStudio/pull/545)
- feat: add JXL thumbnail and animated APNG + WEBP support (port [#344](https://github.com/TagStudioDev/TagStudio/pull/344) and partially port [#357](https://github.com/TagStudioDev/TagStudio/pull/357)) by [@BPplays](https://github.com/BPplays) and [@CyanVoxel](https://github.com/CyanVoxel) in [#549](https://github.com/TagStudioDev/TagStudio/pull/549)
- fix: catch ImportError for pillow_jxl module by [@CyanVoxel](https://github.com/CyanVoxel) in [a2f9685](https://github.com/TagStudioDev/TagStudio/commit/a2f9685bc0d744ea6f5334c6d2926aad3f6d375a)
##### Audio Playback
- feat: audio playback by [@csponge](https://github.com/csponge) in [#576](https://github.com/TagStudioDev/TagStudio/pull/576)
- feat(ui): add audio volume slider by [@SkeleyM](https://github.com/SkeleyM) in [#691](https://github.com/TagStudioDev/TagStudio/pull/691)
##### Thumbnail Caching
- feat(ui): add thumbnail caching by [@CyanVoxel](https://github.com/CyanVoxel) in [#694](https://github.com/TagStudioDev/TagStudio/pull/694)
#### Tags
##### Delete Tags _(Finally!)_
- feat: remove and create tags from tag database panel by [@DandyDev01](https://github.com/DandyDev01) in [#569](https://github.com/TagStudioDev/TagStudio/pull/569)
##### New Tag Colors + UI
- feat: expanded tag color system by [@CyanVoxel](https://github.com/CyanVoxel) in [#709](https://github.com/TagStudioDev/TagStudio/pull/709)
- fix(ui): use correct pink tag color by [@CyanVoxel](https://github.com/CyanVoxel) in [431efe4](https://github.com/TagStudioDev/TagStudio/commit/431efe4fe93213141c763e59ca9887215766fd42)
- fix(ui): use consistent tag outline colors by [@CyanVoxel](https://github.com/CyanVoxel) in [020a73d](https://github.com/TagStudioDev/TagStudio/commit/020a73d095c74283d6c80426d3c3db8874409952)
[![Screenshot 2025-01-04 at 04 23 43](https://private-user-images.githubusercontent.com/46939827/408753168-c8f82d89-ad7e-4be6-830e-b91cdc58e4c6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTUwODcsIm5iZiI6MTc0NjY1NDc4NywicGF0aCI6Ii80NjkzOTgyNy80MDg3NTMxNjgtYzhmODJkODktYWQ3ZS00YmU2LTgzMGUtYjkxY2RjNThlNGM2LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNTMwN1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWI3ZDk2MDg5ODVjYzA2ZGU2Njc1ODE5M2U4OWU4ZGMwY2MxNzUzM2M2YmM2ZmRiMTdlOTkyNGM3MjlhMWNiOWUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.0RYUWgVW8VFvu2unzdWHtDCE4USYM77OcMvWeZkd8Hs)](https://private-user-images.githubusercontent.com/46939827/408753168-c8f82d89-ad7e-4be6-830e-b91cdc58e4c6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDY2NTUwODcsIm5iZiI6MTc0NjY1NDc4NywicGF0aCI6Ii80NjkzOTgyNy80MDg3NTMxNjgtYzhmODJkODktYWQ3ZS00YmU2LTgzMGUtYjkxY2RjNThlNGM2LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA1MDclMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNTA3VDIxNTMwN1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWI3ZDk2MDg5ODVjYzA2ZGU2Njc1ODE5M2U4OWU4ZGMwY2MxNzUzM2M2YmM2ZmRiMTdlOTkyNGM3MjlhMWNiOWUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.0RYUWgVW8VFvu2unzdWHtDCE4USYM77OcMvWeZkd8Hs)
##### New Tag Alias UI
- fix: preview panel aliases not staying up to date with database by [@DandyDev01](https://github.com/DandyDev01) in [#641](https://github.com/TagStudioDev/TagStudio/pull/641)
- fix: subtags/parent tags & aliases update the UI for building a tag by [@DandyDev01](https://github.com/DandyDev01) in [#534](https://github.com/TagStudioDev/TagStudio/pull/534)
#### Miscellaneous
- feat: about section by [@mashed5894](https://github.com/mashed5894) in [#712](https://github.com/TagStudioDev/TagStudio/pull/712)
- feat(ui): add configurable splash screens by [@CyanVoxel](https://github.com/CyanVoxel) in [#703](https://github.com/TagStudioDev/TagStudio/pull/703)
- feat(ui): show filenames in thumbnail grid by [@CyanVoxel](https://github.com/CyanVoxel) in [#633](https://github.com/TagStudioDev/TagStudio/pull/633)
### Fixed
- fix(ui): display all tags in panel during empty search by [@samuellieberman](https://github.com/samuellieberman) in [#328](https://github.com/TagStudioDev/TagStudio/pull/328)
- fix: avoid `KeyError` in `add_folders_to_tree()` (fix [#346](https://github.com/TagStudioDev/TagStudio/issues/346)) by [@CyanVoxel](https://github.com/CyanVoxel) in [#347](https://github.com/TagStudioDev/TagStudio/pull/347)
- fix: error on closing library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#484](https://github.com/TagStudioDev/TagStudio/pull/484)
- fix: resolution info [#550](https://github.com/TagStudioDev/TagStudio/issues/550) by [@Roc25](https://github.com/Roc25) in [#551](https://github.com/TagStudioDev/TagStudio/pull/551)
- fix: remove queued thumnail jobs when closing library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#583](https://github.com/TagStudioDev/TagStudio/pull/583)
- fix: use absolute ffprobe path on macos (Fix [#511](https://github.com/TagStudioDev/TagStudio/issues/511)) by [@CyanVoxel](https://github.com/CyanVoxel) in [#629](https://github.com/TagStudioDev/TagStudio/pull/629)
- fix(ui): prevent duplicate parent tags in UI by [@SkeleyM](https://github.com/SkeleyM) in [#665](https://github.com/TagStudioDev/TagStudio/pull/665)
- fix: fix -o flag not working if path has whitespace around it by [@python357-1](https://github.com/python357-1) in [#670](https://github.com/TagStudioDev/TagStudio/pull/670)
- fix: better file opening compatibility with non-ascii filenames by [@SkeleyM](https://github.com/SkeleyM) in [#667](https://github.com/TagStudioDev/TagStudio/pull/667)
- fix: restore environment before launching external programs by [@mashed5894](https://github.com/mashed5894) in [#707](https://github.com/TagStudioDev/TagStudio/pull/707)
- fix: have pydub use known ffmpeg + ffprobe locations by [@CyanVoxel](https://github.com/CyanVoxel) in [#724](https://github.com/TagStudioDev/TagStudio/pull/724)
- fix: add ".DS_Store" to `GLOBAL_IGNORE_SET` by [@CyanVoxel](https://github.com/CyanVoxel) in [b72a2f2](https://github.com/TagStudioDev/TagStudio/commit/b72a2f233141db4db6aa6be8796b626ebd3f0756)
- fix: don't add "._" files to libraries by [@CyanVoxel](https://github.com/CyanVoxel) in [eb1f634](https://github.com/TagStudioDev/TagStudio/commit/eb1f634d386cd8a5ecee1e6ff6a0b7d8811550fa)
### Changed
#### SQLite Save File Format
This was the main focus of this update, and where the majority of development time and resources have been spent since v9.4. These changes include everything that was done to migrate from the JSON format to SQLite starting from the initial SQLite PR, while re-implementing every feature from v9.4 as the initial SQLite PR was based on v9.3.x at the time.
- refactor!: use SQLite and SQLAlchemy for database backend by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#332](https://github.com/TagStudioDev/TagStudio/pull/332)
- feat: make search results more ergonomic by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#498](https://github.com/TagStudioDev/TagStudio/pull/498)
- feat: store `Entry` suffix separately by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#503](https://github.com/TagStudioDev/TagStudio/pull/503)
- feat: port thumbnail ([#390](https://github.com/TagStudioDev/TagStudio/pull/390)) and related features to v9.5 by [@CyanVoxel](https://github.com/CyanVoxel) in [#522](https://github.com/TagStudioDev/TagStudio/pull/522)
- fix: don't check db version with new library by [@yedpodtrzitko](https://github.com/yedpodtrzitko) in [#536](https://github.com/TagStudioDev/TagStudio/pull/536)
- fix(ui): update ui when removing fields by [@DandyDev01](https://github.com/DandyDev01) in [#560](https://github.com/TagStudioDev/TagStudio/pull/560)
- feat(parity): backend for aliases and parent tags by [@DandyDev01](https://github.com/DandyDev01) in [#596](https://github.com/TagStudioDev/TagStudio/pull/596)
- fix: "open in explorer" opens correct folder by [@KirilBourakov](https://github.com/KirilBourakov) in [#603](https://github.com/TagStudioDev/TagStudio/pull/603)
- fix: ui/ux parity fixes for thumbnails and files by [@CyanVoxel](https://github.com/CyanVoxel) in [#608](https://github.com/TagStudioDev/TagStudio/pull/608)
- feat(parity): migrate json libraries to sqlite by [@CyanVoxel](https://github.com/CyanVoxel) in [#604](https://github.com/TagStudioDev/TagStudio/pull/604)
- fix: clear all setting values when opening a library by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#622](https://github.com/TagStudioDev/TagStudio/pull/622)
- fix: remove/rework windows path tests by [@VasigaranAndAngel](https://github.com/VasigaranAndAngel) in [#625](https://github.com/TagStudioDev/TagStudio/pull/625)
- fix: add check to see if library is loaded in filter_items by [@Roc25](https://github.com/Roc25) in [#547](https://github.com/TagStudioDev/TagStudio/pull/547)
- fix: multiple macro errors by [@Computerdores](https://github.com/Computerdores) in [#612](https://github.com/TagStudioDev/TagStudio/pull/612)
- fix: don't allow blank tag alias values in db by [@CyanVoxel](https://github.com/CyanVoxel) in [#628](https://github.com/TagStudioDev/TagStudio/pull/628)
- feat: Reimplement drag drop files on sql migration by [@seakrueger](https://github.com/seakrueger) in [#528](https://github.com/TagStudioDev/TagStudio/pull/528)
- fix: stop sqlite db from being updated while running tests by [@python357-1](https://github.com/python357-1) in [#648](https://github.com/TagStudioDev/TagStudio/pull/648)
- fix: enter/return adds top result tag by [@SkeleyM](https://github.com/SkeleyM) in [#651](https://github.com/TagStudioDev/TagStudio/pull/651)
- fix: show correct unlinked files count by [@SkeleyM](https://github.com/SkeleyM) in [#653](https://github.com/TagStudioDev/TagStudio/pull/653)
- feat: implement parent tag search by [@Computerdores](https://github.com/Computerdores) in [#673](https://github.com/TagStudioDev/TagStudio/pull/673)
- fix: only close add tag menu with no search by [@SkeleyM](https://github.com/SkeleyM) in [#685](https://github.com/TagStudioDev/TagStudio/pull/685)
- fix: drag and drop no longer resets by [@SkeleyM](https://github.com/SkeleyM) in [#710](https://github.com/TagStudioDev/TagStudio/pull/710)
- feat(ui): port "create and add tag" to main branch by [@SkeleyM](https://github.com/SkeleyM) in [#711](https://github.com/TagStudioDev/TagStudio/pull/711)
- fix: don't add default title field, use proper phrasing for adding files by [@CyanVoxel](https://github.com/CyanVoxel) in [#701](https://github.com/TagStudioDev/TagStudio/pull/701)
- fix: preview panel + main window fixes and optimizations by [@CyanVoxel](https://github.com/CyanVoxel) in [#700](https://github.com/TagStudioDev/TagStudio/pull/700)
- fix: sort tag results by [@mashed5894](https://github.com/mashed5894) in [#721](https://github.com/TagStudioDev/TagStudio/pull/721)
- fix: restore opening last library on startup by [@SkeleyM](https://github.com/SkeleyM) in [#729](https://github.com/TagStudioDev/TagStudio/pull/729)
- fix(ui): don't always create tag on enter by [@SkeleyM](https://github.com/SkeleyM) in [#731](https://github.com/TagStudioDev/TagStudio/pull/731)
- fix: use tag aliases in tag search by [@CyanVoxel](https://github.com/CyanVoxel) in [#726](https://github.com/TagStudioDev/TagStudio/pull/726)
- fix: keep initial id order in `get_entries_full()` by [@CyanVoxel](https://github.com/CyanVoxel) in [#736](https://github.com/TagStudioDev/TagStudio/pull/736)
- fix: always catch db mismatch by [@CyanVoxel](https://github.com/CyanVoxel) in [#738](https://github.com/TagStudioDev/TagStudio/pull/738)
- fix: relink unlinked entry to existing entry without sql error by [@mashed5894](https://github.com/mashed5894) in [#730](https://github.com/TagStudioDev/TagStudio/issues/730)
- fix: refactor and fix bugs with missing_files.py by [@CyanVoxel](https://github.com/CyanVoxel) in [#739](https://github.com/TagStudioDev/TagStudio/pull/739)
- fix: dragging files references correct entry IDs [@CyanVoxel](https://github.com/CyanVoxel) in [44ff17c](https://github.com/TagStudioDev/TagStudio/commit/44ff17c0b3f05570e356c112f005dbc14c7cc05d)
- ui: port splash screen from Alpha-v9.4 by [@CyanVoxel](https://github.com/CyanVoxel) in [af760ee](https://github.com/TagStudioDev/TagStudio/commit/af760ee61a523c84bab0fb03a68d7465866d0e05)
- fix: tags created from tag database now add aliases by [@CyanVoxel](https://github.com/CyanVoxel) in [2903dd2](https://github.com/TagStudioDev/TagStudio/commit/2903dd22c45c02498687073d075bb88886de6b62)
- fix: check for tag name parity during JSON migration by [@CyanVoxel](https://github.com/CyanVoxel) in [#748](https://github.com/TagStudioDev/TagStudio/pull/748)
- feat(ui): re-implement tag display names on sql by [@CyanVoxel](https://github.com/CyanVoxel) in [#747](https://github.com/TagStudioDev/TagStudio/pull/747)
- fix(ui): restore Windows accent color on PySide 6.8.0.1 by [@CyanVoxel](https://github.com/CyanVoxel) in [#755](https://github.com/TagStudioDev/TagStudio/pull/755)
- fix(ui): (mostly) fix right-click search option on tags by [@CyanVoxel](https://github.com/CyanVoxel) in [#756](https://github.com/TagStudioDev/TagStudio/pull/756)
- feat: copy/paste fields and tags by [@mashed5894](https://github.com/mashed5894) in [#722](https://github.com/TagStudioDev/TagStudio/pull/722)
#### UI/UX
- feat(ui): pre-select default tag name in `BuildTagPanel` by [@Cool-Game-Dev](https://github.com/Cool-Game-Dev) in [#592](https://github.com/TagStudioDev/TagStudio/pull/592)
- feat(ui): keyboard navigation for editing tags by [@Computerdores](https://github.com/Computerdores) in [#407](https://github.com/TagStudioDev/TagStudio/pull/407)
- feat(ui): use tag query as default new tag name by [@CyanVoxel](https://github.com/CyanVoxel) in [29c0dfd](https://github.com/TagStudioDev/TagStudio/commit/29c0dfdb2d88e8f473e27c7f1fe7ede6e5bd0feb)
- feat(ui): shortcut to add tags to selected entries; change click behavior of tags to edit by [@CyanVoxel](https://github.com/CyanVoxel) in [#749](https://github.com/TagStudioDev/TagStudio/pull/749)
- fix(ui): use consistent dark mode colors for all systems by [@CyanVoxel](https://github.com/CyanVoxel) in [#752](https://github.com/TagStudioDev/TagStudio/pull/752)
- fix(ui): use camera white balance for raw images by [@CyanVoxel](https://github.com/CyanVoxel) in [6ee5304](https://github.com/TagStudioDev/TagStudio/commit/6ee5304b52f217af0f5df543fcb389649203d6b2)
- Mixed field editing has been limited due to various bugs in both the JSON and SQL implementations. This will be re-implemented in a future release.
#### Performance
- feat: improve performance of "Delete Missing Entries" by [@Toby222](https://github.com/Toby222) and [@Computerdores](https://github.com/Computerdores) in [#696](https://github.com/TagStudioDev/TagStudio/pull/696)
#### Internal Changes
- refactor: combine open launch args by [@UnusualEgg](https://github.com/UnusualEgg) in [#364](https://github.com/TagStudioDev/TagStudio/pull/364)
- feat: add date_created, date_modified, and date_added columns to entries table by [@CyanVoxel](https://github.com/CyanVoxel) in [#740](https://github.com/TagStudioDev/TagStudio/pull/740)
## [9.4.2] - 2024-12-01
### Added/Fixed
- Create auto-backup of library for use in save failures (Fix [#343](https://github.com/TagStudioDev/TagStudio/issues/343)) by [@CyanVoxel](https://github.com/CyanVoxel) in [#554](https://github.com/TagStudioDev/TagStudio/pull/554)
## [9.4.1] - 2024-09-13
### Added
- Warn user if FFmpeg is not installed
- Support for `.raf` and `.orf` raw image thumbnails and previews
### Fixed
- Use `birthtime` for file creation time on Mac & Windows
- Use audio icon fallback when FFmpeg is not detected
- Retain search query upon directory refresh
### Changed
- Significantly improve file re-scanning performance
## [9.4.0] - 2024-09-03
### Added
- Copy and paste fields
- Add multiple fields at once
- Drag and drop files in/out of the program
- Files can be shared by dragging them from the thumbnail grid to other programs
- Files can be added to library folder by dragging them into the program
- Manage Python virtual environment in Nix flake
- Ability to create tag when adding tags
- Blender preview thumbnail support
- File deletion/trashing
- Added right-click option on thumbnails and preview panel to delete files
- Added Edit Menu option for deleting files
- Added <kbd>Delete</kbd> key shortcut for deleting files
- Font preview thumbnail support
- Short "Aa" previews for thumbnails
- Full alphabet preview for the preview pane
- Sort tags by alphabetical/color
- File explorer action follows OS naming
- Preview Source Engine files
- Expanded thumbnail and preview features
- Add album cover art thumbnails
- Add audio waveform thumbnails for audio files without embedded cover art
- Add new default file thumbnails, both for generic and specific file types
- Change the unlinked file icon to better convey its meaning
- Add dropdown for different thumbnail sizes
- Show File Creation and Modified dates; Restyle file path label
### Fixed
- Backslashes in f-string on file dupe widget
- Tags not shown when none searched
- Avoid error from eagerly grabbing data values
- Correct behavior for tag search options
- Load Gallery-DL sidecar files correctly
- Correct duplicate file matching
- GPU hardware acceleration in Nix flake
- Suppress command prompt windows for FFmpeg in builds
### Internal Changes
- Move type constants to media classes
- Combine open launch arguments
- Revamp Nix flake with devenv/direnv in cb4798b
- Remove impurity of Nix flake when used with direnv in bc38e56
## [9.3.2] - 2024-07-18
### Fixed
- Fix signal log warning
- Fix "Folders to Tags" feature
- Fix search ignoring case of extension list
### Internal Changes
- Add tests into CI by
- Create testing library files ad-hoc
- Refactoring: centralize field IDs
- Update to pyside6 version 6.7.1
## [9.3.1] - 2024-06-13
### Fixed
- Separately pin QT nixpkg version
- Bugfix for #252, don't attempt to read video file if invalid or 0 frames long
- Toggle Mouse Event Transparency on ItemThumbs
- Refactor `video_player.py`
## [9.3.0] - 2024-06-08
### Added
- Added playback previews for video files
- Added Boolean "and/or" search mode selection
- Added ability to scan and fix duplicate entries (not to be confused with duplicate files) from the "Fix Unlinked Entries" menu
- Added “Select All” (<kbd>Ctrl</kbd>+<kbd>A</kbd> / <kbd>⌘ Command</kbd>+<kbd>A</kbd>) hotkey for the library grid view
- Added "Clear Selection" hotkey (<kbd>Esc</kbd>) for the library grid view
- Added the ability to invert the file extension inclusion list into an exclusion list
- Added default landing page when no library is open
### Fixed
- TagStudio will no longer attempt to or allow you to reopen a library from a missing location
- Fixed `PermissionError` when attempting to access files with a higher permission level upon scanning the library directory
- Fixed RAW image previews sometimes not loadingand
- Fixed most non-UTF-8 encoded text files from not being able to be previewed
- Fixed "Refresh Directories"/"Fix Unlinked Entries" creating duplicate entries
- Other miscellaneous fixes
### Changed
- Renamed "Subtags" to "Parent Tags" to help better describe their function
- Increased number of tags shown by default in the "Add Tag" modal from 29 to 100
- Documentation is now split into individual linked files and updated to include future features
- Replaced use of `os.path` with `pathlib`
- `.cr2` files are now included in the list of RAW image file types
- Minimum supported macOS version raised to 12.0
## [9.2.1] - 2024-05-23
### Added
- Basic thumbnail/preview support for RAW images (currently `.raw`, `.dng`, `.rw2`, `.nef`, `.arw`, `.crw`, `.cr3`)
- NOTE: These previews are currently slow to load given the nature of rendering them. In the future once thumbnail caching is added, this process should only happen once.
- Thumbnail/preview support for HEIF images
### Fixed
- Fixed sidebar not expanding horizontally
- Fixed "Recent Library" list not updating when creating a new library
- Fixed palletized images not loading with alpha channels
- Low resolution images (such as pixel art) now render with crisp edges in thumbnails and previews
- Fixed visual bug where the edit icon would show for incorrect fields
## [9.2.0] - 2024-05-14
### Added
@@ -847,7 +48,6 @@ This was the main focus of this update, and where the majority of development ti
- New application icons
### Known Issues
- Using and editing multiple entry fields of the same type may result in incorrect field(s) being updated
- Adding Favorite or Archived tags via the thumbnail badges may apply the tag(s) to incorrect fields
- Searching for tag names with spaces does not currently function as intended

View File

@@ -43,13 +43,13 @@ If you know what you're doing and have developed for Python projects in the past
4. If using a virtual environment instead of a dependency manager, install an editable version of the program and development dependencies with the following PIP command:
```
pip install -e ".[dev]"
pip install -e .[dev]
```
Otherwise, modify the command above for use with your dependency manager of choice. For example if using uv, you may use this:
```
uv pip install -e ".[dev]"
uv pip install -e .[dev]
```
## Workflow Checks
@@ -93,7 +93,19 @@ Mypy is also available as a VS Code [extension](https://marketplace.visualstudio
- Run all tests by running `pytest tests/` in the repository root.
## Code Style
See the [Style Guide](/STYLE.md)
Most of the style guidelines can be checked, fixed, and enforced via Ruff. Older code may not be adhering to all of these guidelines, in which case _"do as I say, not as I do"..._
- Do your best to write clear, concise, and modular code.
- Keep a maximum column with of no more than **100** characters.
- Code comments should be used to help describe sections of code that can't speak for themselves.
- Use [Google style](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings) docstrings for any classes and functions you add.
- If you're modifying an existing function that does _not_ have docstrings, you don't _have_ to add docstrings to it... but it would be pretty cool if you did ;)
- Imports should be ordered alphabetically.
- Lists of values should be ordered using their [natural sort order](https://en.wikipedia.org/wiki/Natural_sort_order).
- Some files have their methods ordered alphabetically as well (i.e. [`thumb_renderer`](https://github.com/TagStudioDev/TagStudio/blob/main/tagstudio/src/qt/widgets/thumb_renderer.py)). If you're working in a file and notice this, please try and keep to the pattern.
- When writing text for window titles or form titles, use "[Title Case](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case)" capitalization. Your IDE may have a command to format this for you automatically, although some may incorrectly capitalize short prepositions. In a pinch you can use a website such as [capitalizemytitle.com](https://capitalizemytitle.com/) to check.
- If it wasn't mentioned above, then stick to [**PEP-8**](https://peps.python.org/pep-0008/)!
### Modules & Implementations

View File

@@ -1,84 +0,0 @@
# Code Style
Most of the style guidelines can be checked, fixed, and enforced via Ruff. Older code may not be adhering to all of these guidelines, in which case _"do as I say, not as I do"..._
- Do your best to write clear, concise, and modular code.
- This should include making methods private by default (e.g. `__method()`)
- Methods should only be protected (e.g. `_method()`) or public (e.g. `method()`) when needed and warranted
- Keep a maximum column width of no more than **100** characters.
- Code comments should be used to help describe sections of code that can't speak for themselves.
- Use [Google style](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings) docstrings for any classes and functions you add.
- If you're modifying an existing function that does _not_ have docstrings, you don't _have_ to add docstrings to it... but it would be pretty cool if you did ;)
- Imports should be ordered alphabetically.
- Lists of values should be ordered using their [natural sort order](https://en.wikipedia.org/wiki/Natural_sort_order).
- Some files have their methods ordered alphabetically as well (i.e. [`thumb_renderer`](https://github.com/TagStudioDev/TagStudio/blob/main/src/tagstudio/qt/widgets/thumb_renderer.py)). If you're working in a file and notice this, please try and keep to the pattern.
- When writing text for window titles or form titles, use "[Title Case](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case)" capitalization. Your IDE may have a command to format this for you automatically, although some may incorrectly capitalize short prepositions. In a pinch you can use a website such as [capitalizemytitle.com](https://capitalizemytitle.com/) to check.
- If it wasn't mentioned above, then stick to [**PEP-8**](https://peps.python.org/pep-0008/)!
## QT
As of writing this section, the QT part of the code base is quite unstructured and the View and Controller parts are completely intermixed[^1]. This makes maintenance, fixes and general understanding of the code base quite challenging, because the interesting parts you are looking for are entangled in a bunch of repetitive UI setup code. To address this we are aiming to more strictly separate the view and controller aspects of the QT frontend.
The general structure of the QT code base should look like this:
```
qt
├── controller
│ ├── widgets
│ │ └── preview_panel_controller.py
│ └── main_window_controller.py
├── view
│ ├── widgets
│ │ └── preview_panel_view.py
│ └── main_window_view.py
├── ts_qt.py
└── mixed.py
```
In this structure there are the `view` and `controller` sub-directories. They have the exact same structure and for every `<component>_view.py` there is a `<component>_controller.py` at the same location in the other subdirectory and vice versa.
Typically the classes should look like this:
```py
# my_cool_widget_view.py
class MyCoolWidgetView(QWidget):
def __init__(self):
super().__init__()
self.__button = QPushButton()
self.__color_dropdown = QComboBox()
# ...
self.__connect_callbacks()
def __connect_callbacks(self):
self.__button.clicked.connect(self._button_click_callback)
self.__color_dropdown.currentIndexChanged.connect(
lambda idx: self._color_dropdown_callback(self.__color_dropdown.itemData(idx))
)
def _button_click_callback(self):
raise NotImplementedError()
```
```py
# my_cool_widget_controller.py
class MyCoolWidget(MyCoolWidgetView):
def __init__(self):
super().__init__()
def _button_click_callback(self):
print("Button was clicked!")
def _color_dropdown_callback(self, color: Color):
print(f"The selected color is now: {color}")
```
Observe the following key aspects of this example:
- The Controller is just called `MyCoolWidget` instead of `MyCoolWidgetController` as it will be directly used by other code
- The UI elements are in private variables
- This enforces that the controller shouldn't directly access UI elements
- Instead the view should provide a protected API (e.g. `_get_color()`) for things like setting/getting the value of a dropdown, etc.
- Instead of `_get_color()` there could also be a `_color` method marked with `@property`
- The callback methods are already defined as protected methods with NotImplementedErrors
- Defines the interface the callbacks
- Enforces that UI events be handled
> [!TIP]
> A good (non-exhaustive) rule of thumb is: If it requires a non-UI import, then it doesn't belong in the `*_view.py` file.
[^1]: For an explanation of the Model-View-Controller (MVC) Model, checkout this article: [MVC Framework Introduction](https://www.geeksforgeeks.org/mvc-framework-introduction/).

View File

@@ -1,19 +0,0 @@
# shellcheck shell=bash
# If you wish to use this file, symlink or copy it to `.envrc` for direnv to read it.
# This will use the Nix flake development shell.
#
# ln -s contrib/.envrc-nix .envrc
if ! has nix_direnv_version || ! nix_direnv_version 3.0.6; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.6/direnvrc" "sha256-RYcUJaRMf8oF5LznDrlCXbkOQrywm0HDv1VjYGaJGdM="
fi
watch_file nix/shell.nix pyproject.toml
use flake
# Only watch now, or direnv will execute again if created or modified by itself.
watch_file "${UV_PROJECT_ENVIRONMENT:-.venv}"/bin/activate
# vi: ft=bash

View File

@@ -1,32 +0,0 @@
# shellcheck shell=bash
# If you wish to use this file, symlink or copy it to `.envrc` for direnv to read it.
# This will use a virtual environment created by uv.
#
# ln -s contrib/.envrc-uv .envrc
watch_file .python-version pyproject.toml uv.lock
venv="$(expand_path "${UV_PROJECT_ENVIRONMENT:-.venv}")"
if [ ! -f "${venv}"/bin/activate ]; then
printf '%s\n' 'Generating virtual environment...' >&2
rm -rf "${venv}"
uv venv "${venv}"
fi
# Only watch now, or direnv will execute again if created or modified by itself.
watch_file "${venv}"/bin/activate
# shellcheck disable=SC1091
source "${venv}"/bin/activate
if [ ! -f "${venv}"/pyproject.toml ] || ! diff --brief pyproject.toml "${venv}"/pyproject.toml >/dev/null; then
printf '%s\n' 'Installing dependencies, pyproject.toml changed...' >&2
uv pip install --quiet --editable '.[dev]'
cp pyproject.toml "${venv}"/pyproject.toml
fi
pre-commit install
# vi: ft=bash

View File

@@ -1,17 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "TagStudio",
"type": "python",
"request": "launch",
"program": "${workspaceRoot}/src/tagstudio/main.py",
"console": "integratedTerminal",
"justMyCode": true,
"args": [
"-o",
"~/Documents/Example"
]
}
]
}

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 739 739" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(0.986683,0,0,0.986683,-136.081,-136.081)">
<path d="M535.939,863.161C515.931,843.153 203.505,529.713 183.497,509.705C169.086,495.294 161.469,476.645 160.649,457.754C160.046,443.845 138.078,230.102 137.923,217.139C137.681,196.785 145.323,176.356 160.839,160.839C177.115,144.564 198.795,136.951 220.125,138.016C232.439,138.63 447.036,159.52 461.817,160.931C479.3,162.6 496.329,170.12 509.705,183.497C523.113,196.904 849.753,522.531 863.161,535.939C893.716,566.494 893.716,616.108 863.161,646.663L646.663,863.161C616.108,893.716 566.494,893.716 535.939,863.161ZM321.355,223.613C296.045,198.303 254.947,198.303 229.636,223.613C204.326,248.924 204.326,290.022 229.636,315.332C254.947,340.643 296.045,340.643 321.355,315.332C346.666,290.022 346.666,248.924 321.355,223.613ZM362.109,606.786C409.476,654.152 424.103,598.401 454.027,606.786C468.584,610.865 453.72,642.505 443.028,673.551C425.086,725.641 484.094,757.817 516.601,720.743C545.603,687.667 503.579,655.692 520.581,632.527C537.795,609.074 563.542,633.319 565.542,665.527C568.921,719.955 535.825,735.585 543.999,774.591C553.59,820.348 624.181,827.565 638,774.591C647.736,737.269 603.102,705.31 628.352,644.476C636.209,625.545 662.786,619.154 669.759,644.476C673.976,659.791 660.264,670.152 666.759,693.55C674.41,721.114 725.088,732.96 740.374,693.55C746.873,676.793 734.853,651.273 731.597,640.406C714.283,582.611 826.807,582.426 762.374,517.789C703.034,458.263 493.6,249.017 493.6,249.017C479.164,234.58 457.464,234.58 443.028,249.017L249.017,443.028C234.58,457.464 234.58,479.164 249.017,493.6C249.017,493.6 340.149,584.825 362.109,606.786Z" style="fill:white;"/>
</g>
<g transform="matrix(0.986683,0,0,0.986683,-136.081,-136.081)">
<path d="M733.962,560.164C740.987,553.139 740.987,541.733 733.962,534.708L482.173,282.92C475.148,275.895 463.742,275.895 456.717,282.92L431.261,308.376C424.237,315.4 424.237,326.807 431.261,333.831L683.05,585.62C690.075,592.645 701.481,592.645 708.506,585.62L733.962,560.164ZM439.639,559.207C446.664,552.182 446.664,540.776 439.639,533.751L335.491,429.602C328.466,422.578 317.059,422.578 310.035,429.602L284.579,455.058C277.554,462.083 277.554,473.489 284.579,480.514L388.728,584.663C395.752,591.688 407.159,591.688 414.184,584.663L439.639,559.207ZM584.306,556.624C591.331,549.599 591.331,538.192 584.306,531.168L409.115,355.977C402.091,348.953 390.684,348.953 383.66,355.977L358.204,381.433C351.179,388.458 351.179,399.864 358.204,406.889L533.394,582.079C540.419,589.104 551.825,589.104 558.85,582.079L584.306,556.624ZM298.425,246.543C311.081,259.198 311.081,279.747 298.425,292.402C285.77,305.058 265.221,305.058 252.566,292.402C239.911,279.747 239.911,259.198 252.566,246.543C265.221,233.888 285.77,233.888 298.425,246.543Z" style="fill:white;"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 234 KiB

View File

@@ -1,192 +0,0 @@
---
icon: material/code-braces
---
# :material-code-braces: Developing
If you wish to develop for TagStudio, you'll need to create a development environment by installing the required dependencies. You have a number of options depending on your level of experience and familiarity with existing Python toolchains.
<!-- prettier-ignore -->
!!! tip "Contributing"
If you wish to contribute to TagStudio's development, please read our [CONTRIBUTING.md](https://github.com/TagStudioDev/TagStudio/blob/main/CONTRIBUTING.md)!
## Installing Python
Python [3.12](https://www.python.org/downloads) is required to develop for TagStudio. Any version matching "Python 3.12.x" should work, with "x" being any number. Alternatively you can use a tool such as [pyenv](https://github.com/pyenv/pyenv) to install this version of Python without affecting any existing Python installations on your system. Tools such as [uv](#installing-with-uv) can also install Python versions.
<!-- prettier-ignore -->
!!! info "Python Aliases"
Depending on your system, Python may be called `python`, `py`, `python3`, or `py3`. These instructions use the alias `python` for consistency.
If you already have Python installed on your system, you can check the version by running the following command:
```sh
python --version
```
---
### Installing with pyenv
If you choose to install Python using pyenv, please refer to the following instructions:
1. Follow pyenv's [install instructions](https://github.com/pyenv/pyenv/?tab=readme-ov-file#installation) for your system.
2. Install the appropriate Python version with pyenv by running `pyenv install 3.12` (This will **not** mess with your existing Python installation).
3. Navigate to the repository root folder in your terminal and run `pyenv local 3.12`. You could alternatively use `pyenv shell 3.12` or `pyenv global 3.12` instead to set the Python version for the current terminal session or the entire system respectively, however using `local` is recommended.
---
## Cloning from GitHub
The repository can be cloned/downloaded via `git` in your terminal, or by downloading the zip file from the "Code" button on the [repository page](https://github.com/TagStudioDev/TagStudio).
```sh
git clone https://github.com/TagStudioDev/TagStudio.git
```
## Installing Dependencies
To install the required dependencies, you can use a dependency manager such as [uv](https://docs.astral.sh/uv) or [Poetry 2.0](https://python-poetry.org). Alternatively you can create a virtual environment and manually install the dependencies yourself.
### Installing with uv
If using [uv](https://docs.astral.sh/uv), you can install the dependencies for TagStudio with the following command:
```sh
uv pip install -e ".[dev]"
```
A reference `.envrc` is provided for use with [direnv](#direnv), see [`contrib/.envrc-uv`](https://github.com/TagStudioDev/TagStudio/blob/main/contrib/.envrc-uv).
---
### Installing with Poetry
If using [Poetry](https://python-poetry.org), you can install the dependencies for TagStudio with the following command:
```sh
poetry install --with dev
```
---
### Manual Installation
If you choose to manually set up a virtual environment and install dependencies instead of using a dependency manager, please refer to the following instructions:
<!-- prettier-ignore -->
!!! tip "Virtual Environments"
Learn more about setting up a virtual environment with Python's [official tutorial](https://docs.python.org/3/tutorial/venv.html).
1. In the root repository directory, create a python virtual environment:
```sh
python -m venv .venv
```
2. Activate your environment:
- Windows w/Powershell: `.venv\Scripts\Activate.ps1`
- Windows w/Command Prompt: `.venv\Scripts\activate.bat`
- Linux/macOS: `source .venv/bin/activate`
<!-- prettier-ignore -->
!!! info "Supported Shells"
Depending on your system, the regular activation script _might_ not work on alternative shells. In this case, refer to the table below for supported shells:
| Shell | Script |
| ---------: | :------------------------ |
| Bash/ZSH | `.venv/bin/activate` |
| Fish | `.venv/bin/activate.fish` |
| CSH/TCSH | `.venv/bin/activate.csh` |
| PowerShell | `.venv/bin/activate.ps1` |
3. Use the following PIP command to create an editable installation and install the required development dependencies:
```sh
pip install -e ".[dev]"
```
## Nix(OS)
If using [Nix](https://nixos.org/), there is a development environment already provided in the [flake](https://wiki.nixos.org/wiki/Flakes) that is accessible with the following command:
```sh
nix develop
```
A reference `.envrc` is provided for use with [direnv](#direnv), see [`contrib/.envrc-nix`](https://github.com/TagStudioDev/TagStudio/blob/main/contrib/.envrc-nix).
## Tooling
### Editor Integration
The entry point for TagStudio is `src/tagstudio/main.py`. You can target this file from your IDE to run or connect a debug session. The example(s) below show off example launch scripts for different IDEs. Here you can also take advantage of [launch arguments](./usage.md/#launch-arguments) to pass your own test [libraries](./library/index.md) to use while developing. You can find more editor configurations in [`contrib`](https://github.com/TagStudioDev/TagStudio/tree/main/contrib).
<!-- prettier-ignore -->
=== "VS Code"
```json title=".vscode/launch.json"
{
"version": "0.2.0",
"configurations": [
{
"name": "TagStudio",
"type": "python",
"request": "launch",
"program": "${workspaceRoot}/src/tagstudio/main.py",
"console": "integratedTerminal",
"justMyCode": true,
"args": ["-o", "~/Documents/Example"]
}
]
}
```
### pre-commit
There is a [pre-commit](https://pre-commit.com/) configuration that will run through some checks before code is committed. Namely, mypy and the Ruff linter and formatter will check your code, catching those nits right away.
Once you have pre-commit installed, just run:
```sh
pre-commit install
```
From there, Git will automatically run through the hooks during commit actions!
### direnv
You can automatically enter this development shell, and keep your user shell, with a tool like [direnv](https://direnv.net/). Some reference `.envrc` files are provided in the repository at [`contrib`](https://github.com/TagStudioDev/TagStudio/tree/main/contrib).
Two currently available are for [Nix](#nixos) and [uv](#installing-with-uv), to use one:
```sh
ln -s .envrc-$variant .envrc
```
You will have to allow usage of it.
<!-- prettier-ignore -->
!!! warning "direnv Security Framework"
These files are generally a good idea to check, as they execute commands on directory load. direnv has a security framework to only run `.envrc` files you have allowed, and does keep track on if it has changed. So, with that being said, the file may need to be allowed again if modifications are made.
```sh
cat .envrc # You are checking them, right?
direnv allow
```
## Building
To build your own executables of TagStudio, first follow the steps in "[Installing Dependencies](#installing-dependencies)." Once that's complete, run the following PyInstaller command:
```
pyinstaller tagstudio.spec
```
If you're on Windows or Linux and wish to build a portable executable, then pass the following flag:
```
pyinstaller tagstudio.spec -- --portable
```
The resulting executable file(s) will be located in a new folder named "dist".

View File

@@ -1,8 +1,4 @@
---
icon: material/movie-open-cog
---
# :material-movie-open-cog: FFmpeg
# FFmpeg
FFmpeg is required for thumbnail previews and playback features on audio and video files. FFmpeg is a free Open Source project dedicated to the handling of multimedia (video, audio, etc) files. For more information, see their official website at [ffmpeg.org](https://www.ffmpeg.org/).

View File

@@ -1,110 +1,52 @@
---
title: Home
hide:
- toc
---
#
# Welcome to the TagStudio Documentation!
<link rel="stylesheet" href="stylesheets/home.css">
![TagStudio Alpha](./assets/github_header.png)
<figure markdown="span">
![TagStudio](./assets/ts-9-3_logo_text.png){ width=80% }<h2>A User-Focused Photo & File Management System</h2>
</figure>
TagStudio is a photo & file organization application with an underlying tag-based system that focuses on giving freedom and flexibility to the user. No proprietary programs or formats, no sea of sidecar files, and no complete upheaval of your filesystem structure.
<br>
<figure width="60%" markdown="span">
![TagStudio screenshot](./assets/screenshot.png)
<figure markdown="span">
![TagStudio screenshot](./assets/screenshot.png){ width=80% }
<figcaption>TagStudio Alpha v9.5.0 running on macOS Sequoia.</figcaption>
</figure>
<div class="grid" markdown>
## Feature Roadmap
![TagStudio screenshot](./assets/tag_bubbles.png)
The [Feature Roadmap](./updates/roadmap.md) lists all of the planned core features for TagStudio to be considered "feature complete" along with estimated release milestones. The development and testing of these features takes priority over all other requested or submitted features unless they are later added to this roadmap. This helps ensure that TagStudio eventually sees a full release and becomes more usable by more people more quickly.
**TagStudio** is a photo & file organization application with an underlying tag-based system that focuses on giving freedom and flexibility to the user. No proprietary programs or formats, no sea of sidecar files, and no complete upheaval of your filesystem structure.
## Current Features
</div>
### Libraries
<figure markdown="span">
[:material-download: Download Latest Release](https://github.com/TagStudioDev/TagStudio/releases){ .md-button .md-button--primary }
</figure>
- Create [libraries](./library/index.md) centered around a system directory. Libraries contain a series of entries: the representations of your files combined with metadata fields. Each entry represents a file in your librarys directory, and is linked to its location.
- Address moved, deleted, or otherwise "unlinked" files by using the "Fix Unlinked Entries" option in the Tools menu.
## :material-star: Core Features
### Tagging + Metadata Fields
<div class="grid cards" markdown>
- Add custom powerful [tags](./library/tag.md) to your library entries
- Add [metadata fields](./library/field.md) to your library entries, including:
- Name, Author, Artist (Single-Line Text Fields)
- Description, Notes (Multi-Line Text Fields)
- Create rich tags composed of a name, color, a list of aliases, and a list of "parent tags" - these being tags in which these tags inherit values from.
- Copy and paste tags and fields across file entries
- Automatically organize tags into groups based on parent tags marked as "categories"
- Generate tags from your existing folder structure with the "Folders to Tags" macro (NOTE: these tags do NOT sync with folders after they are created)
- :material-file-multiple:{ .lg .middle } **[All Files](./library/entry.md) Welcome**
### Search
***
- [Search](./library/library_search.md) for file entries based on tags, file path (`path:`), file types (`filetype:`), and even media types! (`mediatype:`)
- Use and combine Boolean operators (`AND`, `OR`, `NOT`) along with parentheses groups, quotation escaping, and underscore substitution to create detailed search queries
- Use special search conditions (`special:untagged`) to find file entries without tags or fields, respectively
TagStudio works with photos, videos, music, documents, and more! **All file types** are recognized by TagStudio, with most common ones having built-in preview support.
### File Entries
[:material-arrow-right: See Full Preview Support](./library/index.md#preview-support)
- :material-tag-text:{ .lg .middle } **Create [Tags](./library/tag.md) Your Way**
***
- :material-format-font: No character restrictions
- :material-form-textbox: Add aliases/alternate names
- :material-palette: Customize colors and styles
- :material-tag-multiple: Tags can be tagged with other tags!
- :material-star-four-points: And more!
- :material-magnify:{ .lg .middle } **Powerful [Search](./library/library_search.md)**
***
- Full [Boolean operator](./library/library_search.md) support
- Filenames, paths, and extensions with [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) syntax
- General media types (e.g. "Photo", "Video", "Document")
- Special searches (e.g. "Untagged")
- "[Smartcase](./library/library_search.md#case-sensitivity)" case sensitivity
- :material-text-box:{ .lg .middle } **Text and Date [Fields](./library/field.md)**
***
Along with tags, add custom metadata fields such as text and dates to your files!
This is useful for adding notes and descriptions, titling files, and keeping track of extra dates and times.
</div>
## :material-toolbox: Built Different
<div class="grid cards" markdown>
- :material-scale-balance:{ .lg .middle } **Open Source**
***
TagStudio is licensed under the GPL-3.0 license with the source code and executable releases available on [GitHub](https://github.com/TagStudioDev/TagStudio).
[:material-arrow-right: View License](https://github.com/TagStudioDev/TagStudio/blob/main/LICENSE)
[:material-arrow-right: Roadmap to MIT Core Library License](./updates/roadmap.md#core-library-api)
- :material-database:{ .lg .middle } **Central Save File**
***
Apposed to filling your drives with [sidecar files](https://en.wikipedia.org/wiki/Sidecar_file), TagStudio uses a project-like [library](./library/index.md) system that stores your tags and metadata inside a single save file per-library.
[:material-arrow-right: Learn About the Format](./library/index.md)
</div>
---
## :material-layers-triple: More Than an Application
TagStudio aims to create an **open** and **robust** format for file tagging that isn't burdened by the limitations of traditional tagging and file metadata systems. **TagStudio** is the first proof-of-concept implementation of this system.
<div class="grid cards" markdown>
- :material-map-check:{ .lg .middle } See the [**Roadmap**](./updates/roadmap.md) for future features and updates
</div>
- Nearly all [file](./library/entry.md) types are supported in TagStudio libraries - just not all have dedicated thumbnail support.
- Preview most image file types, animated GIFs, videos, plain text documents, audio files, Blender projects, and more!
- Open files or file locations by right-clicking on thumbnails and previews and selecting the respective context menu options. You can also click on the preview panel image to open the file, and click the file path label to open its location.
- Delete files from both your library and drive by right-clicking the thumbnail(s) and selecting the "Move to Trash"/"Move to Recycle Bin" option.

View File

@@ -1,28 +1,20 @@
---
icon: material/download
---
# Installation
# :material-download: Installation
## Releases
TagStudio provides [releases](https://github.com/TagStudioDev/TagStudio/releases) as well as full access to its [source code](https://github.com/TagStudioDev/TagStudio) under the [GPLv3](https://github.com/TagStudioDev/TagStudio/blob/main/LICENSE) license.
## Executables
TagStudio provides executable [releases](https://github.com/TagStudioDev/TagStudio/releases) as well as full access to its [source code](https://github.com/TagStudioDev/TagStudio) under the [GPLv3](https://github.com/TagStudioDev/TagStudio/blob/main/LICENSE) license.
To download executable builds of TagStudio, visit the [Releases](https://github.com/TagStudioDev/TagStudio/releases) page of the GitHub repository and download the latest release for your system under the "Assets" section at the bottom of the release.
TagStudio has builds for **Windows**, **macOS** _(Apple Silicon & Intel)_, and **Linux**. We also offer portable releases for Windows and Linux which are self-contained and easier to move around.
<!-- prettier-ignore -->
!!! info "Third-Party Dependencies"
You may need to install [third-party dependencies](#third-party-dependencies) such as [FFmpeg](https://ffmpeg.org/download.html) to use the full feature set of TagStudio.
<!-- prettier-ignore -->
!!! warning "For macOS Users"
!!! info "For macOS Users"
On macOS, you may be met with a message saying "**"TagStudio" can't be opened because Apple cannot check it for malicious software.**" If you encounter this, then you'll need to go to the "Settings" app, navigate to "Privacy & Security", and scroll down to a section that says "**"TagStudio" was blocked from use because it is not from an identified developer.**" Click the "Open Anyway" button to allow TagStudio to run. You should only have to do this once after downloading the application.
---
## Package Managers
### Package Managers
<!-- prettier-ignore -->
!!! danger "Unofficial Releases"
@@ -50,9 +42,9 @@ pip install .
!!! note "Developer Dependencies"
If you wish to create an editable install with the additional dependencies required for developing TagStudio, use this modified PIP command instead:
```sh
pip install -e ".[dev]"
pip install -e .[dev]
```
_See more under "[Developing](./develop.md)"_
_See more under "[Creating a Development Environment](#creating-a-development-environment)"_
TagStudio can now be launched via the `tagstudio` command in your terminal.
@@ -209,16 +201,183 @@ Finally, `inputs` can be used in a module to add the package to your packages li
Don't forget to rebuild!
## Third-Party Dependencies
---
## Creating a Development Environment
If you wish to develop for TagStudio, you'll need to create a development environment by installing the required dependencies. You have a number of options depending on your level of experience and familiarly with existing Python toolchains.
<!-- prettier-ignore -->
!!! tip
You can check to see if any of these dependencies are correctly located by launching TagStudio and going to "About TagStudio" in the menu bar.
!!! tip "Contributing"
If you wish to contribute to TagStudio's development, please read our [CONTRIBUTING.md](https://github.com/TagStudioDev/TagStudio/blob/main/CONTRIBUTING.md)!
### FFmpeg/FFprobe
### Install Python
For audio/video thumbnails and playback you'll need [FFmpeg](https://ffmpeg.org/download.html) installed on your system. If you encounter any issues with this, please reference our [FFmpeg Help](./help/ffmpeg.md) guide.
Python [3.12](https://www.python.org/downloads/) is required to develop for TagStudio. Any version matching "Python 3.12.x" should work, with "x" being any number. Alternatively you can use a tool such as [pyenv](https://github.com/pyenv/pyenv/) to install this version of Python without affecting any existing Python installations on your system.
### ripgrep
<!-- prettier-ignore -->
!!! info "Python Aliases"
Depending on your system, Python may be called `python`, `py`, `python3`, or `py3`. These instructions use the alias `python` for consistency.
A recommended tool to improve the performance of directory scanning is [`ripgrep`](https://github.com/BurntSushi/ripgrep), a Rust-based directory walker that natively integrates with our [`.ts_ignore`](./utilities/ignore.md) (`.gitignore`-style) pattern matching system for excluding files and directories. Ripgrep is already pre-installed on some Linux distributions and also available from several package managers.
If you already have Python installed on your system, you can check the version by running the following command:
```sh
python --version
```
---
#### Installing with pyenv
If you choose to install Python using pyenv, please refer to the following instructions:
1. Follow pyenv's [install instructions](https://github.com/pyenv/pyenv/?tab=readme-ov-file#installation) for your system.
2. Install the appropriate Python version with pyenv by running `pyenv install 3.12` (This will **not** mess with your existing Python installation).
3. Navigate to the repository root folder in your terminal and run `pyenv local 3.12`. You could alternatively use `pyenv shell 3.12` or `pyenv global 3.12` instead to set the Python version for the current terminal session or the entire system respectively, however using `local` is recommended.
---
### Installing Dependencies
To install the required dependencies, you can use a dependency manager such as [uv](https://docs.astral.sh/uv) or [Poetry 2.0](https://python-poetry.org). Alternatively you can create a virtual environment and manually install the dependencies yourself.
#### Installing with uv
If using [uv](https://docs.astral.sh/uv), you can install the dependencies for TagStudio with the following command:
```sh
uv pip install -e .[dev]
```
---
#### Installing with Poetry
If using [Poetry](https://python-poetry.org), you can install the dependencies for TagStudio with the following command:
```sh
poetry install --with dev
```
---
#### Installing with Nix
If using [Nix](https://nixos.org/), there is a development environment already provided in the [flake](https://wiki.nixos.org/wiki/Flakes) that is accessible with the following command:
```sh
nix develop
```
You can automatically enter this development shell, and keep your user shell, with a tool like [direnv](https://direnv.net/). A reference `.envrc` is provided in the repository; to use it:
```sh
ln -s .envrc.recommended .envrc
```
You will have to allow usage of it.
<!-- prettier-ignore -->
!!! warning "`.envrc` Security"
These files are generally a good idea to check, as they execute commands on directory load. direnv has a security framework to only run `.envrc` files you have allowed, and does keep track on if it has changed. So, with that being said, the file may need to be allowed again if modifications are made.
```sh
cat .envrc # You are checking them, right?
direnv allow
```
---
#### Manual Installation
If you choose to manually set up a virtual environment and install dependencies instead of using a dependency manager, please refer to the following instructions:
<!-- prettier-ignore -->
!!! tip "Virtual Environments"
Learn more about setting up a virtual environment with Python's [official tutorial](https://docs.python.org/3/tutorial/venv.html).
1. In the root repository directory, create a python virtual environment:
```sh
python -m venv .venv
```
2. Activate your environment:
- Windows w/Powershell: `.venv\Scripts\Activate.ps1`
- Windows w/Command Prompt: `.venv\Scripts\activate.bat`
- Linux/macOS: `source .venv/bin/activate`
<!-- prettier-ignore -->
!!! info "Supported Shells"
Depending on your system, the regular activation script _might_ not work on alternative shells. In this case, refer to the table below for supported shells:
| Shell | Script |
| ---------: | :------------------------ |
| Bash/ZSH | `.venv/bin/activate` |
| Fish | `.venv/bin/activate.fish` |
| CSH/TCSH | `.venv/bin/activate.csh` |
| PowerShell | `.venv/bin/activate.ps1` |
3. Use the following PIP command to create an editable installation and install the required development dependencies:
```sh
pip install -e .[dev]
```
### Launching
The entry point for TagStudio is `src/tagstudio/main.py`. You can target this file from your IDE to run or connect a debug session. The example(s) below show off example launch scripts for different IDEs. Here you can also take advantage of [launch arguments](#launch-arguments) to pass your own test [libraries](./library/index.md) to use while developing.
<!-- prettier-ignore -->
=== "VS Code"
```json title=".vscode/launch.json"
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "TagStudio",
"type": "python",
"request": "launch",
"program": "${workspaceRoot}/src/tagstudio/main.py",
"console": "integratedTerminal",
"justMyCode": true,
"args": ["-o", "~/Documents/Example"]
}
]
}
```
## Building
To build your own executables of TagStudio, first follow the steps in "[Installing with PIP](#installing-with-pip)" including the developer dependencies step. Once that's complete, run the following PyInstaller command:
```
pyinstaller tagstudio.spec
```
If you're on Windows or Linux and wish to build a portable executable, then pass the following flag:
```
pyinstaller tagstudio.spec -- --portable
```
The resulting executable file(s) will be located in a new folder named "dist".
## Third-Party Dependencies
For audio/video thumbnails and playback you'll also need [FFmpeg](https://ffmpeg.org/download.html) installed on your system. If you encounter any issues with this, please reference our [FFmpeg Help](./help/ffmpeg.md) guide.
You can check to see if FFmpeg and FFprobe are correctly located by launching TagStudio and going to "About TagStudio" in the menu bar.
## Launch Arguments
There are a handful of launch arguments you can pass to TagStudio via the command line or a desktop shortcut.
| Argument | Short | Description |
| ---------------------- | ----- | ---------------------------------------------------- |
| `--open <path>` | `-o` | Path to a TagStudio Library folder to open on start. |
| `--config-file <path>` | `-c` | Path to the TagStudio config file to load. |

View File

@@ -1,22 +1,18 @@
---
icon: material/file
---
# File Entries
# :material-file: Entries
Entries are the individual representations of your files inside a TagStudio [library](./index.md). Each one corresponds one-to-one to a file on disk, and tracks all of the additional [tags](tag.md) and metadata that you attach to it inside TagStudio.
File entries are the individual representations of your files inside a TagStudio [library](./index.md). Each one corresponds one-to-one to a file on disk, and tracks all of the additional [tags](tag.md) and metadata that you attach to it inside TagStudio.
## Storage
File entry data is stored within the `ts_library.sqlite` file inside each library's `.TagStudio` folder. No modifications are made to your actual files on disk, and nothing like sidecar files are generated for your files.
File entry data is storied within the `ts_library.sqlite` file inside each library's `.TagStudio` folder. No modifications are made to your actual files on disk, and nothing like sidecar files are generated for your files.
## Appearance
File entries appear as thumbnails inside the grid display. The preview panel shows a more detailed preview of the file, along with extra file stats and all attached TagStudio tags and fields.
File entries appear as file previews both inside the thumbnail grid. The preview panel shows a more detailed preview of the file, along with extra file stats and all attached TagStudio tags and fields.
## Unlinked Entries
## Unlinked File Entries
If the file that an entry is referencing has been moved, renamed, or deleted on disk, then TagStudio will display its unlinked status with a red chain-link icon instead of its thumbnail image. Certain uncached stats such as the file size and image dimensions will also be unavailable to see in the preview panel.
If the file that an entry is referencing has been moved, renamed, or deleted on disk, then TagStudio will display a red chain-link icon for the thumbnail image. Certain uncached stats such as the file size and image dimensions will also be unavailable to see in the preview panel when a file becomes unlinked.
To fix file entries that have become unlinked, select the "Fix Unlinked Entries" option from the Tools menu. From there, refresh the unlinked entry count and choose whether to search and relink you files, and/or delete the file entries from your library. This will NOT delete or modify any files on disk.
@@ -36,11 +32,11 @@ To fix file entries that have become unlinked, select the "Fix Unlinked Entries"
- `date_created` (`DATETIME`/`Datetime`)
- _Not currently used, will be implemented in an upcoming update._
- The creation date of the file (not the entry).
- Generated from `st_birthtime` on Windows and Mac, and `st_ctime` on Linux.
- Generates from `st_birthtime` on Windows and Mac, and `st_ctime` on Linux.
- `date_modified` (`DATETIME`/`Datetime`)
- _Not currently used, will be implemented in an upcoming update._
- The latest modification date of the file (not the entry).
- Generated from `st_mtime`.
- Generates from `st_mtime`.
- `date_added` (`DATETIME`/`Datetime`)
- The date the file entry was added to the TagStudio library.

View File

@@ -0,0 +1,8 @@
---
tags:
- Upcoming Feature
---
# Entry Groups
Entries can be grouped via tags marked as "groups" which when applied to different entries will signal TagStudio to treat those entries as a single group inside of searches and browsing.

View File

@@ -1,10 +1,6 @@
---
icon: material/text-box
---
# Fields
# :material-text-box: Fields
Fields are additional types of metadata that you can attach to [file entries](./entry.md). Like [tags](./tag.md), fields are not stored inside files themselves nor in sidecar files, but rather inside the respective TagStudio [library](./index.md) save file.
Fields are additional types of metadata that you can attach to [file entries](./entry.md). Like [tags](./tag.md), fields are not stored inside files themselves nor in sidecar files, but rather inside the respective TagStudio [library](index.md) save file.
## Field Types

View File

@@ -1,155 +1,5 @@
# :material-database: Library
<!-- prettier-ignore -->
!!! info
This page is a work in progress and needs to be updated with additional information.
# Library
The library is how TagStudio represents your chosen directory, with every file inside being represented by a [file entry](./entry.md). You can have as many or few libraries as you wish, since each libraries' data is stored within a `.TagStudio` folder at its root. From there the library save file itself is stored as `ts_library.sqlite`, with TagStudio versions 9.4 and below using a the legacy `ts_library.json` format.
Note that this means [tags](./tag.md) you create only exist _per-library_. Global tags along with other library structure updates are planned for future releases on the [roadmap](../updates/roadmap.md#library).
---
## Preview Support
TagStudio offers built-in preview and thumbnail support for a wide variety of file types. Files that don't have explicit support can still be added to your library like normal, they will just show a default icon for thumbnails and previews. TagStudio also references the file's [MIME](https://en.wikipedia.org/wiki/Media_type) type in an attempt to render previews for file types that haven't gained explicit support yet.
### :material-image-outline: Images
Images will generate thumbnails the first time they are viewed or since the last time they were modified. Thumbnails are used in the grid view, but not in the Preview Panel. Animated images will play in the Preview Panel.
| Filetype | Extensions | Animation |
| -------------------- | -------------------------------------------------- | :---------------------------------: |
| Animated PNG | `.apng` | :material-check-circle:{.lg .green} |
| Apple Icon Image | `.icns` | :material-minus-circle:{.lg .gray} |
| AVIF | `.avif` | :material-minus-circle:{.lg .gray} |
| Bitmap | `.bmp` | :material-minus-circle:{.lg .gray} |
| GIF | `.gif` | :material-check-circle:{.lg .green} |
| HEIF | `.heif`, `.heic` | :material-minus-circle:{.lg .gray} |
| JPEG | `.jpeg`, `.jpg`, `.jfif`, `.jif`, `.jpg_large`[^1] | :material-minus-circle:{.lg .gray} |
| JPEG-XL | `.jxl` | :material-close-circle:{.lg .red} |
| OpenEXR | `.exr` | :material-minus-circle:{.lg .gray} |
| OpenRaster | `.ora` | :material-minus-circle:{.lg .gray} |
| PNG | `.png` | :material-minus-circle:{.lg .gray} |
| SVG | `.svg` | :material-minus-circle:{.lg .gray} |
| TIFF | `.tiff`, `.tif` | :material-minus-circle:{.lg .gray} |
| Valve Texture Format | `.vtf` | :material-close-circle:{.lg .red} |
| WebP | `.webp` | :material-check-circle:{.lg .green} |
| Windows Icon | `.ico` | :material-minus-circle:{.lg .gray} |
#### :material-image-outline: RAW Images
| Filetype | Extensions |
| -------------------------------- | ---------------------- |
| Camera Image File Format (Canon) | `.crw`, `.cr2`, `.cr3` |
| Digital Negative | `.dng` |
| Fuji RAW | `.raf` |
| Nikon RAW | `.nef`, `.nrw` |
| Olympus RAW | `.orf` |
| Panasonic RAW | `.raw`, `.rw2` |
| Sony RAW | `.arw` |
### :material-movie-open: Videos
Video thumbnails will default to the closest viable frame from the middle of the video. Both thumbnail generation and video playback in the Preview Panel requires [FFmpeg](../install.md#third-party-dependencies) installed on your system.
| Filetype | Extensions | Dependencies |
| --------------------- | ----------------------- | :----------: |
| 3GP | `.3gp` | FFmpeg |
| AVI | `.avi` | FFmpeg |
| AVIF | `.avif` | FFmpeg |
| FLV | `.flv` | FFmpeg |
| HEVC | `.hevc` | FFmpeg |
| Matroska | `.mkv` | FFmpeg |
| MP4 | `.mp4` , `.m4p` | FFmpeg |
| MPEG Transport Stream | `.ts` | FFmpeg |
| QuickTime | `.mov`, `.movie`, `.qt` | FFmpeg |
| WebM | `.webm` | FFmpeg |
| WMV | `.wmv` | FFmpeg |
### :material-sine-wave: Audio
Audio thumbnails will default to embedded cover art (if any) andfallback to generated waveform thumbnails. Audio file playback is supported in the Preview Panel if you have [FFmpeg](../install.md#third-party-dependencies) installed on your system. Audio waveforms are currently not cached.
| Filetype | Extensions | Dependencies |
| ------------------- | ------------------------ | :----------: |
| AAC | `.aac`, `.m4a` | FFmpeg |
| AIFF | `.aiff`, `.aif`, `.aifc` | FFmpeg |
| Apple Lossless[^2] | `.alac`, `.aac` | FFmpeg |
| FLAC | `.flac` | FFmpeg |
| MP3 | `.mp3`, | FFmpeg |
| Ogg | `.ogg` | FFmpeg |
| WAVE | `.wav`, `.wave` | FFmpeg |
| Windows Media Audio | `.wma` | FFmpeg |
### :material-file-chart: Documents
Preview support for office documents or well-known project file formats varies by the format and whether or not embedded thumbnails are available to be read from. OpenDocument-based files are typically supported.
| Filetype | Extensions | Preview Type |
| ----------------------------- | --------------------- | -------------------------------------------------------------------------- |
| Blender | `.blend`, `.blend<#>` | Embedded thumbnail :material-alert-circle:{ title="If available in file" } |
| Keynote (Apple iWork) | `.key` | Embedded thumbnail |
| Krita[^3] | `.kra`, `.krz` | Embedded thumbnail :material-alert-circle:{ title="If available in file" } |
| MuseScore | `.mscz` | Embedded thumbnail :material-alert-circle:{ title="If available in file" } |
| Numbers (Apple iWork) | `.numbers` | Embedded thumbnail |
| OpenDocument Presentation | `.odp`, `.fodp` | Embedded thumbnail |
| OpenDocument Spreadsheet | `.ods`, `.fods` | Embedded thumbnail |
| OpenDocument Text | `.odt`, `.fodt` | Embedded thumbnail |
| Pages (Apple iWork) | `.pages` | Embedded thumbnail |
| PDF | `.pdf` | First page render |
| Photoshop | `.psd` | Flattened image render |
| PowerPoint (Microsoft Office) | `.pptx`, `.ppt` | Embedded thumbnail :material-alert-circle:{ title="If available in file" } |
### 3D Models
<!-- prettier-ignore -->
!!! failure "3D Model Support"
TagStudio does not currently support previews for 3D model files *(outside of Blender project embedded thumbnails)*. This is on our [roadmap](../updates/roadmap.md#uiux) for future features.
### :material-format-font: Fonts
Font thumbnails will use a "Aa" example preview of the font, with a full alphanumeric of the font available in the Preview Panel.
| Filetype | Extensions |
| -------------------- | ----------------- |
| OpenType Font | `.otf`, `.otc` |
| TrueType Font | `.ttf`, `.ttc` |
| Web Open Font Format | `.woff`, `.woff2` |
### :material-text-box: Text
<!-- prettier-ignore -->
!!! info "Plain Text Support"
TagStudio supports the *vast* majority of files considered to be "[plain text](https://en.wikipedia.org/wiki/Plain_text)". If an extension or format is not listed here, odds are it's still supported anyway.
Text files render the first 256 bytes of text information to an image preview for thumbnails and the Preview Panel. Improved thumbnails, full scrollable text, and syntax highlighting are on our [roadmap](../updates/roadmap.md#uiux) for future features.
| Filetype | Extensions | Syntax Highlighting |
| ---------- | --------------------------------------------- | :--------------------------------: |
| CSV | `.csv` | :material-close-circle:{.lg .red} |
| HTML | `.html`, `.htm`, `.xhtml`, `.shtml`, `.dhtml` | :material-close-circle:{.lg .red} |
| JSON | `.json`, `.jsonc`, `.json5` | :material-close-circle:{.lg .red} |
| Markdown | `.md`, `.markdown`, `.mkd`, `.rmd` | :material-close-circle:{.lg .red} |
| Plain Text | `.txt`, `.text` | :material-minus-circle:{.lg .gray} |
| TOML | `.toml` | :material-close-circle:{.lg .red} |
| XML | `.xml`, `.xul` | :material-close-circle:{.lg .red} |
| YAML | `.yaml`, `.yml` | :material-close-circle:{.lg .red} |
### :material-file: Other
| Filetype | Extensions | Preview Type |
| -------- | ---------- | -------------------- |
| EPUB | `.epub` | Embedded ebook cover |
<!-- prettier-ignore-start -->
[^1]:
The `.jpg_large` extension is unofficial and instead the byproduct of how [Google Chrome used to download images from Twitter](https://fileinfo.com/extension/jpg_large). Since this mangled extension is still in circulation, TagStudio supports it.
[^2]:
Apple Lossless traditionally uses `.m4a` and `.caf` containers, but may unofficially use the `.alac` extension. The `.m4a` container is also used for separate compressed audio codecs.
[^3]:
Krita also supports saving projects as OpenRaster `.ora` files. Support for these is listed in the "[Images](#images)" section.
<!-- prettier-ignore-end -->
Note that this means [tags](./tag.md) you create only exist _per-library_.

View File

@@ -1,8 +1,4 @@
---
icon: material/magnify
---
# :material-magnify: Search
# Library Search
TagStudio provides various methods to search your library, ranging from TagStudio data such as tags to inherent file data such as paths or media types.
@@ -40,7 +36,7 @@ Searches can be grouped and nested by using parentheses to surround parts of you
<!-- prettier-ignore -->
!!! example
Searching for "(Tag1 `OR` Tag2) `AND` Tag3" will return any results that contain Tag3, plus one or the other (or both) of Tag1 and Tag2.
Searching for "(Tag1 `OR` Tag2) `AND` Tag3" will return results any results that contain Tag3, plus one or the other (or both) of Tag1 and Tag2.
### Escaping Characters
@@ -58,13 +54,13 @@ Sometimes search queries have ambiguous characters and need to be "escaped". Thi
## Tags
[Tag](#tags) search is the default mode of file entry search in TagStudio. No keyword prefix is required, however using `tag:` will also work. The tag search attempts to match tag [names](./tag.md#name), [shorthands](./tag.md#shorthand), [aliases](./tag.md#aliases), as well as allows for tags to [substitute](./tag.md#intuition-via-substitution) in for any of their [parent tags](./tag.md#parent-tags).
[Tag](#tags) search is the default mode of file entry search in TagStudio. No keyword prefix is required, however using `tag:` will also work. The tag search attempts to match tag [names](tag.md#name), [shorthands](tag.md#shorthand), [aliases](tag.md#aliases), as well as allows for tags to [substitute](tag.md#intuition-via-substitution) in for any of their [parent tags](tag.md#parent-tags).
You may also see the `tag_id:` prefix keyword show up when using the right-click "Search for Tag" option on tags. This is meant for internal use, and eventually will not be displayed or accessible to the user.
You may also see the `tag_id:` prefix keyword show up with using the right-click "Search for Tag" option on tags. This is meant for internal use, and eventually will not be displayed or accessible to the user.
## Fields
_[Field](./field.md) search is currently not in the program, however is coming in a future version._
_[Field](field.md) search is currently not in the program, however is coming in a future version._
## File Entry Search
@@ -78,7 +74,7 @@ TagStudio uses a "[smartcase](https://neovim.io/doc/user/options.html#'smartcase
#### Glob Syntax
Optionally, you may use [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) syntax to search filepaths.
Optionally, you may use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) syntax to search filepaths.
#### Examples

View File

@@ -1,8 +1,4 @@
---
icon: material/tag-text
---
# :material-tag-text: Tags
# Tags
Tags are discrete objects that represent some attribute. This could be a person, place, object, concept, and more. Unlike most tagging systems, TagStudio tags are not solely represented by a line of text or a hashtag. Tags in TagStudio consist of several properties and relationships that give extra customization, searching power, and ease of tagging that cannot be achieved by string-based tags alone. TagStudio tags are designed to be as simple or as complex as you'd like, giving options to users of all skill levels and use cases.
@@ -26,7 +22,7 @@ This is a special type of alias that's used for shortening the tag name under sp
Aliases are alternate names that the tag can go by. This may include individual first names for people, alternate spellings, shortened names, and more. If there's a common abbreviation or shortened name for your tag, it's recommended to use the [shorthand](#shorthand) field for this instead.
When searching for a tag, aliases (including the shorthand) can also be used to find the tag. This not only includes searching for tags themselves, but for tagged [file entries](./entry.md) as well!
When searching for a tag, aliases (including the shorthand) can also be used to find the tag. This not only includes searching for tags themselves, but for tagged [file entries](entry.md) as well!
### Automatic Disambiguation
@@ -36,7 +32,7 @@ Given a tag named "Freddy", we may confuse it with other "Freddy" tags in our li
![Tag Disambiguation Example](../assets/tag_disambiguation_example.png)
So if the "Five Nights at Freddy's" tag is added as a parent tag on the "Freddy" tag, and the disambiguation box next to it is checked, then our tag name will automatically be displayed as "Freddy (Five Nights at Freddy's)". Better yet, if the "Five Nights at Freddy's" tag has a shorthand such as "FNAF", then our "Freddy" tag will be displayed as "Freddy (FNAF)". This process preserves our base tag name ("Freddy") and provides an option to get a clean and consistent method to display disambiguating parent categories, rather than having to type this information in manually for each applicable tag.
So if the "Five Night's at Freddy's" tag is added as a parent tag on the "Freddy" tag, and the disambiguation box next to it is checked, then our tag name will automatically be displayed as "Freddy (Five Nights at Freddy's)". Better yet, if the "Five Night's at Freddy's" tag has a shorthand such as "FNAF", then our "Freddy" tag will be displayed as "Freddy (FNAF)". This process preserves our base tag name ("Freddy") and provides an option to get a clean and consistent method to display disambiguating parent categories, rather than having to type this information in manually for each applicable tag.
## Tag Relationships
@@ -64,9 +60,9 @@ Lastly, when searching your files with broader categories such as `Character` or
### Component Tags
**_Coming in version 9.6_**
**_[Coming in version 9.6](../updates/roadmap.md#v96)_**
Component tags will be built from a composition-based, or "HAS" type relationship between tags. This takes care of instances where an attribute may "have" another attribute, but doesn't inherit from it. Shrek may be an `Ogre`, he may be a `Character`, but he is NOT a `Leather Vest` - even if he's commonly seen _with_ it. Component tags, along with the upcoming "Tag Override" feature, are built to handle these cases in a way that still simplifies the tagging process without adding too much undue complexity for the user.
Component tags will be built from a composition-based, or "HAS" type relationship between tags. This takes care of instances where an attribute may "have" another attribute, but doesn't inherit from it. Shrek may be an `Orge`, he may be a `Character`, but he is NOT a `Leather Vest` - even if he's commonly seen _with_ it. Component tags, along with the upcoming [Tag Override](tag_overrides.md) feature, are built to handle these cases in a way that still simplifies the tagging process without adding too much undue complexity for the user.
## Tag Appearance
@@ -84,7 +80,7 @@ Custom palettes and colors can be created via the [Tag Color Manager](./tag_colo
### Icon
**_Coming in version 9.6_**
**_[Coming in version 9.6](../updates/roadmap.md#v96)_**
## Tag Properties
@@ -98,7 +94,7 @@ When the "Is Category" property is checked, this tag now acts as a category sepa
#### Is Hidden
**_Coming in version 9.6_**
**_[Coming in version 9.6](../updates/roadmap.md#v96)_**
When the "Is Hidden" property is checked, any file entries tagged with this tag will not show up in searches by default. This property comes by default with the built-in "Archived" tag.

View File

@@ -1,10 +1,10 @@
---
icon: material/shape-plus
tags:
---
# :material-shape-plus: Tag Categories
# Tag Categories
The "Is Category" property of tags determines if a tag should be treated as a category itself when being organized inside the preview panel. Tags marked as categories will show themselves and all tags inheriting from it (including recursively) underneath a field-like section with the tag's name. This means that duplicates of tags can appear on entries if the tag inherits from multiple parent categories, however this is by design and reflects the nature of multiple inheritance. Any tags not inheriting from a category tag will simply show under a default "Tag" section.
The "Is Category" property of tags determines if a tag should be treated as a category itself when being organized inside the preview panel. Tags marked as categories will show themselves and all tags inheriting from it (including recursively) underneath a field-like section with the tag's name. This means that duplicates of tags can appear on entries if the tag inherits from multiple parent categories, however this is by design and reflects the nature multiple inheritance. Any tags not inheriting from a category tag will simply show under a default "Tag" section.
![Tag Categories Example](../assets/tag_categories_example.png)

View File

@@ -1,14 +1,10 @@
---
icon: material/palette
---
# :material-palette: Tag Colors
# Tag Colors
TagStudio features a variety of built-in tag colors, alongside the ability for users to create their own custom tag color palettes.
## Tag Color Manager
The Tag Color Manager is where you can create and manage your custom tag colors and associated namespaces. You can access the Tag Color Manager from the "File -> Manage Tag Colors" option in the menu bar.
The Tag Color Manager is where you can create and manage your custom tag colors and associated namespaces. To open the Tag Color Manager, go to "File -> Manage Tag Colors" option in the menu bar.
![Tag Color Manager](../assets/tag_color_manager.png)

View File

@@ -0,0 +1,20 @@
---
tags:
- Upcoming Feature
---
# Tag Overrides
Tag overrides are the ability to add or remove [parent tags](./tag.md#parent-tags) from a [tag](./tag.md) on a per-[entry](./entry.md) basis.
## Examples
<figure markdown="span">
![Example 1](../assets/tag_override_ex-1.png){ height="300" }
<figcaption>Ex. 1 - Comparing standard tag composition vs additive and subtractive inheritance overrides.</figcaption>
</figure>
<figure markdown="span">
![Example 2](../assets/tag_override_ex-2.png){ height="300" }
<figcaption>Ex. 2 - Parent tag swap using tag overrides.</figcaption>
</figure>

View File

@@ -1,155 +1,3 @@
/* Dark Theme */
[data-md-color-scheme="slate"] {
--md-default-bg-color: #060617;
--md-default-fg-color: #eae1ff;
--md-default-fg-color--light: #b898ff;
--md-code-fg-color: #eae1ffcc;
--md-code-hl-string-color: rgb(92, 255, 228);
--md-code-hl-keyword-color: rgb(61, 155, 255);
--md-code-hl-constant-color: rgb(205, 78, 255);
--md-footer-bg-color--dark: #03030c;
--md-code-bg-color: #090a26;
}
/* Light Theme */
[data-md-color-scheme="default"] {
--md-default-fg-color--light: #090a26;
}
.md-header {
background: linear-gradient(
60deg,
rgb(205, 78, 255) 10%,
rgb(116, 123, 255) 50%,
rgb(72, 145, 255) 75%,
rgb(98, 242, 255) 100%
);
}
/* Mobile Nav Header */
.md-nav__source {
background: linear-gradient(
60deg,
rgb(205, 78, 255) 0%,
rgb(116, 123, 255) 100%
);
border-style: solid;
border-width: 0 0 2px 0;
border-color: #ffffff33;
}
th,
td {
th, td {
padding: 0.5em 1em 0.5em 1em !important;
}
.md-header {
border-style: solid;
border-width: 0 0 2px 0;
border-color: #ffffff33;
}
.md-header__title {
font-family: "Bai Jamjuree", Roboto, sans-serif;
font-weight: 500 !important;
font-size: 1.1rem;
letter-spacing: -0.05rem !important;
}
.md-nav__title,
h1,
h2,
.md-nav__item--section > .md-nav__link {
font-family: "Bai Jamjuree", Roboto, sans-serif;
font-weight: 500 !important;
font-size: 0.8rem;
letter-spacing: -0.05rem !important;
}
/* Add padding to stop text from cutting off early due to negative letter spacing */
.md-nav__item--section > .md-nav__link > .md-ellipsis {
padding-right: 0.5rem;
}
.md-header__title .md-header__topic .md-ellipsis {
padding-right: 0.5rem;
}
.md-header__button.md-logo {
padding-right: 0;
padding-bottom: 0.3rem;
margin-right: -0.8rem;
}
figcaption {
margin-top: 0 !important;
}
.md-search__form {
height: 1.5rem;
background-color: #00004444;
border-radius: 0.3rem !important;
border-style: solid;
border-width: 2px 1px 0 1px;
border-color: #00004422;
padding-bottom: 2px;
}
.md-search__form > .md-icon {
margin-top: -0.2rem;
}
h1 > .twemoji {
margin-top: 0.14rem;
}
h2 > .twemoji {
margin-top: 0.08rem;
}
/* Matches the palette used by mkdocs-material */
.priority-high {
color: #f1185a;
}
.priority-med {
color: #7c4eff;
}
.priority-low {
color: #28afff;
}
.red {
color: rgb(245, 0, 87);
}
.amber {
color: rgb(255, 145, 0);
}
.green {
color: rgb(0, 191, 165);
}
.gray {
color: rgb(158, 158, 158);
}
@media screen and (max-width: 76.234375em) {
/* Always show image logo on mobile */
.md-header__button.md-logo {
display: block;
}
label[for="__drawer"].md-header__button.md-icon {
order: -1;
}
.md-header {
background: linear-gradient(
60deg,
rgb(205, 78, 255) 10%,
rgb(116, 123, 255) 70%,
rgb(72, 179, 255) 100%
);
}
}

View File

@@ -1,14 +0,0 @@
h2 {
margin: 1rem 0 0 0 !important;
}
.md-content .md-typeset h1 {
/* display: none; */
font-size: 0;
}
.grid > p {
align-content: center;
font-size: 1rem !important;
line-height: 1.25rem;
}

View File

@@ -1,6 +1,4 @@
---
title: Changelog
icon: material/list-status
---
--8<-- "CHANGELOG.md"
--8<-- "CHANGELOG.md"

View File

@@ -1,283 +1,217 @@
---
icon: material/map-check
---
# Feature Roadmap
# :material-map-check: Roadmap
This checklist details the current and remaining features required at a minimum for TagStudio to be considered "Feature Complete". This list is _not_ a definitive list for additional feature requests and PRs as they come in, but rather an outline of my personal core feature set intended for TagStudio.
This page outlines the current and planned features required for TagStudio to be considered "feature complete" (v10.0.0). Features and changes are broken up by group in order to better assess the overall state of those features. [Priority levels](#priority-levels) and [version estimates](#version-estimates) are provided in order to give a rough idea of what's planned and when it may release.
## Priorities
This roadmap will update as new features are planned or completed. If there's a feature you'd like to see but is not listed on this page, please check the GitHub [Issues](https://github.com/TagStudioDev/TagStudio/issues) page and submit a feature request if one does not already exist!
Features are broken up into the following priority levels, with nested priorities referencing their relative priority for the overall feature (i.e. A [LOW] priority feature can have a [HIGH] priority element but it otherwise still a [LOW] priority item overall):
## Priority Levels
- [HIGH] - Core feature
- [MEDIUM] - Important but not necessary
- [LOW] - Just nice to have
Planned features and changes are assigned **priority levels** to signify how important they are to the feature-complete version of TagStudio and to serve as a general guide for what should be worked on first, along with [version estimates](#version-estimates). When features are completed, their priority level icons are removed.
## Version Milestones
<!-- prettier-ignore -->
!!! info "Priority Level Icons"
- :material-chevron-triple-up:{ .priority-high title="High Priority" } **High Priority** - Core features
- :material-chevron-double-up:{ .priority-med title="Medium Priority" } **Medium Priority** - Important, but not necessary
- :material-chevron-up:{ .priority-low title="Low Priority" } **Low Priority** - Just nice to have
## Version Estimates
Features are given rough estimations for which version they will be completed in, and are listed next to their names (e.g. Feature **[v9.0.0]**). They are eventually replaced with links to the version changelog in which they were completed in, if applicable.
<!-- prettier-ignore -->
!!! tip
For a more definitive and up-to-date list of features planned for near-future updates, please reference the current GitHub [Milestones](https://github.com/TagStudioDev/TagStudio/milestones)!
---
## Core
### :material-database: SQL Library Database
An improved SQLite-based library save file format in which legacy JSON libraries are be migrated to.
Must be finalized or deemed "feature complete" before other core features are developed or finalized.
These version milestones are rough estimations for when the previous core features will be added. For a more definitive idea for when features are coming, please reference the current GitHub [milestones](https://github.com/TagStudioDev/TagStudio/milestones).
<!-- prettier-ignore -->
!!! note
See the "[Library](#library)" section for features related to the library database rather than the underlying schema.
This list was created after the release of version 9.4
- [x] A SQLite-based library save file format **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [ ] Cached File Properties Table :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [x] Date Entry Added to Library :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Date File Created :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Date File Modified :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Date Photo Taken :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Media Duration :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Media Dimensions :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Word Count :material-chevron-up:{ .priority-low title="Low Priority" }
### v9.5
### :material-database-cog: Core Library + API
#### Core
A separated, UI agnostic core library that would be used to interface with the TagStudio library format. Would host an API for communication from outside the program. This would be licensed under the more permissive [MIT](https://en.wikipedia.org/wiki/MIT_License) license to foster wider adoption compared to the TagStudio application source code.
- [x] SQL backend [HIGH]
- [ ] Core Library :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
- [ ] Core Library API :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
- [ ] MIT License :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
#### Tags
### :material-clipboard-text: Format Specification
- [x] Deleting Tags [HIGH]
- [ ] User-defined tag colors [HIGH]
- [x] ID based, not string or hex [HIGH]
- [x] Color name [HIGH]
- [x] Color value (hex) [HIGH]
- [x] Existing colors are now a set of base colors [HIGH]
- [x] [Tag Categories](../library/tag_categories.md) [HIGH]
- [x] Property available for tags that allow the tag and any inheriting from it to be displayed separately in the preview panel under a title [HIGH]
A detailed written specification for the TagStudio tag and/or library format. Intended for used by third-parties to build alternative cores or protocols that can remain interoperable.
#### Search
- [ ] Format Specification Established :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
- [x] Boolean operators [HIGH]
- [x] Filename search [HIGH]
- [x] File type search [HIGH]
- [x] Search by extension (e.g. ".jpg", ".png") [HIGH]
- [x] Optional consolidation of extension synonyms (i.e. ".jpg" can equal ".jpeg") [LOW]
- [x] Search by media type (e.g. "image", "video", "document") [MEDIUM]
- [x] Sort by date added [HIGH]
---
#### UI
## Application
- [ ] Translations _(Any applicable)_ [MEDIUM]
### :material-button-cursor: UI/UX
#### Performance
- [x] Library Grid View
- [ ] Explore Filesystem in Grid View :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Infinite Scrolling (No Pagination) :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Library List View :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Explore Filesystem in List View :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Lightbox View :material-chevron-triple-up:{ .priority-high title="High Priority" }
- Similar to List View in concept, but displays one large preview that can cycle back/forth between entries.
- [ ] Smaller thumbnails of immediate adjacent entries below :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [x] Library Statistics Screen :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.5.4]**
- [ ] Unified Library Health/Cleanup Screen :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.5.4]**
- [x] Fix Unlinked Entries
- [x] Fix Duplicate Files
- [x] ~~Fix Duplicate Entries~~
- [ ] Remove Ignored Entries :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.5.4]**
- [ ] Delete Old Backups :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.5.5]**
- [ ] Delete Legacy JSON File :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.5.5]**
- [x] Translations
- [ ] Search Bar Rework :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.7.0]**
- [ ] Improved Tag Autocomplete :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Tags appear as widgets in search bar :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [x] Unified Media Player
- [x] Auto-Hiding Player Controls
- [x] Play/Pause
- [x] Loop
- [x] Toggle Autoplay
- [x] Volume Control
- [x] Toggle Mute
- [x] Timeline scrubber
- [ ] Fullscreen :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Fine-Tuned UI/UX :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6]**
- [ ] 3D Model Thumbnails/Previews :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] STL File Support
- [ ] OBJ File Support
- [ ] Plaintext Thumbnails/Previews :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [x] Basic Support
- [ ] Full File Preview :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Syntax Highlighting :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Toggleable Persistent Tagging Panel :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Top Tags
- [ ] Recent Tags
- [ ] Tag Search
- [ ] Pinned Tags
- [ ] New Tabbed Tag Building UI to Support New Tag Features :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Custom Thumbnail Overrides :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Media Duration Labels :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Word/Line Count Labels :material-chevron-up:{ .priority-low title="Low Priority" }
- [ ] Custom Tag Badges :material-chevron-up:{ .priority-low title="Low Priority" }
- Would serve as an addition/alternative to the Favorite and Archived badges.
- [x] Thumbnail caching [HIGH]
### :material-cog: Settings
### v9.6
- [x] Application Settings
- [x] Stored in System User Folder/Designated Folder
- [x] Language
- [x] Date and Time Format
- [x] Theme
- [x] Thumbnail Generation :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.5.4]**
- [x] Configurable Page Size
- [ ] Library Settings :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Stored in `.TagStudio` folder :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Toggle File Extension Label :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Toggle Duration Label :material-chevron-double-up:{ .priority-med title="Medium Priority" }
#### Core
### :material-puzzle: Plugin Support
- [ ] Cached file property table (media duration, word count, dimensions, etc.) [MEDIUM]
Some form of official plugin support for TagStudio, likely with its own API that may connect to or encapsulate part of the the [core library API](#core-library-api).
#### Library
- [ ] Plugin Support :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
- [ ] Multiple Root Directories per Library [HIGH]
- [ ] `.ts_ignore` (`.gitignore`-style glob ignoring) [HIGH]
- [ ] Sharable Color Packs [MEDIUM]
- [ ] Human-readable (TOML) files containing tag data [HIGH]
- [ ] Importable [HIGH]
- [ ] Exportable [HIGH]
---
#### Tags
## [Library](../library/index.md)
- [ ] Merging Tags [HIGH]
- [ ] [Component/HAS](../library/tag.md#component-tags) subtags [HIGH]
- [ ] Tag Icons [HIGH]
- [ ] Small Icons [HIGH]
- [ ] Large Icons for Profiles [MEDIUM]
- [ ] Built-in Icon Packs (i.e. Boxicons) [HIGH]
- [ ] User Defined Icons [HIGH]
- [ ] Multiple Languages for Tag Strings [MEDIUM]
- [ ] Title is tag name [HIGH]
- [ ] Title has tag color [MEDIUM]
- [ ] Tag marked as category does not display as a tag itself [HIGH]
- [ ] [Tag Overrides](../library/tag_overrides.md) [MEDIUM]
- [ ] Per-file overrides of subtags [HIGH]
### :material-wrench: Library Mechanics
#### Fields
- [x] Per-Library Tags
- [ ] Global Tags :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Multiple Root Directories :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Ability to store TagStudio library folder separate from library files :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Automatic Entry Relinking :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.7.0]**
- [ ] Detect Renames :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Detect Moves :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Detect Deletions :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Performant :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Background File Scanning :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.7.0]**
- [x] Thumbnail Caching **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [ ] Audio Waveform Caching :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.7.0]**
- [ ] Datetime fields [HIGH]
- [ ] Custom field names [HIGH]
### :material-grid: [Entries](../library/entry.md)
#### Search
Library representations of files or file-like objects.
- [ ] Field content search [HIGH]
- [ ] Sort by date created [HIGH]
- [ ] Sort by date modified [HIGH]
- [ ] Sort by filename [HIGH]
- [ ] HAS operator for composition tags [HIGH]
- [ ] Search bar rework
- [ ] Improved tag autocomplete [HIGH]
- [ ] Tags appear as widgets in search bar [HIGH]
- [x] File Entries **[v1.0.0]**
- [ ] Folder Entries :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] URL Entries / Bookmarks :material-chevron-up:{ .priority-low title="Low Priority" }
- [x] Fields
- [x] Text Lines
- [x] Text Boxes
- [x] Datetimes **[v9.5.4]**
- [ ] User-Titled Fields :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Removal of Deprecated Fields :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Entry Groups :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.7.0]**
- [ ] Non-exclusive; Entries can be in multiple groups :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Ability to number entries within group :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Ability to set sorting method for group :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Ability to set custom thumbnail for group :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Group is treated as entry with tags and metadata :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Nested groups :material-chevron-double-up:{ .priority-med title="Medium Priority" }
#### UI
### :material-tag-text: [Tags](../library/tag.md)
- [ ] File duration on video thumbnails [HIGH]
- [ ] 3D Model Previews [MEDIUM]
- [ ] STL Previews [HIGH]
- [ ] Word count/line count on text thumbnails [LOW]
- [ ] Settings Menu [HIGH]
- [ ] Application Settings [HIGH]
- [ ] Stored in system user folder/designated folder [HIGH]
- [ ] Library Settings [HIGH]
- [ ] Stored in `.TagStudio` folder [HIGH]
- [ ] Tagging Panel [HIGH]
Discrete library objects representing [attributes](<https://en.wikipedia.org/wiki/Property_(philosophy)>). Can be applied to library [entries](../library/entry.md), or applied to other tags to build traversable relationships.
Togglebale persistent main window panel or popout. Replaces the current tag manager.
- [x] Tag Name **[v8.0.0]**
- [x] Tag Shorthand Name **[v8.0.0]**
- [x] Tag Aliases List **[v8.0.0]**
- [x] Tag Color **[v8.0.0]**
- [ ] Tag Description :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.6.0]**
- [x] Tag Colors
- [x] Built-in Color Palette **[v8.0.0]**
- [x] User-Defined Colors **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Primary and Secondary Colors **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [ ] Tag Icons :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Small Icons :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Large Icons for Profiles :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.6.0]**
- [ ] Built-in Icon Packs (i.e. Boxicons) :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] User-Defined Icons :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [x] [Category Property](../library/tag_categories.md) **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Property available for tags that allow the tag and any inheriting from it to be displayed separately in the preview panel under a title
- [ ] Fine-tuned exclusion from categories :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Hidden Property :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Built-in "Archived" tag has this property by default :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Checkbox near search bar to show hidden tags in search :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Tag Relationships
- [x] [Parent Tags](../library/tag.md#parent-tags) ([Inheritance](<https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)>) Relationship) **[v9.0.0]**
- [ ] [Component Tags](../library/tag.md#component-tags) ([Composition](https://en.wikipedia.org/wiki/Object_composition) Relationship) :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Multiple Language Support :material-chevron-up:{ .priority-low title="Low Priority" } **[v9.9.0]**
- [ ] Tag Overrides :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Tag Merging :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Top Tags [HIGH]
- [ ] Recent Tags [HIGH]
- [ ] Tag Search [HIGH]
- [ ] Pinned Tags [HIGH]
### :material-magnify: [Search](../library/library_search.md)
- [ ] New tabbed tag building UI to support the new tag features [HIGH]
- [x] Tag Search **[v8.0.0]**
- [x] Filename Search **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Glob Search **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Filetype Search **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Search by Extension (e.g. ".jpg", ".png") **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Optional consolidation of extension synonyms (i.e. ".jpg" can equal ".jpeg") **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] Search by media type (e.g. "image", "video", "document") **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [ ] Field Content Search :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [x] [Boolean Operators](../library/library_search.md) **[[v9.5.0](./changelog.md#950-2025-03-03)]**
- [x] `AND` Operator
- [x] `OR` Operator
- [x] `NOT` Operator
- [x] Parenthesis Grouping
- [x] Character Escaping
- [ ] `HAS` Operator (for [Component Tags](../library/tag.md#component-tags)) :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Conditional Search :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.7.0]**
- [ ] Compare Dates :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Compare Durations :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Compare File Sizes :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Compare Dimensions :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [x] Smartcase Search [[v9.5.0](./changelog.md#950-2025-03-03)]
- [ ] Search Result Sorting
- [x] Sort by Filename **[[v9.5.2](./changelog.md#952-2025-03-31)]**
- [x] Sort by Date Entry Added to Library **[[v9.5.2](./changelog.md#952-2025-03-31)]**
- [ ] Sort by File Creation Date :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Sort by File Modification Date :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [ ] Sort by File Modification Date :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Sort by Date Taken (Photos) :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.6.0]**
- [x] Random/Shuffle Sort
- [ ] OCR Search :material-chevron-up:{ .priority-low title="Low Priority" }
- [ ] Fuzzy Search :material-chevron-up:{ .priority-low title="Low Priority" }
### v9.7
### :material-file-cog: [Macros](../utilities/macro.md)
#### Library
- [ ] Standard, Human Readable Format (TOML) :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.5.5]**
- [ ] Versioning System :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.5.5]**
- [ ] Triggers **[v9.5.5]**
- [ ] On File Added :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] On Library Refresh :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] [Entry groups](../library/entry_groups.md) [HIGH]
- [ ] Groups for files/entries where the same entry can be in multiple groups [HIGH]
- [ ] Ability to number entries within group [HIGH]
- [ ] Ability to set sorting method for group [HIGH]
- [ ] Ability to set custom thumbnail for group [HIGH]
- [ ] Group is treated as entry with tags and metadata [HIGH]
- [ ] Nested groups [MEDIUM]
#### Search
- [ ] Sort by relevance [HIGH]
- [ ] Sort by date taken (photos) [MEDIUM]
- [ ] Sort by file size [HIGH]
- [ ] Sort by file dimension (images/video) [LOW]
#### [Macros](../utilities/macro.md)
- [ ] Sharable Macros [MEDIUM]
- [ ] Standard notation format (TOML) contacting macro instructions [HIGH]
- [ ] Exportable [HIGH]
- [ ] Importable [HIGH]
- [ ] Triggers [HIGH]
- [ ] On new file [HIGH]
- [ ] On library refresh [HIGH]
- [ ] [...]
- [ ] Actions **[v9.5.5]**
- [ ] Add Tag(s) :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Add Field(s) :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Set Field Content :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Actions [HIGH]
- [ ] Add tag(s) [HIGH]
- [ ] Add field(s) [HIGH]
- [ ] Set field content [HIGH]
- [ ] [...]
### :material-table-arrow-right: Sharable Data
#### UI
Sharable TagStudio library data in the form of data packs (tags, colors, etc.) or other formats.
Packs are intended as an easy way to import and export specific data between libraries and users, while export-only formats are intended to be imported by other programs.
- [ ] Custom thumbnail overrides [MEDIUM]
- [ ] Toggle File Extension Label [MEDIUM]
- [ ] Toggle Duration Label [MEDIUM]
- [ ] Custom Tag Badges [LOW]
- [ ] Unified Media Player [HIGH]
- [ ] Auto-hiding player controls
- [x] Play/Pause [HIGH]
- [x] Loop [HIGH]
- [x] Toggle Autoplay [MEDIUM]
- [ ] Volume Control [HIGH]
- [x] Toggle Mute [HIGH]
- [ ] Timeline scrubber [HIGH]
- [ ] Fullscreen [MEDIUM]
- [ ] Library list view [HIGH]
- [ ] Configurable page size [HIGH]
- [ ] Color Packs :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.5.5]**
- [ ] Importable
- [ ] Exportable
- [x] UUIDs + Namespaces :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [x] Standard, Human Readable Format (TOML) :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Versioning System :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Tag Packs :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.9.0]**
- [ ] Importable :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Exportable :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] UUIDs + Namespaces :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Standard, Human Readable Format (TOML) :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Versioning System :material-chevron-double-up:{ .priority-med title="Medium Priority" }
- [ ] Macro Sharing :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v9.5.5]**
- [ ] Importable :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Exportable :material-chevron-triple-up:{ .priority-high title="High Priority" }
- [ ] Sharable Entry Data :material-chevron-double-up:{ .priority-med title="Medium Priority" } **[v9.9.0]**
- _Specifics of this are yet to be determined_
- [ ] Export Library to Human Readable Format :material-chevron-triple-up:{ .priority-high title="High Priority" } **[v10.0.0]**
- Intended to give users more flexible options with their data if they wish to migrate away from TagStudio
### v9.8
#### Library
- [ ] Automatic Entry Relinking [HIGH]
- [ ] Detect Renames [HIGH]
- [ ] Detect Moves [HIGH]
- [ ] Detect Deletions [HIGH]
#### Search
- [ ] OCR search [LOW]
- [ ] Fuzzy Search [LOW]
### v9.9
#### Library
- [ ] Exportable Library Data [HIGH]
- [ ] Standard notation format (i.e. JSON) contacting all library data [HIGH]
#### Tags
- [ ] Tag Packs [MEDIUM]
- [ ] Human-readable (TOML) files containing tag data [HIGH]
- [ ] Multiple Languages for Tag Strings [MEDIUM]
- [ ] Importable [HIGH]
- [ ] Exportable [HIGH]
- [ ] Conflict resolution [HIGH]
### v10.0
- [ ] All remaining [HIGH] and optional [MEDIUM] features
### Post v10.0
#### Core
- [ ] Core Library/API
- [ ] Plugin Support

View File

@@ -1,117 +1,46 @@
---
icon: material/database-edit
---
# Save Format Changes
# :material-database-edit: Save Format Changes
This page outlines the various changes made to the TagStudio library save file format over time, sometimes referred to as the "database" or "database file".
---
This page outlines the various changes made the TagStudio save file format over time, sometimes referred to as the "database" or "database file".
## JSON
Legacy (JSON) library save format versions were tied to the release version of the program itself. This number was stored in a `version` key inside the JSON file.
### Versions 1.0.0 - 9.4.2
| Used From | Used Until | Format | Location |
| --------- | ----------------------------------------------------------------------- | ------ | --------------------------------------------- |
| v1.0.0 | [v9.4.2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.4.2) | JSON | `<Library Folder>`/.TagStudio/ts_library.json |
| First Used | Last Used | Format | Location |
| ---------- | ----------------------------------------------------------------------- | ------ | --------------------------------------------- |
| v1.0.0 | [v9.4.2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.4.2) | JSON | `<Library Folder>`/.TagStudio/ts_library.json |
The legacy database format for public TagStudio releases [v9.1](https://github.com/TagStudioDev/TagStudio/tree/Alpha-v9.1) through [v9.4.2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.4.2). Variations of this format had been used privately since v1.0.0.
Replaced by the new SQLite format introduced in TagStudio [v9.5.0 Pre-Release 1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1).
---
## DB_VERSION 6
## SQLite
Starting with TagStudio [v9.5.0-pr1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1), the library save format has been moved to a [SQLite](https://sqlite.org) format. Legacy JSON libraries are migrated (with the user's consent) to the new format when opening in current versions of the program. The save format versioning is now separate from the program's versioning number.
Versions **1-100** stored the database version in a table called `preferences` in a row with the `key` column of `"DB_VERSION"` inside the corresponding `value` column.
Versions **>101** store the database version in a table called `versions` in a row with the `key` column of `'CURRENT'` inside the corresponding `value` column. The `versions` table also stores the initial database version in which the file was created with under the `'INITIAL'` key. Databases created before this key was introduced will always have `'INITIAL'` value of `100`.
```mermaid
erDiagram
versions {
TEXT key PK "Values: ['INITIAL', 'CURRENT']"
INTEGER value
}
```
### Versions 1 - 5
These versions were used while developing the new SQLite file format, outside any official or recommended release. These versions **were never supported** in any official capacity and were actively warned against using for real libraries.
---
### Version 6
| Used From | Used Until | Format | Location |
| First Used | Last Used | Format | Location |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| [v9.5.0-pr1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1) | [v9.5.0-pr1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
| [v9.5.0-PR1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1) | [v9.5.0-PR1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
The first public version of the SQLite save file format.
Migration from the legacy JSON format is provided via a walkthrough when opening a legacy library in TagStudio [v9.5.0 Pre-Release 1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr1) or later.
---
## DB_VERSION 7
### Version 7
| Used From | Used Until | Format | Location |
| First Used | Last Used | Format | Location |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| [v9.5.0-pr2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr2) | [v9.5.0-pr3](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr3) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
| [v9.5.0-PR2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr2) | [v9.5.0-PR3](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr3) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
### Changes
- Repairs "Description" fields to use a TEXT_LINE key instead of a TEXT_BOX key.
- Repairs tags that may have a disambiguation_id pointing towards a deleted tag.
---
## DB_VERSION 8
### Version 8
| First Used | Last Used | Format | Location |
| ------------------------------------------------------------------------------- | --------- | ------ | ----------------------------------------------- |
| [v9.5.0-PR4](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr4) | _Current_ | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
| Used From | Used Until | Format | Location |
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| [v9.5.0-pr4](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.0-pr4) | [v9.5.1](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.1) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
### Changes
- Adds the `color_border` column to the `tag_colors` table. Used for instructing the [secondary color](../library/tag_color.md#secondary-color) to apply to a tag's border as a new optional behavior.
- Adds the `color_border` column to `tag_colors` table. Used for instructing the [secondary color](../library/tag_color.md#secondary-color) to apply to a tag's border as a new optional behavior.
- Adds three new default colors: "Burgundy (TagStudio Shades)", "Dark Teal (TagStudio Shades)", and "Dark Lavender (TagStudio Shades)".
- Updates Neon colors to use the new `color_border` property.
---
### Version 9
| Used From | Used Until | Format | Location |
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| [v9.5.2](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.2) | [v9.5.3](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.3) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
- Adds the `filename` column to the `entries` table. Used for sorting entries by filename in search results.
---
### Version 100
| Used From | Used Until | Format | Location |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| [74383e3](https://github.com/TagStudioDev/TagStudio/commit/74383e3c3c12f72be1481ab0b86c7360b95c2d85) | [v9.5.4](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.4) | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
- Introduces built-in minor versioning
- The version number divided by 100 (and floored) constitutes the **major** version. Major version indicate breaking changes that prevent libraries from being opened in TagStudio versions older than the ones they were created in.
- Values more precise than this ("ones" through "tens" columns) constitute the **minor** version. These indicate minor changes that don't prevent a newer library from being opened in an older version of TagStudio, as long as the major version is not also increased.
- Swaps `parent_id` and `child_id` values in the `tag_parents` table, which have erroneously been flipped since the first SQLite DB version.
#### Version 101
| Used From | Used Until | Format | Location |
| ----------------------------------------------------------------------- | ---------- | ------ | ----------------------------------------------- |
| [v9.5.4](https://github.com/TagStudioDev/TagStudio/releases/tag/v9.5.4) | _Current_ | SQLite | `<Library Folder>`/.TagStudio/ts_library.sqlite |
- Deprecates the `preferences` table, set to be removed in a future TagStudio version.
- Introduces the `versions` table
- Has a string `key` column and an int `value` column
- The `key` column stores one of two values: `'INITIAL'` and `'CURRENT'`
- `'INITIAL'` stores the database version number in which in was created
- Pre-existing databases set this number to `100`
- `'CURRENT'` stores the current database version number

View File

@@ -1,8 +1,4 @@
---
icon: material/mouse
---
# :material-mouse: Usage
# Usage
## Creating/Opening a Library
@@ -16,7 +12,7 @@ Libraries under 10,000 files automatically scan for new or modified files when o
Access the "Add Tag" search box by either clicking on the "Add Tag" button at the bottom of the right sidebar, accessing the "Add Tags to Selected" option from the File menu, or by pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>T</kbd>.
From here you can search for existing tags or create a new one if the one you're looking for doesn't exist. Click the "+" button next to any tags you want to the currently selected file entries. To quickly add the top result, press the <kbd>Enter</kbd>/<kbd>Return</kbd> key to add the topmost tag and reset the tag search. Press <kbd>Enter</kbd>/<kbd>Return</kbd> once more to close the dialog box. By using this method, you can quickly add various tags in quick succession just by using the keyboard!
From here you can search for existing tags or create a new one if the one you're looking for doesn't exist. Click the "+" button next to any tags you want to the currently selected file entries. To quickly add the top result, press the <kbd>Enter</kbd>/<kbd>Return</kbd> key to add the the topmost tag and reset the tag search. Press <kbd>Enter</kbd>/<kbd>Return</kbd> once more to close the dialog box. By using this method, you can quickly add various tags in quick succession just by using the keyboard!
To remove a tag from a file entry, hover over the tag in the preview panel and click on the "-" icon that appears.
@@ -45,7 +41,7 @@ Create a new tag by accessing the "New Tag" option from the Edit menu or by pres
### Tag Manager
You can manage your library of tags by opening the "Tag Manager" panel from Edit -> "Manage Tags". From here you can create, search for, edit, and permanently delete any tags you've created in your library.
You can manage your library of tags from opening the "Tag Manager" panel from Edit -> "Manage Tags". From here you can create, search for, edit, and permanently delete any tags you've created in your library.
## Editing Tags
@@ -66,14 +62,3 @@ Inevitably some of the files inside your library will be renamed, moved, or dele
### Saving the Library
As of version 9.5, libraries are saved automatically as you go. To save a backup of your library, select File -> Save Library Backup from the menu bar.
## Launch Arguments
There are a handful of launch arguments you can pass to TagStudio via the command line or a desktop shortcut.
| Argument | Short | Description |
| ------------------------ | ----- | ------------------------------------------------------ |
| `--cache-file <path>` | `-c` | Path to a TagStudio .ini or .plist cache file to use. |
| `--open <path>` | `-o` | Path to a TagStudio Library folder to open on start. |
| `--settings-file <path>` | `-s` | Path to a TagStudio .toml global settings file to use. |
| `--version` | `-v` | Displays TagStudio version information. |

View File

@@ -1,322 +0,0 @@
---
title: Ignore Files
icon: material/file-document-remove
---
# :material-file-document-remove: Ignore Files & Directories
<!-- prettier-ignore -->
!!! warning "Legacy File Extension Ignoring"
TagStudio versions prior to v9.5.4 use a different, more limited method to exclude or include file extensions from your library and subsequent searches. Opening a pre-exiting library in v9.5.4 or later will non-destructively convert this to the newer, more extensive `.ts_ignore` format.
If you're still running an older version of TagStudio in the meantime, you can access the legacy system by going to "Edit -> Manage File Extensions" in the menubar.
TagStudio offers the ability to ignore specific files and directories via a `.ts_ignore` file located inside your [library's](../library/index.md) `.TagStudio` folder. This file is designed to use very similar [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>)-style pattern matching as the [`.gitignore`](https://git-scm.com/docs/gitignore) file used by Git™[^1]. It can be edited within TagStudio or opened to edit with an external program by going to the "Edit -> Ignore Files" option in the menubar.
This file is only referenced when scanning directories for new files to add to your library, and does not apply to files that have already been added to your library.
<!-- prettier-ignore -->
!!! tip
If you just want some specific examples of how to achieve common tasks with the ignore patterns (e.g. ignoring a single file type, ignoring a specific folder) then jump to the "[Use Cases](#use-cases)" section!
<!-- prettier-ignore-start -->
=== "Example .ts_ignore file"
```toml title="My Library/.TagStudio/.ts_ignore"
# TagStudio .ts_ignore file.
# Code
__pycache__
.pytest_cache
.venv
.vs
# Projects
Minecraft/**/Metadata
Minecraft/Website
!Minecraft/Website/*.png
!Minecraft/Website/*.css
# Documents
*.doc
*.docx
*.ppt
*.pptx
*.xls
*.xlsx
```
<!-- prettier-ignore-end -->
## Pattern Format
<!-- prettier-ignore -->
!!! note ""
_This section sourced and adapted from Git's[^1] `.gitignore` [documentation](https://git-scm.com/docs/gitignore)._
### Internal Processes
When scanning your library directories, the `.ts_ignore` file is read by either the [`wcmatch`](https://facelessuser.github.io/wcmatch/glob/) library or [`ripgrep`](https://github.com/BurntSushi/ripgrep) in glob mode depending if you have the later installed on your system and it's detected by TagStudio. Ripgrep is the preferred method for scanning directories due to its improved performance and identical pattern matching to `.gitignore`. This mixture of tools may lead to slight inconsistencies if not using `ripgrep`.
---
### Comments ( `#` )
A `#` symbol at the start of a line indicates that this line is a comment, and match no items. Blank lines are used to enhance readability and also match no items.
- Can be escaped by putting a backslash ("`\`") in front of the `#` symbol.
<!-- prettier-ignore-start -->
=== "Example comment"
```toml
# This is a comment! I can say whatever I want on this line.
file_that_is_being_matched.txt
# file_that_is_NOT_being_matched.png
file_that_is_being_matched.png
```
=== "Organizing with comments"
```toml
# TagStudio .ts_ignore file.
# Minecraft Stuff
Minecraft/**/Metadata
Minecraft/Website
!Minecraft/Website/*.png
!Minecraft/Website/*.css
# Microsoft Office
*.doc
*.docx
*.ppt
*.pptx
*.xls
*.xlsx
```
=== "Escape a # symbol"
```toml
# To ensure a file named '#hashtag.jpg' is ignored:
\#hashtag.jpg
```
<!-- prettier-ignore-end -->
---
### Directories ( `/` )
The forward slash "`/`" is used as the directory separator. Separators may occur at the beginning, middle or end of the `.ts_ignore` search pattern.
- If there is a separator at the beginning or middle (or both) of the pattern, then the pattern is relative to the directory level of the particular `.TagStudio` library folder itself. Otherwise the pattern may also match at any level below the `.TagStudio` folder level.
- If there is a separator at the end of the pattern then the pattern will only match directories, otherwise the pattern can match both files and directories.
<!-- prettier-ignore-start -->
=== "Example folder pattern"
```toml
# Matches "frotz" and "a/frotz" if they are directories.
frotz/
```
=== "Example nested folder pattern"
```toml
# Matches "doc/frotz" but not "a/doc/frotz".
doc/frotz/
```
<!-- prettier-ignore-end -->
---
### Negation ( `!` )
A `!` prefix before a pattern negates the pattern, allowing any files matched matched by previous patterns to be un-matched.
- Any matching file excluded by a previous pattern will become included again.
- **It is not possible to re-include a file if a parent directory of that file is excluded.**
<!-- prettier-ignore-start -->
=== "Example negation"
```toml
# All .jpg files will be ignored, except any located in the 'Photos' folder.
*.jpg
Photos/!*.jpg
```
=== "Escape a ! Symbol"
```toml
# To ensure a file named '!wowee.jpg' is ignored:
\!wowee.jpg
```
<!-- prettier-ignore-end -->
---
### Wildcards
#### Single Asterisks ( `*` )
An asterisk "`*`" matches anything except a slash.
<!-- prettier-ignore-start -->
=== "File examples"
```toml
# Matches all .png files in the "Images" folder.
Images/*.png
# Matches all .png files in all folders
*.png
```
=== "Folder examples"
```toml
# Matches any files or folders directly in "Images/" but not deeper levels.
# Matches file "Images/mario.jpg"
# Matches folder "Images/Mario"
# Does not match file "Images/Mario/cat.jpg"
Images/*
```
<!-- prettier-ignore-end -->
#### Question Marks ( `?` )
The character "`?`" matches any one character except "`/`".
<!-- prettier-ignore-start -->
=== "File examples"
```toml
# Matches any .png file starting with "IMG_" and ending in any four characters.
# Matches "IMG_0001.png"
# Matches "Photos/IMG_1234.png"
# Does not match "IMG_1.png"
IMG_????.png
# Same as above, except matches any file extension instead of only .png
IMG_????.*
```
=== "Folder examples"
```toml
# Matches all files in any direct subfolder of "Photos" beginning in "20".
# Matches "Photos/2000"
# Matches "Photos/2024"
# Matches "Photos/2099"
# Does not match "Photos/1995"
Photos/20??/
```
<!-- prettier-ignore-end -->
#### Double Asterisks ( `**` )
Two consecutive asterisks ("`**`") in patterns matched against full pathname may have special meaning:
- A leading "`**`" followed by a slash means matches in all directories.
- A trailing "`/**`" matches everything inside.
- A slash followed by two consecutive asterisks then a slash ("`/**/`") matches zero or more directories.
- Other consecutive asterisks are considered regular asterisks and will match according to the previous rules.
<!-- prettier-ignore-start -->
=== "Leading **"
```toml
# Both match file or directory "foo" anywhere
**/foo
foo
# Matches file or directory "bar" anywhere that is directly under directory "foo"
**/foo/bar
```
=== "Trailing /**"
```toml
# Matches all files inside directory "abc" with infinite depth.
abc/**
```
=== "Middle /**/"
```toml
# Matches "a/b", "a/x/b", "a/x/y/b" and so on.
a/**/b
```
<!-- prettier-ignore-end -->
#### Square Brackets ( `[a-Z]` )
Character sets and ranges are specific and powerful forms of wildcards that use characters inside of brackets (`[]`) to leverage very specific matching. The range notation, e.g. `[a-zA-Z]`, can be used to match one of the characters in a range.
<!-- prettier-ignore -->
!!! tip
For more in-depth examples and explanations on how to use ranges, please reference the [`glob`](https://man7.org/linux/man-pages/man7/glob.7.html) man page.
<!-- prettier-ignore-start -->
=== "Range examples"
```toml
# Matches all files that start with "IMG_" and end in a single numeric character.
# Matches "IMG_0.jpg", "IMG_7.png"
# Does not match "IMG_10.jpg", "IMG_A.jpg"
IMG_[0-9]
# Matches all files that start with "IMG_" and end in a single alphabetic character
IMG_[a-z]
```
=== "Set examples"
```toml
# Matches all files that start with "IMG_" and in any character in the set.
# Matches "draft_a.docx", "draft_b.docx", "draft_c.docx"
# Does not match "draft_d.docx"
draft_[abc]
# Matches all files that start with "IMG_" and end in a single alphabetic character
IMG_[a-z]
```
<!-- prettier-ignore-end -->
---
## Use Cases
### Ignoring Files by Extension
<!-- prettier-ignore -->
=== "Ignore all .jpg files"
```toml
*.jpg
```
=== "Ignore all files EXCEPT .jpg files"
```toml
*
!*.jpg
```
=== "Ignore all .jpg files in specific folders"
```toml
./Photos/Worst Vacation/*.jpg
Music/Artwork Art/*.jpg
```
<!-- prettier-ignore -->
!!! tip "Ensuring Complete Extension Matches"
For some filetypes, it may be nessisary to specify different casing and alternative spellings in order to match with all possible variations of an extension in your library.
```toml title="Ignore (Most) Possible JPEG File Extensions"
# The JPEG Cinematic Universe
*.jpg
*.jpeg
*.jfif
*.jpeg_large
*.JPG
*.JPEG
*.JFIF
*.JPEG_LARGE
```
### Ignoring a Folder
<!-- prettier-ignore -->
=== "Ignore all "Cache" folders"
```toml
# Matches any folder called "Cache" no matter where it is in your library.
cache/
```
=== "Ignore a "Downloads" folder"
```toml
# "Downloads" must be a folder on the same level as your ".TagStudio" folder.
# Does not match with folders name "Downloads" elsewhere in your library
# Does not match with a file called "Downloads"
/Downloads/
```
=== "Ignore .jpg files in specific folders"
```toml
Photos/Worst Vacation/*.jpg
/Music/Artwork Art/*.jpg
```
[^1]: The term "Git" is a licensed trademark of "The Git Project", a member of the Software Freedom Conservancy. Git is released under the [GNU General Public License version 2.0](https://opensource.org/license/GPL-2.0), an open source license. TagStudio is not associated with the Git Project, only including systems based on some therein.

View File

@@ -1,8 +1,4 @@
---
icon: material/script-text
---
# :material-script-text: Tools & Macros
# Tools & Macros
Tools and macros are features that serve to create a more fluid [library](../library/index.md)-managing process, or provide some extra functionality. Please note that some are still in active development and will be fleshed out in future updates.
@@ -39,11 +35,11 @@ This tool is a preview of an upcoming feature. When selected, TagStudio will gen
### Auto-fill [WIP]
Tool is in development and will be documented in a future update.
Tool is in development and will be documented in future update.
### Sort fields
Tool is in development. Will allow for user-defined sorting of [fields](../library/field.md).
Tool is in development, will allow for user-defined sorting of [fields](../library/field.md).
### Folders to Tags

29
flake.lock generated
View File

@@ -7,11 +7,11 @@
]
},
"locked": {
"lastModified": 1754487366,
"narHash": "sha256-pHYj8gUBapuUzKV/kN/tR3Zvqc7o6gdFB9XKXIp1SQ8=",
"lastModified": 1725024810,
"narHash": "sha256-ODYRm8zHfLTH3soTFWE452ydPYz2iTvr9T8ftDMUQ3E=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "af66ad14b28a127c5c0f3bbb298218fc63528a18",
"rev": "af510d4a62d071ea13925ce41c95e3dec816c01d",
"type": "github"
},
"original": {
@@ -22,11 +22,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1755615617,
"narHash": "sha256-HMwfAJBdrr8wXAkbGhtcby1zGFvs+StOp19xNsbqdOg=",
"lastModified": 1741173522,
"narHash": "sha256-k7VSqvv0r1r53nUI/IfPHCppkUAddeXn843YlAC5DR0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "20075955deac2583bb12f07151c2df830ef346b4",
"rev": "d69ab0d71b22fa1ce3dbeff666e6deb4917db049",
"type": "github"
},
"original": {
@@ -36,10 +36,27 @@
"type": "github"
}
},
"nixpkgs-qt6": {
"locked": {
"lastModified": 1734856068,
"narHash": "sha256-Q+CB1ajsJg4Z9HGHTBAGY1q18KpnnkmF/eCTLUY6FQ0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "93ff48c9be84a76319dac293733df09bbbe3f25c",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "93ff48c9be84a76319dac293733df09bbbe3f25c",
"type": "github"
}
},
"root": {
"inputs": {
"flake-parts": "flake-parts",
"nixpkgs": "nixpkgs",
"nixpkgs-qt6": "nixpkgs-qt6",
"systems": "systems"
}
},

View File

@@ -9,6 +9,8 @@
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nixpkgs-qt6.url = "github:NixOS/nixpkgs/93ff48c9be84a76319dac293733df09bbbe3f25c";
systems.url = "github:nix-systems/default";
};
@@ -27,30 +29,27 @@
perSystem =
{ pkgs, ... }:
let
python3 = pkgs.python312;
in
{
packages =
let
python3Packages = python3.pkgs;
python = pkgs.python312Packages;
pillow-jxl-plugin = python3Packages.callPackage ./nix/package/pillow-jxl-plugin.nix {
pillow-jxl-plugin = python.callPackage ./nix/package/pillow-jxl-plugin.nix {
inherit (pkgs) cmake;
inherit pyexiv2;
inherit (pkgs) rustPlatform;
};
pyexiv2 = python3Packages.callPackage ./nix/package/pyexiv2.nix { inherit (pkgs) exiv2; };
pyexiv2 = python.callPackage ./nix/package/pyexiv2.nix { inherit (pkgs) exiv2; };
vtf2img = python.callPackage ./nix/package/vtf2img.nix { };
in
rec {
default = tagstudio;
tagstudio = pkgs.callPackage ./nix/package {
inherit python3Packages;
inherit pillow-jxl-plugin;
tagstudio = pkgs.python312Packages.callPackage ./nix/package {
inherit pillow-jxl-plugin vtf2img;
};
tagstudio-jxl = tagstudio.override { withJXLSupport = true; };
inherit pillow-jxl-plugin pyexiv2;
inherit pillow-jxl-plugin pyexiv2 vtf2img;
};
devShells = rec {
@@ -61,8 +60,6 @@
lib
pkgs
self
python3
;
};
};

View File

@@ -9,7 +9,6 @@
# To run the preview server:
# mkdocs serve
---
site_name: TagStudio
site_description: "A User-Focused Photo & File Management System"
site_url: https://docs.tagstud.io/
@@ -26,59 +25,58 @@ extra:
tags:
Upcoming Feature: upcoming
nav:
- Home:
- index.md
- install.md
- usage.md
- develop.md
- Help:
- help/ffmpeg.md
- Library:
- library/index.md
- library/library_search.md
- library/entry.md
- library/field.md
- library/tag.md
- library/tag_categories.md
- library/tag_color.md
- Utilities:
- utilities/ignore.md
- utilities/macro.md
- Updates:
- updates/changelog.md
- updates/roadmap.md
- updates/schema_changes.md
# by default the navigation is an alphanumerically sorted,
# nested list of all the Markdown files found within the /docs directory
# where index files are always first
# uncomment the following to configure the navigation manually:
# nav:
# - Home:
# - index.md
# - install.md
# - usage.md
# - Library:
# - library/index.md
# - library/entry.md
# - library/entry_groups.md
# - library/field.md
# - library/tag.md
# - library/tag_categories.md
# - library/tag_overrides.md
# - Utilities:
# - utilities/macro.md
# - Updates:
# - updates/changelog.md
# - updates/roadmap.md
# - updates/db_migration.md
theme:
name: material
custom_dir: overrides
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/lightbulb-auto-outline
name: Switch to Light Mode
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
- media: "(prefers-color-scheme: light)"
scheme: default
primary: purple
accent: purple
primary: deep purple
accent: deep purple
toggle:
icon: material/lightbulb
name: Switch to Dark Mode
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: purple
accent: purple
primary: deep purple
accent: deep purple
toggle:
icon: material/lightbulb-night-outline
name: Switch to System Preference
logo: assets/icon_mono.svg
icon: material/brightness-4
name: SSwitch to system preference
logo: assets/icon.png
favicon: assets/icon.ico
font:
code: Jetbrains Mono
font: false # use system fonts
language: en
features:
- navigation.instant
@@ -86,11 +84,13 @@ theme:
- navigation.tracking
- navigation.expand
- navigation.sections
#- navigation.tabs
#- content.tabs.link
#- navigation.top
- search.suggest
- content.code.annotate
- content.code.copy
- content.action.edit
- content.tooltips
icon:
repo: fontawesome/brands/github
tag:
@@ -105,7 +105,6 @@ markdown_extensions:
- def_list
- footnotes
- md_in_html
- tables
- toc:
permalink: true
@@ -116,15 +115,11 @@ markdown_extensions:
smart_enable: all
- pymdownx.caret
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
- pymdownx.highlight
- pymdownx.inlinehilite
- pymdownx.keys
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.snippets
- pymdownx.superfences:
custom_fences:
- name: mermaid
@@ -140,9 +135,8 @@ markdown_extensions:
plugins:
- search
- tags
- social: # social embed cards
enabled: !ENV [CI, false] # enabled only when running in CI (eg GitHub Actions)
- social: # social embed cards
enabled: !ENV [CI, false] # enabled only when running in CI (eg GitHub Actions)
extra_css:
- stylesheets/extra.css
- https://fonts.googleapis.com/css2?family=Bai+Jamjuree:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700&display=swap

View File

@@ -1,14 +1,33 @@
{
buildPythonApplication,
chardet,
ffmpeg-headless,
ffmpeg-python,
hatchling,
humanfriendly,
lib,
pipewire,
python3Packages,
qt6,
ripgrep,
stdenv,
wrapGAppsHook,
mutagen,
numpy,
opencv-python,
pillow,
pillow-heif,
pillow-jxl-plugin,
pipewire,
pydub,
pyside6,
pytest-qt,
pytest-xdist,
pytestCheckHook,
pythonRelaxDepsHook,
qt6,
rawpy,
send2trash,
sqlalchemy,
stdenv,
structlog,
syrupy,
ujson,
vtf2img,
withJXLSupport ? false,
}:
@@ -16,7 +35,7 @@
let
pyproject = (lib.importTOML ../../pyproject.toml).project;
in
python3Packages.buildPythonApplication {
buildPythonApplication {
pname = pyproject.name;
inherit (pyproject) version;
pyproject = true;
@@ -24,110 +43,64 @@ python3Packages.buildPythonApplication {
src = ../../.;
nativeBuildInputs = [
python3Packages.pythonRelaxDepsHook
pythonRelaxDepsHook
qt6.wrapQtAppsHook
# Should be unnecessary once PR is pulled.
# PR: https://github.com/NixOS/nixpkgs/pull/271037
# Issue: https://github.com/NixOS/nixpkgs/issues/149812
wrapGAppsHook
];
buildInputs = [
qt6.qtbase
qt6.qtmultimedia
];
nativeCheckInputs = with python3Packages; [
nativeCheckInputs = [
pytest-qt
pytest-xdist
pytestCheckHook
syrupy
];
# TODO: Install more icon resolutions when available.
preInstall = ''
mkdir -p $out/share/applications $out/share/icons/hicolor/512x512/apps
makeWrapperArgs =
[ "--prefix PATH : ${lib.makeBinPath [ ffmpeg-headless ]}" ]
++ lib.optional stdenv.hostPlatform.isLinux "--prefix LD_LIBRARY_PATH : ${
lib.makeLibraryPath [ pipewire ]
}";
cp $src/src/tagstudio/resources/tagstudio.desktop $out/share/applications
cp $src/src/tagstudio/resources/icon.png $out/share/icons/hicolor/512x512/apps/tagstudio.png
'';
dontWrapGApps = true;
dontWrapQtApps = true;
makeWrapperArgs = [
"--prefix PATH : ${
lib.makeBinPath [
ffmpeg-headless
ripgrep
]
}"
]
++ lib.optional stdenv.hostPlatform.isLinux "--prefix LD_LIBRARY_PATH : ${
lib.makeLibraryPath [ pipewire ]
}"
++ [
"\${gappsWrapperArgs[@]}"
"\${qtWrapperArgs[@]}"
];
pythonRemoveDeps = lib.optional (!withJXLSupport) [ "pillow_jxl" ];
pythonRelaxDeps = [
"numpy"
"pillow"
"pillow-avif-plugin"
"pillow-heif"
"pillow-jxl-plugin"
"pyside6"
"structlog"
"typing-extensions"
];
pythonRemoveDeps = true;
pythonImportsCheck = [ "tagstudio" ];
build-system = with python3Packages; [ hatchling ];
dependencies =
with python3Packages;
[
chardet
ffmpeg-python
humanfriendly
mutagen
numpy
opencv-python
pillow
pillow-avif-plugin
pillow-heif
pydantic
pydub
pyside6
rawpy
send2trash
sqlalchemy
srctools
structlog
toml
ujson
wcmatch
]
++ lib.optional withJXLSupport pillow-jxl-plugin;
build-system = [ hatchling ];
dependencies = [
chardet
ffmpeg-python
humanfriendly
mutagen
numpy
opencv-python
pillow
pillow-heif
pydub
pyside6
rawpy
send2trash
sqlalchemy
structlog
ujson
vtf2img
] ++ lib.optional withJXLSupport pillow-jxl-plugin;
# These tests require modifications to a library, which does not work
# INFO: These tests require modifications to a library, which does not work
# in a read-only environment.
disabledTests = [
"test_badge_visual_state"
"test_browsing_state_update"
"test_flow_layout_happy_path"
"test_build_tag_panel_add_alias_callback"
"test_build_tag_panel_add_aliases"
"test_build_tag_panel_add_sub_tag_callback"
"test_build_tag_panel_build_tag"
"test_build_tag_panel_remove_alias_callback"
"test_build_tag_panel_remove_subtag_callback"
"test_build_tag_panel_set_aliases"
"test_build_tag_panel_set_parent_tags"
"test_build_tag_panel_set_tag"
"test_json_migration"
"test_library_migrations"
"test_update_tags"
];
disabledTestPaths = [
"tests/qt/test_build_tag_panel.py"
"tests/qt/test_field_containers.py"
"tests/qt/test_file_path_options.py"
"tests/qt/test_preview_panel.py"
"tests/qt/test_tag_panel.py"
"tests/qt/test_tag_search_panel.py"
"tests/test_library.py"
];
meta = {

View File

@@ -13,18 +13,18 @@
buildPythonPackage rec {
pname = "pillow-jxl-plugin";
version = "1.3.4";
version = "1.3.2";
pyproject = true;
src = fetchPypi {
pname = "pillow_jxl_plugin";
pname = builtins.replaceStrings [ "-" ] [ "_" ] pname;
inherit version;
hash = "sha256-jqWJ/FWep8XfzLQq9NgUj121CPX01FGDKLq1ox/LJo4=";
hash = "sha256-efBoek8yUFR+ArhS55lm9F2XhkZ7/I3GsScQEe8U/2I=";
};
cargoDeps = rustPlatform.fetchCargoVendor {
inherit src;
hash = "sha256-7j+sCn+P6q6tsm2MJ/cM7hF2KEjILJNA6SDb35tecPg=";
hash = "sha256-vZHrwGfgo3fIIOY7p0vy4XIKiHoddPDdJggkBen+w/A=";
};
nativeBuildInputs = [
@@ -39,9 +39,9 @@ buildPythonPackage rec {
pytestCheckHook
];
# Working directory takes precedence in the Python path. Remove
# INFO: Working directory takes precedence in the Python path. Remove
# `pillow_jxl` to prevent it from being loaded during pytest, rather than the
# built module, as it includes a `pillow_jxl.pillow_jxl.so` that is imported.
# built module, as it includes a `pillow_jxl.pillow_jxl` .so that is imported.
# See: https://github.com/NixOS/nixpkgs/issues/255262
# See: https://github.com/NixOS/nixpkgs/pull/255471
preCheck = ''
@@ -58,9 +58,8 @@ buildPythonPackage rec {
];
meta = {
description = "Pillow plugin for JPEG-XL, using Rust for bindings";
description = "Pillow plugin for JPEG-XL, using Rust for bindings.";
homepage = "https://github.com/Isotr0py/pillow-jpegxl-plugin";
changelog = "https://github.com/Isotr0py/pillow-jpegxl-plugin/releases/tag/v${version}";
license = lib.licenses.gpl3;
maintainers = with lib.maintainers; [ xarvex ];
platforms = lib.platforms.unix;

View File

@@ -4,18 +4,16 @@
exiv2,
fetchFromGitHub,
lib,
setuptools,
}:
buildPythonPackage rec {
pname = "pyexiv2";
version = "2.15.3";
pyproject = true;
src = fetchFromGitHub {
owner = "LeoHsiao1";
repo = "pyexiv2";
tag = "v${version}";
repo = pname;
rev = "v${version}";
hash = "sha256-83bFMaoXncvhRJNcCgkkC7B29wR5pjuLO/EdkQdqxxo=";
};
@@ -24,12 +22,9 @@ buildPythonPackage rec {
pythonImportsCheck = [ "pyexiv2" ];
build-system = [ setuptools ];
meta = {
description = "Read and write image metadata, including EXIF, IPTC, XMP, ICC Profile";
description = "Read and write image metadata, including EXIF, IPTC, XMP, ICC Profile.";
homepage = "https://github.com/LeoHsiao1/pyexiv2";
changelog = "https://github.com/LeoHsiao1/pyexiv2/releases/tag/v${version}";
license = lib.licenses.gpl3;
maintainers = with lib.maintainers; [ xarvex ];
platforms = with lib.platforms; darwin ++ linux ++ windows;

29
nix/package/vtf2img.nix Normal file
View File

@@ -0,0 +1,29 @@
{
buildPythonPackage,
fetchPypi,
lib,
pillow,
}:
buildPythonPackage rec {
pname = "vtf2img";
version = "0.1.0";
src = fetchPypi {
inherit pname version;
hash = "sha256-YmWs8673d72wH4nTOXP4AFGs2grIETln4s1MD5PfE0A=";
};
pythonImportsCheck = [ "vtf2img" ];
dependencies = [ pillow ];
meta = {
description = "A Python library to convert Valve Texture Format (VTF) files to images.";
homepage = "https://github.com/julienc91/vtf2img";
license = lib.licenses.mit;
maintainers = with lib.maintainers; [ xarvex ];
mainProgram = "vtf2img";
platforms = lib.platforms.unix;
};
}

View File

@@ -1,125 +1,89 @@
{
inputs,
lib,
pkgs,
python3,
...
}:
let
pythonLibraryPath =
with pkgs;
lib.makeLibraryPath (
[
fontconfig
freetype
glib
qt6.qtbase
stdenv.cc.cc
zstd
]
++ lib.optionals (!stdenv.isDarwin) [
dbus
qt6Pkgs = import inputs.nixpkgs-qt6 { inherit (pkgs) system; };
pythonLibraryPath = lib.makeLibraryPath (
(with pkgs; [
fontconfig.lib
freetype
glib
stdenv.cc.cc.lib
zstd
])
++ (with qt6Pkgs.qt6; [ qtbase ])
++ lib.optionals (!pkgs.stdenv.isDarwin) (
(with pkgs; [
dbus.lib
libGL
libdrm
libpulseaudio
libva
libxkbcommon
pipewire
qt6.qtwayland
xorg.libX11
xorg.libXrandr
]
);
])
++ (with qt6Pkgs.qt6; [ qtwayland ])
)
);
libraryPath = "${lib.optionalString pkgs.stdenv.isDarwin "DY"}LD_LIBRARY_PATH";
python3Wrapped = pkgs.symlinkJoin {
inherit (python3)
python = pkgs.python312;
pythonWrapped = pkgs.symlinkJoin {
inherit (python)
name
pname
version
meta
;
paths = [ python3 ];
paths = [ python ];
nativeBuildInputs = with pkgs; [
makeWrapper
qt6.wrapQtAppsHook
# Should be unnecessary once PR is pulled.
# PR: https://github.com/NixOS/nixpkgs/pull/271037
# Issue: https://github.com/NixOS/nixpkgs/issues/149812
wrapGAppsHook
];
buildInputs = with pkgs.qt6; [
qtbase
qtmultimedia
];
nativeBuildInputs = (with pkgs; [ makeWrapper ]) ++ (with qt6Pkgs.qt6; [ wrapQtAppsHook ]);
buildInputs = with qt6Pkgs.qt6; [ qtbase ];
postBuild = ''
wrapProgram $out/bin/${python3.meta.mainProgram} \
wrapProgram $out/bin/python3.12 \
--prefix ${libraryPath} : ${pythonLibraryPath} \
"''${gappsWrapperArgs[@]}" \
"''${qtWrapperArgs[@]}"
'';
dontWrapGApps = true;
dontWrapQtApps = true;
};
in
pkgs.mkShellNoCC {
nativeBuildInputs = with pkgs; [
coreutils
uv
ruff
];
buildInputs = [
python3Wrapped
]
++ (with pkgs; [
ffmpeg-headless
ripgrep
]);
buildInputs = [ pythonWrapped ] ++ (with pkgs; [ ffmpeg-headless ]);
env = {
QT_QPA_PLATFORM = "wayland;xcb";
UV_NO_SYNC = "1";
UV_PYTHON_DOWNLOADS = "never";
};
env.QT_QPA_PLATFORM = "wayland;xcb";
shellHook =
let
python = lib.getExe python3Wrapped;
# PySide/Qt are very particular about matching versions. Override with nixpkgs package.
pythonPath = lib.makeSearchPathOutput "lib" python3.sitePackages (
with python3.pkgs; [ pyside6 ] ++ pyside6.propagatedBuildInputs or [ ]
);
python = lib.getExe pythonWrapped;
in
# bash
''
venv=''${UV_PROJECT_ENVIRONMENT:-.venv}
if [ ! -f "''${venv}"/bin/activate ] || [ "$(readlink -f "''${venv}"/bin/python)" != "$(readlink -f ${python})" ]; then
if [ ! -f .venv/bin/activate ] || [ "$(readlink -f .venv/bin/python)" != "$(readlink -f ${python})" ]; then
printf '%s\n' 'Regenerating virtual environment, Python interpreter changed...' >&2
rm -rf "''${venv}"
uv venv --python ${python} "''${venv}"
rm -rf .venv
${python} -m venv .venv
fi
source "''${venv}"/bin/activate
PYTHONPATH=${pythonPath}''${PYTHONPATH:+:}''${PYTHONPATH:-}
source .venv/bin/activate
if [ ! -f "''${venv}"/pyproject.toml ] || ! diff --brief pyproject.toml "''${venv}"/pyproject.toml >/dev/null; then
if [ ! -f .venv/pyproject.toml ] || [ "$(cat .venv/pyproject.toml)" != "$(cat pyproject.toml)" ]; then
printf '%s\n' 'Installing dependencies, pyproject.toml changed...' >&2
uv pip install --quiet --editable '.[mkdocs,mypy,pre-commit,pytest]'
cp pyproject.toml "''${venv}"/pyproject.toml
pip install --quiet --editable '.[mkdocs,mypy,pytest]'
cp pyproject.toml .venv/pyproject.toml
fi
pre-commit install
'';
meta = {

View File

@@ -1,122 +0,0 @@
<!--
Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
-->
<!-- Determine classes -->
{% set class = "md-header" %}
{% if "navigation.tabs.sticky" in features %}
{% set class = class ~ " md-header--shadow md-header--lifted" %}
{% elif "navigation.tabs" not in features %}
{% set class = class ~ " md-header--shadow" %}
{% endif %}
<!-- Header -->
<header class="{{ class }}" data-md-component="header">
<nav
class="md-header__inner md-grid"
aria-label="{{ lang.t('header') }}"
>
<!-- Link to home -->
<a
href="{{ config.extra.homepage | d(nav.homepage.url, true) | url }}"
title="{{ config.site_name | e }}"
class="md-header__button md-logo"
aria-label="{{ config.site_name }}"
data-md-component="logo"
>
{% include "partials/logo.html" %}
</a>
<!-- Button to open drawer -->
<label class="md-header__button md-icon" for="__drawer">
{% set icon = config.theme.icon.menu or "material/menu" %}
{% include ".icons/" ~ icon ~ ".svg" %}
</label>
<!-- Header title -->
<div class="md-header__title" data-md-component="header-title">
<div class="md-header__ellipsis">
<div class="md-header__topic">
<span class="md-ellipsis">
<a style="font-weight: 900;">Tag</a><a style="font-weight: 500;"><i>Studio</i></a>
</span>
</div>
<div class="md-header__topic" data-md-component="header-topic">
<span class="md-ellipsis">
{% if page.meta and page.meta.title %}
{{ page.meta.title }}
{% else %}
{{ page.title }}
{% endif %}
</span>
</div>
</div>
</div>
<!-- Color palette toggle -->
{% if config.theme.palette %}
{% if not config.theme.palette is mapping %}
{% include "partials/palette.html" %}
{% endif %}
{% endif %}
<!-- User preference: color palette -->
{% if not config.theme.palette is mapping %}
{% include "partials/javascripts/palette.html" %}
{% endif %}
<!-- Site language selector -->
{% if config.extra.alternate %}
{% include "partials/alternate.html" %}
{% endif %}
<!-- Button to open search modal -->
{% if "material/search" in config.plugins %}
{% set search = config.plugins["material/search"] | attr("config") %}
<!-- Check if search is actually enabled - see https://t.ly/DT_0V -->
{% if search.enabled %}
<label class="md-header__button md-icon" for="__search">
{% set icon = config.theme.icon.search or "material/magnify" %}
{% include ".icons/" ~ icon ~ ".svg" %}
</label>
<!-- Search interface -->
{% include "partials/search.html" %}
{% endif %}
{% endif %}
<!-- Repository information -->
{% if config.repo_url %}
<div class="md-header__source">
{% include "partials/source.html" %}
</div>
{% endif %}
</nav>
<!-- Navigation tabs (sticky) -->
{% if "navigation.tabs.sticky" in features %}
{% if "navigation.tabs" in features %}
{% include "partials/tabs.html" %}
{% endif %}
{% endif %}
</header>

View File

@@ -1,69 +0,0 @@
<!--
Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
-->
{% import "partials/nav-item.html" as item with context %}
<!-- Determine classes -->
{% set class = "md-nav md-nav--primary" %}
{% if "navigation.tabs" in features %}
{% set class = class ~ " md-nav--lifted" %}
{% endif %}
{% if "toc.integrate" in features %}
{% set class = class ~ " md-nav--integrated" %}
{% endif %}
<!-- Navigation -->
<nav
class="{{ class }}"
aria-label="{{ lang.t('nav') }}"
data-md-level="0"
>
<!-- Site title -->
<!-- <label class="md-nav__title" for="__drawer">
<a
href="{{ config.extra.homepage | d(nav.homepage.url, true) | url }}"
title="{{ config.site_name | e }}"
class="md-nav__button md-logo"
aria-label="{{ config.site_name }}"
data-md-component="logo"
>
{% include "partials/logo.html" %}
</a>
{{ config.site_name }}
</label> -->
<!-- Repository information -->
{% if config.repo_url %}
<div class="md-nav__source">
{% include "partials/source.html" %}
</div>
{% endif %}
<!-- Navigation list -->
<ul class="md-nav__list" data-md-scrollfix>
{% for nav_item in nav %}
{% set path = "__nav_" ~ loop.index %}
{{ item.render(nav_item, path, 1) }}
{% endfor %}
</ul>
</nav>

View File

@@ -5,48 +5,42 @@ build-backend = "hatchling.build"
[project]
name = "TagStudio"
description = "A User-Focused Photo & File Management System."
version = "9.5.4"
version = "9.5.1"
license = "GPL-3.0-only"
readme = "README.md"
requires-python = ">=3.12,<3.13"
dependencies = [
"chardet~=5.2",
"ffmpeg-python~=0.2",
"humanfriendly==10.*",
"mutagen~=1.47",
"numpy~=2.2",
"opencv_python~=4.11",
"Pillow>=10.2,<=11",
"pillow-avif-plugin~=1.5",
"pillow-heif~=0.22",
"pillow-jxl-plugin~=1.3",
"pydantic~=2.10",
"pydub~=0.25",
"PySide6==6.8.0.*",
"rawpy~=0.24",
"Send2Trash~=1.8",
"SQLAlchemy~=2.0",
"srctools~=2.6",
"structlog~=25.3",
"toml~=0.10",
"typing_extensions~=4.13",
"ujson~=5.10",
"wcmatch==10.*",
"chardet==5.2.0",
"ffmpeg-python==0.2.0",
"humanfriendly==10.0",
"mutagen==1.47.0",
"numpy==2.1.0",
"opencv_python==4.10.0.84",
"Pillow==10.3.0",
"pillow-heif==0.16.0",
"pillow-jxl-plugin==1.3.0",
"pydub==0.25.1",
"PySide6==6.8.0.1",
"rawpy==0.22.0",
"Send2Trash==1.8.3",
"SQLAlchemy==2.0.34",
"structlog==24.4.0",
"typing_extensions>=3.10.0.0,<4.11.0",
"ujson>=5.8.0,<5.9.0",
"vtf2img==0.1.0",
]
[project.optional-dependencies]
dev = ["tagstudio[mkdocs,mypy,pre-commit,pyinstaller,pytest,ruff]"]
mkdocs = ["mkdocs-material[imaging]>=9.6.14"]
mypy = ["mypy==1.15.0", "mypy-extensions==1.*", "types-ujson~=5.10"]
pre-commit = ["pre-commit~=4.2"]
pyinstaller = ["Pyinstaller~=6.13"]
dev = ["pre-commit==3.7.0", "tagstudio[mkdocs,mypy,pyinstaller,pytest,ruff]"]
mkdocs = ["mkdocs-material[imaging]==9.*"]
mypy = ["mypy==1.11.2", "mypy-extensions==1.*", "types-ujson>=5.8.0,<5.9.0"]
pyinstaller = ["Pyinstaller==6.6.0"]
pytest = [
"pytest==8.3.5",
"pytest-cov==6.1.1",
"pytest==8.2.0",
"pytest-cov==5.0.0",
"pytest-qt==4.4.0",
"syrupy==4.9.1",
"syrupy==4.7.1",
]
ruff = ["ruff==0.11.8"]
ruff = ["ruff==0.8.1"]
[project.gui-scripts]
tagstudio = "tagstudio.main:main"
@@ -85,22 +79,18 @@ ignore_errors = true
qt_api = "pyside6"
[tool.pyright]
ignore = ["src/tagstudio/qt/helpers/vendored/pydub/", ".venv/**"]
include = ["src/tagstudio", "tests"]
ignore = [".venv/**"]
include = ["src/tagstudio/**"]
reportAny = false
reportIgnoreCommentWithoutRule = false
reportImplicitStringConcatenation = false
reportMissingTypeArgument = false
reportMissingTypeStubs = false
# reportOptionalMemberAccess = false
reportUnannotatedClassAttribute = false
reportUnknownArgumentType = false
reportUnknownLambdaType = false
reportUnknownMemberType = false
reportUnusedCallResult = false
[tool.ruff]
exclude = ["home_ui.py", "resources.py", "resources_rc.py"]
exclude = ["main_window.py", "home_ui.py", "resources.py", "resources_rc.py"]
line-length = 100
[tool.ruff.lint]

View File

@@ -2,14 +2,13 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
VERSION: str = "9.5.4" # Major.Minor.Patch
VERSION: str = "9.5.1" # Major.Minor.Patch
VERSION_BRANCH: str = "" # Usually "" or "Pre-Release"
# The folder & file names where TagStudio keeps its data relative to a library.
TS_FOLDER_NAME: str = ".TagStudio"
BACKUP_FOLDER_NAME: str = "backups"
COLLAGE_FOLDER_NAME: str = "collages"
IGNORE_NAME: str = ".ts_ignore"
THUMB_CACHE_NAME: str = "thumbs"
FONT_SAMPLE_TEXT: str = (

View File

@@ -5,15 +5,13 @@ from PySide6.QtCore import QSettings
from tagstudio.core.constants import TS_FOLDER_NAME
from tagstudio.core.enums import SettingItems
from tagstudio.core.global_settings import GlobalSettings
from tagstudio.core.library.alchemy.library import LibraryStatus
logger = structlog.get_logger(__name__)
class DriverMixin:
cached_values: QSettings
settings: GlobalSettings
settings: QSettings
def evaluate_path(self, open_path: str | None) -> LibraryStatus:
"""Check if the path of library is valid."""
@@ -23,17 +21,17 @@ class DriverMixin:
if not library_path.exists():
logger.error("Path does not exist.", open_path=open_path)
return LibraryStatus(success=False, message="Path does not exist.")
elif self.settings.open_last_loaded_on_startup and self.cached_values.value(
SettingItems.LAST_LIBRARY
):
library_path = Path(str(self.cached_values.value(SettingItems.LAST_LIBRARY)))
elif self.settings.value(
SettingItems.START_LOAD_LAST, defaultValue=True, type=bool
) and self.settings.value(SettingItems.LAST_LIBRARY):
library_path = Path(str(self.settings.value(SettingItems.LAST_LIBRARY)))
if not (library_path / TS_FOLDER_NAME).exists():
logger.error(
"TagStudio folder does not exist.",
library_path=library_path,
ts_folder=TS_FOLDER_NAME,
)
self.cached_values.setValue(SettingItems.LAST_LIBRARY, "")
self.settings.setValue(SettingItems.LAST_LIBRARY, "")
# dont consider this a fatal error, just skip opening the library
library_path = None

View File

@@ -10,27 +10,14 @@ from uuid import uuid4
class SettingItems(str, enum.Enum):
"""List of setting item names."""
START_LOAD_LAST = "start_load_last"
LAST_LIBRARY = "last_library"
LIBS_LIST = "libs_list"
WINDOW_SHOW_LIBS = "window_show_libs"
SHOW_FILENAMES = "show_filenames"
AUTOPLAY = "autoplay_videos"
THUMB_CACHE_SIZE_LIMIT = "thumb_cache_size_limit"
class ShowFilepathOption(int, enum.Enum):
"""Values representing the options for the "show_filenames" setting."""
SHOW_FULL_PATHS = 0
SHOW_RELATIVE_PATHS = 1
SHOW_FILENAMES_ONLY = 2
DEFAULT = SHOW_RELATIVE_PATHS
class TagClickActionOption(int, enum.Enum):
"""Values representing the options for the "tag_click_action" setting."""
OPEN_EDIT = 0
SET_SEARCH = 1
ADD_TO_SEARCH = 2
DEFAULT = OPEN_EDIT
LANGUAGE = "language"
class Theme(str, enum.Enum):
@@ -79,9 +66,10 @@ class DefaultEnum(enum.Enum):
raise AttributeError("access the value via .default property instead")
# TODO: Remove DefaultEnum and LibraryPrefs classes once remaining values are removed.
class LibraryPrefs(DefaultEnum):
"""Library preferences with default value accessible via .default property."""
IS_EXCLUDE_LIST = True
EXTENSION_LIST = [".json", ".xmp", ".aae"]
PAGE_SIZE = 500
DB_VERSION = 8

View File

@@ -1,111 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import platform
from datetime import datetime
from enum import Enum, IntEnum, StrEnum
from pathlib import Path
from typing import override
import structlog
import toml
from pydantic import BaseModel, Field
from tagstudio.core.enums import ShowFilepathOption, TagClickActionOption
DEFAULT_GLOBAL_SETTINGS_PATH = (
Path.home() / "Appdata" / "Roaming" / "TagStudio" / "settings.toml"
if platform.system() == "Windows"
else Path.home() / ".config" / "TagStudio" / "settings.toml"
)
logger = structlog.get_logger(__name__)
class TomlEnumEncoder(toml.TomlEncoder):
@override
def dump_value(self, v): # pyright: ignore[reportMissingParameterType]
if isinstance(v, Enum):
return super().dump_value(v.value)
return super().dump_value(v)
class Theme(IntEnum):
DARK = 0
LIGHT = 1
SYSTEM = 2
DEFAULT = SYSTEM
class Splash(StrEnum):
DEFAULT = "default"
RANDOM = "random"
CLASSIC = "classic"
GOO_GEARS = "goo_gears"
NINETY_FIVE = "95"
# NOTE: pydantic also has a BaseSettings class (from pydantic-settings) that allows any settings
# properties to be overwritten with environment variables. As TagStudio is not currently using
# environment variables, this was not based on that, but that may be useful in the future.
class GlobalSettings(BaseModel):
language: str = Field(default="en")
open_last_loaded_on_startup: bool = Field(default=True)
generate_thumbs: bool = Field(default=True)
autoplay: bool = Field(default=True)
loop: bool = Field(default=True)
show_filenames_in_grid: bool = Field(default=True)
page_size: int = Field(default=100)
show_filepath: ShowFilepathOption = Field(default=ShowFilepathOption.DEFAULT)
tag_click_action: TagClickActionOption = Field(default=TagClickActionOption.DEFAULT)
theme: Theme = Field(default=Theme.SYSTEM)
splash: Splash = Field(default=Splash.DEFAULT)
date_format: str = Field(default="%x")
hour_format: bool = Field(default=True)
zero_padding: bool = Field(default=True)
loaded_from: Path = Field(default=DEFAULT_GLOBAL_SETTINGS_PATH, exclude=True)
@staticmethod
def read_settings(path: Path = DEFAULT_GLOBAL_SETTINGS_PATH) -> "GlobalSettings":
if path.exists():
with open(path) as file:
filecontents = file.read()
if len(filecontents.strip()) != 0:
logger.info("[Settings] Reading Global Settings File", path=path)
settings_data = toml.loads(filecontents)
settings = GlobalSettings(**settings_data, loaded_from=path)
return settings
return GlobalSettings(loaded_from=path)
def save(self, path: Path | None = None) -> None:
if path is None:
path = self.loaded_from
if not path.parent.exists():
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
toml.dump(self.model_dump(), f, encoder=TomlEnumEncoder())
@property
def datetime_format(self) -> str:
date_format = self.date_format
is_24h = self.hour_format
hour_format = "%H:%M:%S" if is_24h else "%I:%M:%S %p"
zero_padding = self.zero_padding
zero_padding_symbol = ""
if not zero_padding:
zero_padding_symbol = "#" if platform.system() == "Windows" else "-"
date_format = date_format.replace("%d", f"%{zero_padding_symbol}d").replace(
"%m", f"%{zero_padding_symbol}m"
)
hour_format = hour_format.replace("%H", f"%{zero_padding_symbol}H").replace(
"%I", f"%{zero_padding_symbol}I"
)
return f"{date_format}, {hour_format}"
def format_datetime(self, dt: datetime) -> str:
return datetime.strftime(dt, self.datetime_format)

View File

@@ -1,25 +0,0 @@
# Copyright (C) 2025
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from sqlalchemy import text
SQL_FILENAME: str = "ts_library.sqlite"
JSON_FILENAME: str = "ts_library.json"
DB_VERSION_LEGACY_KEY: str = "DB_VERSION"
DB_VERSION_CURRENT_KEY: str = "CURRENT"
DB_VERSION_INITIAL_KEY: str = "INITIAL"
DB_VERSION: int = 101
TAG_CHILDREN_QUERY = text("""
WITH RECURSIVE ChildTags AS (
SELECT :tag_id AS tag_id
UNION
SELECT tp.child_id AS tag_id
FROM tag_parents tp
INNER JOIN ChildTags c ON tp.parent_id = c.tag_id
)
SELECT * FROM ChildTags;
""")

View File

@@ -1,11 +1,10 @@
import enum
import random
from dataclasses import dataclass, replace
from pathlib import Path
import structlog
from tagstudio.core.query_lang.ast import AST
from tagstudio.core.query_lang.ast import AST, Constraint, ConstraintType
from tagstudio.core.query_lang.parser import Parser
MAX_SQL_VARIABLES = 32766 # 32766 is the max sql bind parameter count as defined here: https://github.com/sqlite/sqlite/blob/master/src/sqliteLimit.h#L140
@@ -68,85 +67,67 @@ class ItemType(enum.Enum):
class SortingModeEnum(enum.Enum):
DATE_ADDED = "file.date_added"
FILE_NAME = "generic.filename"
PATH = "file.path"
RANDOM = "sorting.mode.random"
@dataclass
class BrowsingState:
class FilterState:
"""Represent a state of the Library grid view."""
page_index: int = 0
# these should remain
page_index: int | None = 0
page_size: int | None = 500
sorting_mode: SortingModeEnum = SortingModeEnum.DATE_ADDED
ascending: bool = True
random_seed: float = 0
query: str | None = None
# these should be erased on update
# Abstract Syntax Tree Of the current Search Query
ast: AST = None
@property
def ast(self) -> AST | None:
if self.query is None:
return None
return Parser(self.query).parse()
def limit(self):
return self.page_size
@property
def offset(self):
return self.page_size * self.page_index
@classmethod
def show_all(cls) -> "BrowsingState":
return BrowsingState()
def show_all(cls) -> "FilterState":
return FilterState()
@classmethod
def from_search_query(cls, search_query: str) -> "BrowsingState":
return cls(query=search_query)
def from_search_query(cls, search_query: str) -> "FilterState":
return cls(ast=Parser(search_query).parse())
@classmethod
def from_tag_id(
cls, tag_id: int | str, state: "BrowsingState | None" = None
) -> "BrowsingState":
"""Create and return a BrowsingState object given a tag ID.
Args:
tag_id(int): The tag ID to search for.
state(BrowsingState|None): An optional BrowsingState object to use
existing options from, such as sorting options.
"""
logger.warning(state)
if state:
return state.with_search_query(f"tag_id:{str(tag_id)}")
return cls(query=f"tag_id:{str(tag_id)}")
def from_tag_id(cls, tag_id: int | str) -> "FilterState":
return cls(ast=Constraint(ConstraintType.TagID, str(tag_id), []))
@classmethod
def from_path(cls, path: Path | str) -> "BrowsingState":
return cls(query=f'path:"{str(path).strip()}"')
def from_path(cls, path: Path | str) -> "FilterState":
return cls(ast=Constraint(ConstraintType.Path, str(path).strip(), []))
@classmethod
def from_mediatype(cls, mediatype: str) -> "BrowsingState":
return cls(query=f"mediatype:{mediatype}")
def from_mediatype(cls, mediatype: str) -> "FilterState":
return cls(ast=Constraint(ConstraintType.MediaType, mediatype, []))
@classmethod
def from_filetype(cls, filetype: str) -> "BrowsingState":
return cls(query=f"filetype:{filetype}")
def from_filetype(cls, filetype: str) -> "FilterState":
return cls(ast=Constraint(ConstraintType.FileType, filetype, []))
@classmethod
def from_tag_name(cls, tag_name: str) -> "BrowsingState":
return cls(query=f'tag:"{tag_name}"')
def from_tag_name(cls, tag_name: str) -> "FilterState":
return cls(ast=Constraint(ConstraintType.Tag, tag_name, []))
def with_page_index(self, index: int) -> "BrowsingState":
return replace(self, page_index=index)
def with_page_size(self, page_size: int) -> "FilterState":
return replace(self, page_size=page_size)
def with_sorting_mode(self, mode: SortingModeEnum) -> "BrowsingState":
seed = self.random_seed
if mode == SortingModeEnum.RANDOM:
seed = random.random()
return replace(self, sorting_mode=mode, random_seed=seed)
def with_sorting_mode(self, mode: SortingModeEnum) -> "FilterState":
return replace(self, sorting_mode=mode)
def with_sorting_direction(self, ascending: bool) -> "BrowsingState":
def with_sorting_direction(self, ascending: bool) -> "FilterState":
return replace(self, ascending=ascending)
def with_search_query(self, search_query: str) -> "BrowsingState":
return replace(self, query=search_query)
class FieldTypeEnum(enum.Enum):
TEXT_LINE = "Text Line"

View File

@@ -7,16 +7,15 @@ import re
import shutil
import time
import unicodedata
from collections.abc import Iterable, Iterator
from collections.abc import Iterator
from dataclasses import dataclass
from datetime import UTC, datetime
from os import makedirs
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from uuid import uuid4
from warnings import catch_warnings
import sqlalchemy
import structlog
from humanfriendly import format_timespan
from sqlalchemy import (
@@ -32,7 +31,6 @@ from sqlalchemy import (
desc,
exists,
func,
inspect,
or_,
select,
text,
@@ -44,13 +42,11 @@ from sqlalchemy.orm import (
contains_eager,
joinedload,
make_transient,
noload,
selectinload,
)
from tagstudio.core.constants import (
BACKUP_FOLDER_NAME,
IGNORE_NAME,
LEGACY_TAG_FIELD_IDS,
RESERVED_NAMESPACE_PREFIX,
RESERVED_TAG_END,
@@ -62,20 +58,11 @@ from tagstudio.core.constants import (
)
from tagstudio.core.enums import LibraryPrefs
from tagstudio.core.library.alchemy import default_color_groups
from tagstudio.core.library.alchemy.constants import (
DB_VERSION,
DB_VERSION_CURRENT_KEY,
DB_VERSION_INITIAL_KEY,
DB_VERSION_LEGACY_KEY,
JSON_FILENAME,
SQL_FILENAME,
TAG_CHILDREN_QUERY,
)
from tagstudio.core.library.alchemy.db import make_tables
from tagstudio.core.library.alchemy.enums import (
MAX_SQL_VARIABLES,
BrowsingState,
FieldTypeEnum,
FilterState,
SortingModeEnum,
)
from tagstudio.core.library.alchemy.fields import (
@@ -94,11 +81,9 @@ from tagstudio.core.library.alchemy.models import (
TagAlias,
TagColorGroup,
ValueType,
Version,
)
from tagstudio.core.library.alchemy.visitors import SQLBoolExpressionBuilder
from tagstudio.core.library.json.library import Library as JsonLibrary
from tagstudio.core.utils.types import unwrap
from tagstudio.qt.translations import Translations
if TYPE_CHECKING:
@@ -107,6 +92,18 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
TAG_CHILDREN_QUERY = text("""
-- Note for this entire query that tag_parents.child_id is the parent id and tag_parents.parent_id is the child id due to bad naming
WITH RECURSIVE ChildTags AS (
SELECT :tag_id AS child_id
UNION ALL
SELECT tp.parent_id AS child_id
FROM tag_parents tp
INNER JOIN ChildTags c ON tp.child_id = c.child_id
)
SELECT * FROM ChildTags;
""") # noqa: E501
class ReservedNamespaceError(Exception):
"""Raise during an unauthorized attempt to create or modify a reserved namespace value.
@@ -173,26 +170,26 @@ class SearchResult:
Attributes:
total_count(int): total number of items for given query, might be different than len(items).
ids(list[int]): for current page (size matches filter.page_size).
items(list[Entry]): for current page (size matches filter.page_size).
"""
total_count: int
ids: list[int]
items: list[Entry]
def __bool__(self) -> bool:
"""Boolean evaluation for the wrapper.
:return: True if there are ids in the result.
:return: True if there are items in the result.
"""
return self.total_count > 0
def __len__(self) -> int:
"""Return the total number of ids in the result."""
return len(self.ids)
"""Return the total number of items in the result."""
return len(self.items)
def __getitem__(self, index: int) -> int:
"""Allow to access ids via index directly on the wrapper."""
return self.ids[index]
def __getitem__(self, index: int) -> Entry:
"""Allow to access items via index directly on the wrapper."""
return self.items[index]
@dataclass
@@ -210,16 +207,13 @@ class Library:
"""Class for the Library object, and all CRUD operations made upon it."""
library_dir: Path | None = None
storage_path: Path | str | None
storage_path: Path | None
engine: Engine | None = None
folder: Folder | None
included_files: set[Path] = set()
def __init__(self) -> None:
self.dupe_entries_count: int = -1 # NOTE: For internal management.
self.dupe_files_count: int = -1
self.ignored_entries_count: int = -1
self.unlinked_entries_count: int = -1
SQL_FILENAME: str = "ts_library.sqlite"
JSON_FILENAME: str = "ts_library.json"
def close(self):
if self.engine:
@@ -229,11 +223,6 @@ class Library:
self.folder = None
self.included_files = set()
self.dupe_entries_count = -1
self.dupe_files_count = -1
self.ignored_entries_count = -1
self.unlinked_entries_count = -1
def migrate_json_to_sqlite(self, json_lib: JsonLibrary):
"""Migrate JSON library data to the SQLite database."""
logger.info("Starting Library Conversion...")
@@ -283,8 +272,8 @@ class Library:
# Parent Tags (Previously known as "Subtags" in JSON)
for tag in json_lib.tags:
for parent_id in tag.subtag_ids:
self.add_parent_tag(parent_id=parent_id, child_id=tag.id)
for child_id in tag.subtag_ids:
self.add_parent_tag(parent_id=tag.id, child_id=child_id)
# Entries
self.add_entries(
@@ -325,12 +314,13 @@ class Library:
return f
return None
def tag_display_name(self, tag: Tag | None) -> str:
if not tag:
return "<NO TAG>"
def tag_display_name(self, tag_id: int) -> str:
with Session(self.engine) as session:
tag = session.scalar(select(Tag).where(Tag.id == tag_id))
if not tag:
return "<NO TAG>"
if tag.disambiguation_id:
with Session(self.engine) as session:
if tag.disambiguation_id:
disam_tag = session.scalar(select(Tag).where(Tag.id == tag.disambiguation_id))
if not disam_tag:
return "<NO DISAM TAG>"
@@ -338,22 +328,19 @@ class Library:
if not disam_name:
disam_name = disam_tag.name
return f"{tag.name} ({disam_name})"
else:
return tag.name
else:
return tag.name
def open_library(
self, library_dir: Path, storage_path: Path | str | None = None
) -> LibraryStatus:
def open_library(self, library_dir: Path, storage_path: Path | None = None) -> LibraryStatus:
is_new: bool = True
if storage_path == ":memory:":
self.storage_path = storage_path
is_new = True
return self.open_sqlite_library(library_dir, is_new)
else:
self.storage_path = library_dir / TS_FOLDER_NAME / SQL_FILENAME
assert isinstance(self.storage_path, Path)
self.storage_path = library_dir / TS_FOLDER_NAME / self.SQL_FILENAME
if self.verify_ts_folder(library_dir) and (is_new := not self.storage_path.exists()):
json_path = library_dir / TS_FOLDER_NAME / JSON_FILENAME
json_path = library_dir / TS_FOLDER_NAME / self.JSON_FILENAME
if json_path.exists():
return LibraryStatus(
success=False,
@@ -377,7 +364,7 @@ class Library:
# https://docs.sqlalchemy.org/en/20/changelog/migration_07.html
# Under -> sqlite-the-sqlite-dialect-now-uses-nullpool-for-file-based-databases
poolclass = None if self.storage_path == ":memory:" else NullPool
loaded_db_version: int = 0
db_version: int = 0
logger.info(
"[Library] Opening SQLite Library",
@@ -386,19 +373,16 @@ class Library:
)
self.engine = create_engine(connection_string, poolclass=poolclass)
with Session(self.engine) as session:
# Don't check DB version when creating new library
# dont check db version when creating new library
if not is_new:
loaded_db_version = self.get_version(DB_VERSION_CURRENT_KEY)
db_result = session.scalar(
select(Preferences).where(Preferences.key == LibraryPrefs.DB_VERSION.name)
)
if db_result:
db_version = db_result.value
# ======================== Library Database Version Checking =======================
# DB_VERSION 6 is the first supported SQLite DB version.
# If the DB_VERSION is >= 100, that means it's a compound major + minor version.
# - Dividing by 100 and flooring gives the major (breaking changes) version.
# - If a DB has major version higher than the current program, don't load it.
# - If only the minor version is higher, it's still allowed to load.
if loaded_db_version < 6 or (
loaded_db_version >= 100 and loaded_db_version // 100 > DB_VERSION // 100
):
# NOTE: DB_VERSION 6 is the first supported SQL DB version.
if db_version < 6 or db_version > LibraryPrefs.DB_VERSION.default:
mismatch_text = Translations["status.library_version_mismatch"]
found_text = Translations["status.library_version_found"]
expected_text = Translations["status.library_version_expected"]
@@ -406,12 +390,12 @@ class Library:
success=False,
message=(
f"{mismatch_text}\n"
f"{found_text} v{loaded_db_version}, "
f"{expected_text} v{DB_VERSION}"
f"{found_text} v{db_version}, "
f"{expected_text} v{LibraryPrefs.DB_VERSION.default}"
),
)
logger.info(f"[Library] DB_VERSION: {loaded_db_version}")
logger.info(f"[Library] DB_VERSION: {db_version}")
make_tables(self.engine)
# Add default tag color namespaces.
@@ -449,37 +433,13 @@ class Library:
except IntegrityError:
session.rollback()
# Ensure version rows are present
with catch_warnings(record=True):
# NOTE: The "Preferences" table is depreciated and will be removed in the future.
# The DB_VERSION is still being set to it in order to remain backwards-compatible
# with existing TagStudio versions until it is removed.
try:
session.add(Preferences(key=DB_VERSION_LEGACY_KEY, value=DB_VERSION))
session.commit()
except IntegrityError:
session.rollback()
try:
initial = DB_VERSION if is_new else 100
session.add(Version(key=DB_VERSION_INITIAL_KEY, value=initial))
session.commit()
except IntegrityError:
session.rollback()
try:
session.add(Version(key=DB_VERSION_CURRENT_KEY, value=DB_VERSION))
session.commit()
except IntegrityError:
session.rollback()
# TODO: Remove this "Preferences" system.
for pref in LibraryPrefs:
with catch_warnings(record=True):
try:
session.add(Preferences(key=pref.name, value=pref.default))
session.commit()
except IntegrityError:
logger.debug("preference already exists", pref=pref)
session.rollback()
for field in _FieldID:
@@ -510,52 +470,24 @@ class Library:
session.commit()
self.folder = folder
# Generate default .ts_ignore file
if is_new:
try:
ts_ignore_template = (
Path(__file__).parents[3] / "resources/templates/ts_ignore_template.txt"
)
shutil.copy2(ts_ignore_template, library_dir / TS_FOLDER_NAME / IGNORE_NAME)
except Exception as e:
logger.error("[ERROR][Library] Could not generate '.ts_ignore' file!", error=e)
# Apply any post-SQL migration patches.
if not is_new:
# save backup if patches will be applied
if loaded_db_version < DB_VERSION:
self.library_dir = library_dir
self.save_library_backup_to_disk()
self.library_dir = None
# schema changes first
if loaded_db_version < 8:
self.__apply_db8_schema_changes(session)
if loaded_db_version < 9:
self.__apply_db9_schema_changes(session)
# now the data changes
if loaded_db_version == 6:
self.__apply_repairs_for_db6(session)
if loaded_db_version >= 6 and loaded_db_version < 8:
self.__apply_db8_default_data(session)
if loaded_db_version < 9:
self.__apply_db9_filename_population(session)
if loaded_db_version < 100:
self.__apply_db100_parent_repairs(session)
# Convert file extension list to ts_ignore file, if a .ts_ignore file does not exist
self.migrate_sql_to_ts_ignore(library_dir)
if db_version < 8:
self.apply_db8_schema_changes(session)
if db_version == 6:
self.apply_repairs_for_db6(session)
if db_version >= 6 and db_version < 8:
self.apply_db8_default_data(session)
# Update DB_VERSION
if loaded_db_version < DB_VERSION:
self.set_version(DB_VERSION_CURRENT_KEY, DB_VERSION)
if LibraryPrefs.DB_VERSION.default > db_version:
self.set_prefs(LibraryPrefs.DB_VERSION, LibraryPrefs.DB_VERSION.default)
# everything is fine, set the library path
self.library_dir = library_dir
return LibraryStatus(success=True, library_path=library_dir)
def __apply_repairs_for_db6(self, session: Session):
def apply_repairs_for_db6(self, session: Session):
"""Apply database repairs introduced in DB_VERSION 7."""
logger.info("[Library][Migration] Applying patches to DB_VERSION: 6 library...")
with session:
@@ -576,9 +508,11 @@ class Library:
.values(disambiguation_id=None)
)
session.execute(disam_stmt)
session.flush()
session.commit()
def __apply_db8_schema_changes(self, session: Session):
def apply_db8_schema_changes(self, session: Session):
"""Apply database schema changes introduced in DB_VERSION 8."""
# TODO: Use Alembic for this part instead
# Add the missing color_border column to the TagColorGroups table.
@@ -596,7 +530,7 @@ class Library:
)
session.rollback()
def __apply_db8_default_data(self, session: Session):
def apply_db8_default_data(self, session: Session):
"""Apply default data changes introduced in DB_VERSION 8."""
tag_colors: list[TagColorGroup] = default_color_groups.standard()
tag_colors += default_color_groups.pastels()
@@ -646,69 +580,6 @@ class Library:
)
session.rollback()
def __apply_db9_schema_changes(self, session: Session):
"""Apply database schema changes introduced in DB_VERSION 9."""
add_filename_column = text(
"ALTER TABLE entries ADD COLUMN filename TEXT NOT NULL DEFAULT ''"
)
try:
session.execute(add_filename_column)
session.commit()
logger.info("[Library][Migration] Added filename column to entries table")
except Exception as e:
logger.error(
"[Library][Migration] Could not create filename column in entries table!",
error=e,
)
session.rollback()
def __apply_db9_filename_population(self, session: Session):
"""Populate the filename column introduced in DB_VERSION 9."""
for entry in self.all_entries():
session.merge(entry).filename = entry.path.name
session.commit()
logger.info("[Library][Migration] Populated filename column in entries table")
def __apply_db100_parent_repairs(self, session: Session):
"""Swap the child_id and parent_id values in the TagParent table."""
with session:
# Repair parent-child tag relationships that are the wrong way around.
stmt = update(TagParent).values(
parent_id=TagParent.child_id,
child_id=TagParent.parent_id,
)
session.execute(stmt)
session.commit()
logger.info("[Library][Migration] Refactored TagParent column")
def migrate_sql_to_ts_ignore(self, library_dir: Path):
# Do not continue if existing '.ts_ignore' file is found
if Path(library_dir / TS_FOLDER_NAME / IGNORE_NAME).exists():
return
# Create blank '.ts_ignore' file
ts_ignore_template = (
Path(__file__).parents[3] / "resources/templates/ts_ignore_template_blank.txt"
)
ts_ignore = library_dir / TS_FOLDER_NAME / IGNORE_NAME
try:
shutil.copy2(ts_ignore_template, ts_ignore)
except Exception as e:
logger.error("[ERROR][Library] Could not generate '.ts_ignore' file!", error=e)
# Load legacy extension data
extensions: list[str] = self.prefs(LibraryPrefs.EXTENSION_LIST) # pyright: ignore[reportAssignmentType]
is_exclude_list: bool = self.prefs(LibraryPrefs.IS_EXCLUDE_LIST) # pyright: ignore[reportAssignmentType]
# Copy extensions to '.ts_ignore' file
if ts_ignore.exists():
with open(ts_ignore, "a") as f:
prefix = ""
if not is_exclude_list:
prefix = "!"
f.write("*\n")
f.writelines([f"{prefix}*.{x.lstrip('.')}\n" for x in extensions])
@property
def default_fields(self) -> list[BaseField]:
with Session(self.engine) as session:
@@ -752,10 +623,7 @@ class Library:
entry_stmt = (
entry_stmt.outerjoin(Entry.text_fields)
.outerjoin(Entry.datetime_fields)
.options(
selectinload(Entry.text_fields),
selectinload(Entry.datetime_fields),
)
.options(selectinload(Entry.text_fields), selectinload(Entry.datetime_fields))
)
# if with_tags:
# entry_stmt = entry_stmt.outerjoin(Entry.tags).options(selectinload(Entry.tags))
@@ -770,7 +638,7 @@ class Library:
start_time = time.time()
entry = session.scalar(entry_stmt)
if with_tags:
tags = set(session.scalars(tag_stmt)) # pyright: ignore[reportPossiblyUnboundVariable]
tags = set(session.scalars(tag_stmt)) # pyright: ignore [reportPossiblyUnboundVariable]
end_time = time.time()
logger.info(
f"[Library] Time it took to get entry: "
@@ -788,12 +656,6 @@ class Library:
entry.tags = tags
return entry
def get_entries(self, entry_ids: Iterable[int]) -> list[Entry]:
with Session(self.engine) as session:
statement = select(Entry).where(Entry.id.in_(entry_ids))
entries = dict((e.id, e) for e in session.scalars(statement))
return [entries[id] for id in entry_ids]
def get_entries_full(self, entry_ids: list[int] | set[int]) -> Iterator[Entry]:
"""Load entry and join with all joins and all tags."""
with Session(self.engine) as session:
@@ -848,25 +710,12 @@ class Library:
make_transient(entry)
return entry
def get_tag_entries(
self, tag_ids: Iterable[int], entry_ids: Iterable[int]
) -> dict[int, set[int]]:
"""Returns a dict of tag_id->(entry_ids with tag_id)."""
tag_entries: dict[int, set[int]] = dict((id, set()) for id in tag_ids)
with Session(self.engine) as session:
statement = select(TagEntry).where(
and_(TagEntry.tag_id.in_(tag_ids), TagEntry.entry_id.in_(entry_ids))
)
for tag_entry in session.scalars(statement).fetchall():
tag_entries[tag_entry.tag_id].add(tag_entry.entry_id)
return tag_entries
@property
def entries_count(self) -> int:
with Session(self.engine) as session:
return session.scalar(select(func.count(Entry.id)))
def all_entries(self, with_joins: bool = False) -> Iterator[Entry]:
def get_entries(self, with_joins: bool = False) -> Iterator[Entry]:
"""Load entries without joins."""
with Session(self.engine) as session:
stmt = select(Entry)
@@ -972,18 +821,17 @@ class Library:
def search_library(
self,
search: BrowsingState,
page_size: int | None,
search: FilterState,
) -> SearchResult:
"""Filter library by search query.
:return: number of entries matching the query and one page of results.
"""
assert isinstance(search, BrowsingState)
assert self.library_dir
assert isinstance(search, FilterState)
assert self.engine
with Session(unwrap(self.engine), expire_on_commit=False) as session:
statement = select(Entry.id, func.count().over())
with Session(self.engine, expire_on_commit=False) as session:
statement = select(Entry)
if search.ast:
start_time = time.time()
@@ -992,22 +840,29 @@ class Library:
logger.info(
f"SQL Expression Builder finished ({format_timespan(end_time - start_time)})"
)
extensions = self.prefs(LibraryPrefs.EXTENSION_LIST)
is_exclude_list = self.prefs(LibraryPrefs.IS_EXCLUDE_LIST)
if extensions and is_exclude_list:
statement = statement.where(Entry.suffix.notin_(extensions))
elif extensions:
statement = statement.where(Entry.suffix.in_(extensions))
statement = statement.distinct(Entry.id)
start_time = time.time()
query_count = select(func.count()).select_from(statement.alias("entries"))
count_all: int = session.execute(query_count).scalar()
end_time = time.time()
logger.info(f"finished counting ({format_timespan(end_time - start_time)})")
sort_on: ColumnExpressionArgument = Entry.id
match search.sorting_mode:
case SortingModeEnum.DATE_ADDED:
sort_on = Entry.id
case SortingModeEnum.FILE_NAME:
sort_on = func.lower(Entry.filename)
case SortingModeEnum.PATH:
sort_on = func.lower(Entry.path)
case SortingModeEnum.RANDOM:
sort_on = func.sin(Entry.id * search.random_seed)
statement = statement.order_by(asc(sort_on) if search.ascending else desc(sort_on))
if page_size is not None:
statement = statement.limit(page_size).offset(search.page_index * page_size)
statement = statement.limit(search.limit).offset(search.offset)
logger.info(
"searching library",
@@ -1016,18 +871,13 @@ class Library:
)
start_time = time.time()
rows = session.execute(statement).fetchall()
ids = []
count = 0
for row in rows:
id, count = row._tuple()
ids.append(id)
items = session.scalars(statement).fetchall()
end_time = time.time()
logger.info(f"SQL Execution finished ({format_timespan(end_time - start_time)})")
res = SearchResult(
total_count=count,
ids=ids,
total_count=count_all,
items=list(items),
)
session.expunge_all()
@@ -1260,7 +1110,7 @@ class Library:
value: str | datetime | None = None,
) -> bool:
logger.info(
"[Library][add_field_to_entry]",
"add_field_to_entry",
entry_id=entry_id,
field_type=field,
field_id=field_id,
@@ -1433,19 +1283,8 @@ class Library:
def add_tags_to_entries(
self, entry_ids: int | list[int], tag_ids: int | list[int] | set[int]
) -> int:
"""Add one or more tags to one or more entries.
Returns:
The total number of tags added across all entries.
"""
total_added: int = 0
logger.info(
"[Library][add_tags_to_entries]",
entry_ids=entry_ids,
tag_ids=tag_ids,
)
) -> bool:
"""Add one or more tags to one or more entries."""
entry_ids_ = [entry_ids] if isinstance(entry_ids, int) else entry_ids
tag_ids_ = [tag_ids] if isinstance(tag_ids, int) else tag_ids
with Session(self.engine, expire_on_commit=False) as session:
@@ -1453,12 +1292,16 @@ class Library:
for entry_id in entry_ids_:
try:
session.add(TagEntry(tag_id=tag_id, entry_id=entry_id))
total_added += 1
session.commit()
session.flush()
except IntegrityError:
session.rollback()
return total_added
try:
session.commit()
except IntegrityError as e:
logger.warning("[Library][add_tags_to_entries]", warning=e)
session.rollback()
return False
return True
def remove_tags_from_entries(
self, entry_ids: int | list[int], tag_ids: int | list[int] | set[int]
@@ -1524,12 +1367,10 @@ class Library:
target_path = self.library_dir / TS_FOLDER_NAME / BACKUP_FOLDER_NAME / filename
shutil.copy2(
self.library_dir / TS_FOLDER_NAME / SQL_FILENAME,
self.library_dir / TS_FOLDER_NAME / self.SQL_FILENAME,
target_path,
)
logger.info("Library backup saved to disk.", path=target_path)
return target_path
def get_tag(self, tag_id: int) -> Tag | None:
@@ -1541,14 +1382,12 @@ class Library:
)
tag = session.scalar(tags_query.where(Tag.id == tag_id))
if tag is not None:
session.expunge(tag)
session.expunge(tag)
for parent in tag.parent_tags:
session.expunge(parent)
for parent in tag.parent_tags:
session.expunge(parent)
for alias in tag.aliases:
session.expunge(alias)
for alias in tag.aliases:
session.expunge(alias)
return tag
@@ -1556,23 +1395,10 @@ class Library:
with Session(self.engine) as session:
statement = (
select(Tag)
.options(selectinload(Tag.parent_tags), selectinload(Tag.aliases))
.outerjoin(TagAlias)
.where(or_(Tag.name == tag_name, TagAlias.name == tag_name))
)
tag = session.scalar(statement)
if tag is not None:
session.expunge(tag)
for parent in tag.parent_tags:
session.expunge(parent)
for alias in tag.aliases:
session.expunge(alias)
return tag
return session.scalar(statement)
def get_alias(self, tag_id: int, alias_id: int) -> TagAlias | None:
with Session(self.engine) as session:
@@ -1588,45 +1414,6 @@ class Library:
return session.scalar(statement)
def get_tag_hierarchy(self, tag_ids: Iterable[int]) -> dict[int, Tag]:
"""Get a dictionary containing tags in `tag_ids` and all of their ancestor tags."""
current_tag_ids: set[int] = set(tag_ids)
all_tag_ids: set[int] = set()
all_tags: dict[int, Tag] = {}
all_tag_parents: dict[int, list[int]] = {}
with Session(self.engine) as session:
while len(current_tag_ids) > 0:
all_tag_ids.update(current_tag_ids)
statement = select(TagParent).where(TagParent.child_id.in_(current_tag_ids))
tag_parents = session.scalars(statement).fetchall()
current_tag_ids.clear()
for tag_parent in tag_parents:
all_tag_parents.setdefault(tag_parent.child_id, []).append(tag_parent.parent_id)
current_tag_ids.add(tag_parent.parent_id)
current_tag_ids = current_tag_ids.difference(all_tag_ids)
statement = select(Tag).where(Tag.id.in_(all_tag_ids))
statement = statement.options(
noload(Tag.parent_tags), selectinload(Tag.aliases), joinedload(Tag.color)
)
tags = session.scalars(statement).fetchall()
for tag in tags:
all_tags[tag.id] = tag
for tag in all_tags.values():
# Sqlalchemy tracks this as a change to the parent_tags field
tag.parent_tags = {all_tags[p] for p in all_tag_parents.get(tag.id, [])}
# When calling session.add with this tag instance sqlalchemy will
# attempt to create TagParents that already exist.
state = inspect(tag)
# Prevent sqlalchemy from thinking any fields are different from what's commited
# commited_state contains original values for fields that have changed.
# empty when no fields have changed
state.committed_state.clear()
return all_tags
def add_parent_tag(self, parent_id: int, child_id: int) -> bool:
if parent_id == child_id:
return False
@@ -1758,105 +1545,35 @@ class Library:
# load all tag's parent tags to know which to remove
prev_parent_tags = session.scalars(
select(TagParent).where(TagParent.child_id == tag.id)
select(TagParent).where(TagParent.parent_id == tag.id)
).all()
for parent_tag in prev_parent_tags:
if parent_tag.parent_id not in parent_ids:
if parent_tag.child_id not in parent_ids:
session.delete(parent_tag)
else:
# no change, remove from list
parent_ids.remove(parent_tag.parent_id)
parent_ids.remove(parent_tag.child_id)
# create remaining items
for parent_id in parent_ids:
# add new parent tag
parent_tag = TagParent(
parent_id=parent_id,
child_id=tag.id,
parent_id=tag.id,
child_id=parent_id,
)
session.add(parent_tag)
def get_version(self, key: str) -> int:
"""Get a version value from the DB.
Args:
key(str): The key for the name of the version type to set.
"""
with Session(self.engine) as session:
engine = sqlalchemy.inspect(self.engine)
try:
# "Version" table added in DB_VERSION 101
if engine and engine.has_table("Version"):
version = session.scalar(select(Version).where(Version.key == key))
assert version
return version.value
# NOTE: The "Preferences" table has been depreciated as of TagStudio 9.5.4
# and is set to be removed in a future release.
else:
pref_version = session.scalar(
select(Preferences).where(Preferences.key == DB_VERSION_LEGACY_KEY)
)
assert pref_version
assert isinstance(pref_version.value, int)
return pref_version.value
except Exception:
return 0
def set_version(self, key: str, value: int) -> None:
"""Set a version value to the DB.
Args:
key(str): The key for the name of the version type to set.
value(int): The version value to set.
"""
with Session(self.engine) as session:
try:
version = session.scalar(select(Version).where(Version.key == key))
assert version
version.value = value
session.add(version)
session.commit()
# If a depreciated "Preferences" table is found, update the version value to be read
# by older TagStudio versions.
engine = sqlalchemy.inspect(self.engine)
if engine and engine.has_table("Preferences"):
pref = session.scalar(
select(Preferences).where(Preferences.key == DB_VERSION_LEGACY_KEY)
)
assert pref is not None
pref.value = value # pyright: ignore
session.add(pref)
session.commit()
except (IntegrityError, AssertionError) as e:
logger.error("[Library][ERROR] Couldn't add default tag color namespaces", error=e)
session.rollback()
def prefs(self, key: str | LibraryPrefs):
def prefs(self, key: LibraryPrefs):
# load given item from Preferences table
with Session(self.engine) as session:
if isinstance(key, LibraryPrefs):
return session.scalar(select(Preferences).where(Preferences.key == key.name)).value
else:
return session.scalar(select(Preferences).where(Preferences.key == key)).value
return session.scalar(select(Preferences).where(Preferences.key == key.name)).value
def set_prefs(self, key: str | LibraryPrefs, value: Any) -> None:
def set_prefs(self, key: LibraryPrefs, value) -> None:
# set given item in Preferences table
with Session(self.engine) as session:
# load existing preference and update value
stuff = session.scalars(select(Preferences))
logger.info([x.key for x in list(stuff)])
pref: Preferences = unwrap(
session.scalar(
select(Preferences).where(
Preferences.key == (key.name if isinstance(key, LibraryPrefs) else key)
)
)
)
logger.info("loading pref", pref=pref, key=key, value=value)
pref = session.scalar(select(Preferences).where(Preferences.key == key.name))
pref.value = value
session.add(pref)
session.commit()
@@ -1881,23 +1598,18 @@ class Library:
value=field.value,
)
def merge_entries(self, from_entry: Entry, into_entry: Entry) -> bool:
def merge_entries(self, from_entry: Entry, into_entry: Entry) -> None:
"""Add fields and tags from the first entry to the second, and then delete the first."""
success = True
for field in from_entry.fields:
result = self.add_field_to_entry(
self.add_field_to_entry(
entry_id=into_entry.id,
field_id=field.type_key,
value=field.value,
)
if not result:
success = False
tag_ids = [tag.id for tag in from_entry.tags]
self.add_tags_to_entries(into_entry.id, tag_ids)
self.remove_entries([from_entry.id])
return success
@property
def tag_color_groups(self) -> dict[str, list[TagColorGroup]]:
"""Return every TagColorGroup in the library."""
@@ -1922,10 +1634,7 @@ class Library:
session.expunge(en)
return dict(
sorted(
color_groups.items(),
key=lambda kv: self.get_namespace_name(kv[0]).lower(),
)
sorted(color_groups.items(), key=lambda kv: self.get_namespace_name(kv[0]).lower())
)
@property

View File

@@ -7,7 +7,6 @@ from pathlib import Path
from sqlalchemy import JSON, ForeignKey, ForeignKeyConstraint, Integer, event
from sqlalchemy.orm import Mapped, mapped_column, relationship
from typing_extensions import deprecated
from tagstudio.core.constants import TAG_ARCHIVED, TAG_FAVORITE
from tagstudio.core.library.alchemy.db import Base, PathType
@@ -100,8 +99,8 @@ class Tag(Base):
aliases: Mapped[set[TagAlias]] = relationship(back_populates="tag")
parent_tags: Mapped[set["Tag"]] = relationship(
secondary=TagParent.__tablename__,
primaryjoin="Tag.id == TagParent.child_id",
secondaryjoin="Tag.id == TagParent.parent_id",
primaryjoin="Tag.id == TagParent.parent_id",
secondaryjoin="Tag.id == TagParent.child_id",
back_populates="parent_tags",
)
disambiguation_id: Mapped[int | None]
@@ -127,8 +126,8 @@ class Tag(Base):
def __init__(
self,
name: str,
id: int | None = None,
name: str | None = None,
shorthand: str | None = None,
aliases: set[TagAlias] | None = None,
parent_tags: set["Tag"] | None = None,
@@ -147,7 +146,8 @@ class Tag(Base):
self.shorthand = shorthand
self.disambiguation_id = disambiguation_id
self.is_category = is_category
self.id = id # pyright: ignore[reportAttributeAccessIssue]
assert not self.id
self.id = id
super().__init__()
def __str__(self) -> str:
@@ -156,9 +156,6 @@ class Tag(Base):
def __repr__(self) -> str:
return self.__str__()
def __hash__(self) -> int:
return hash(self.id)
def __lt__(self, other) -> bool:
return self.name < other.name
@@ -190,7 +187,6 @@ class Entry(Base):
folder: Mapped[Folder] = relationship("Folder")
path: Mapped[Path] = mapped_column(PathType, unique=True)
filename: Mapped[str] = mapped_column()
suffix: Mapped[str] = mapped_column()
date_created: Mapped[dt | None]
date_modified: Mapped[dt | None]
@@ -235,8 +231,7 @@ class Entry(Base):
) -> None:
self.path = path
self.folder = folder
self.id = id # pyright: ignore[reportAttributeAccessIssue]
self.filename = path.name
self.id = id
self.suffix = path.suffix.lstrip(".").lower()
# The date the file associated with this entry was created.
@@ -314,18 +309,8 @@ def slugify_field_key(mapper, connection, target):
target.key = slugify(target.tag)
# NOTE: The "Preferences" table has been depreciated as of TagStudio 9.5.4
# and is set to be removed in a future release.
@deprecated("Use `Version` for storing version, and `ts_ignore` system for file exclusion.")
class Preferences(Base):
__tablename__ = "preferences"
key: Mapped[str] = mapped_column(primary_key=True)
value: Mapped[dict] = mapped_column(JSON, nullable=False)
class Version(Base):
__tablename__ = "versions"
key: Mapped[str] = mapped_column(primary_key=True)
value: Mapped[int] = mapped_column(nullable=False, default=0)

View File

@@ -14,7 +14,6 @@ from tagstudio.core.library.alchemy.joins import TagEntry
from tagstudio.core.library.alchemy.models import Entry, Tag, TagAlias
from tagstudio.core.media_types import FILETYPE_EQUIVALENTS, MediaCategories
from tagstudio.core.query_lang.ast import (
AST,
ANDList,
BaseVisitor,
Constraint,
@@ -32,16 +31,18 @@ else:
logger = structlog.get_logger(__name__)
# TODO: Reevaluate after subtags -> parent tags name change
TAG_CHILDREN_ID_QUERY = text("""
-- Note for this entire query that tag_parents.child_id is the parent id and tag_parents.parent_id is the child id due to bad naming
WITH RECURSIVE ChildTags AS (
SELECT :tag_id AS tag_id
UNION
SELECT tp.child_id AS tag_id
FROM tag_parents tp
INNER JOIN ChildTags c ON tp.parent_id = c.tag_id
SELECT :tag_id AS child_id
UNION ALL
SELECT tp.parent_id AS child_id
FROM tag_parents tp
INNER JOIN ChildTags c ON tp.child_id = c.child_id
)
SELECT tag_id FROM ChildTags;
""")
SELECT child_id FROM ChildTags;
""") # noqa: E501
def get_filetype_equivalency_list(item: str) -> list[str] | set[str]:
@@ -57,15 +58,42 @@ class SQLBoolExpressionBuilder(BaseVisitor[ColumnElement[bool]]):
self.lib = lib
def visit_or_list(self, node: ORList) -> ColumnElement[bool]:
tag_ids, bool_expressions = self.__separate_tags(node.elements, only_single=False)
if len(tag_ids) > 0:
bool_expressions.append(self.__entry_has_any_tags(tag_ids))
return or_(*bool_expressions)
return or_(*[self.visit(element) for element in node.elements])
def visit_and_list(self, node: ANDList) -> ColumnElement[bool]:
tag_ids, bool_expressions = self.__separate_tags(node.terms, only_single=True)
if len(tag_ids) > 0:
tag_ids: list[int] = []
bool_expressions: list[ColumnElement[bool]] = []
# Search for TagID / unambiguous Tag Constraints and store the respective tag ids separately
for term in node.terms:
if isinstance(term, Constraint) and len(term.properties) == 0:
match term.type:
case ConstraintType.TagID:
try:
tag_ids.append(int(term.value))
except ValueError:
logger.error(
"[SQLBoolExpressionBuilder] Could not cast value to an int Tag ID",
value=term.value,
)
continue
case ConstraintType.Tag:
if len(ids := self.__get_tag_ids(term.value)) == 1:
tag_ids.append(ids[0])
continue
bool_expressions.append(self.visit(term))
# If there are at least two tag ids use a relational division query
# to efficiently check all of them
if len(tag_ids) > 1:
bool_expressions.append(self.__entry_has_all_tags(tag_ids))
# If there is just one tag id, check the normal way
elif len(tag_ids) == 1:
bool_expressions.append(
self.__entry_satisfies_expression(TagEntry.tag_id == tag_ids[0])
)
return and_(*bool_expressions)
def visit_constraint(self, node: Constraint) -> ColumnElement[bool]:
@@ -74,9 +102,9 @@ class SQLBoolExpressionBuilder(BaseVisitor[ColumnElement[bool]]):
raise NotImplementedError("Properties are not implemented yet") # TODO TSQLANG
if node.type == ConstraintType.Tag:
return self.__entry_has_any_tags(self.__get_tag_ids(node.value))
return self.__entry_matches_tag_ids(self.__get_tag_ids(node.value))
elif node.type == ConstraintType.TagID:
return self.__entry_has_any_tags([int(node.value)])
return self.__entry_matches_tag_ids([int(node.value)])
elif node.type == ConstraintType.Path:
ilike = False
glob = False
@@ -119,12 +147,21 @@ class SQLBoolExpressionBuilder(BaseVisitor[ColumnElement[bool]]):
# raise exception if Constraint stays unhandled
raise NotImplementedError("This type of constraint is not implemented yet")
def visit_property(self, node: Property) -> ColumnElement[bool]:
def visit_property(self, node: Property) -> None:
raise NotImplementedError("This should never be reached!")
def visit_not(self, node: Not) -> ColumnElement[bool]:
return ~self.visit(node.child)
def __entry_matches_tag_ids(self, tag_ids: list[int]) -> ColumnElement[bool]:
"""Returns a boolean expression that is true if the entry has at least one of the supplied tags.""" # noqa: E501
return (
select(1)
.correlate(Entry)
.where(and_(TagEntry.entry_id == Entry.id, TagEntry.tag_id.in_(tag_ids)))
.exists()
)
def __get_tag_ids(self, tag_name: str, include_children: bool = True) -> list[int]:
"""Given a tag name find the ids of all tags that this name could refer to."""
with Session(self.lib.engine) as session:
@@ -148,36 +185,6 @@ class SQLBoolExpressionBuilder(BaseVisitor[ColumnElement[bool]]):
outp.extend(list(session.scalars(TAG_CHILDREN_ID_QUERY, {"tag_id": tag_id})))
return outp
def __separate_tags(
self, terms: list[AST], only_single: bool = True
) -> tuple[list[int], list[ColumnElement[bool]]]:
tag_ids: list[int] = []
bool_expressions: list[ColumnElement[bool]] = []
for term in terms:
if isinstance(term, Constraint) and len(term.properties) == 0:
match term.type:
case ConstraintType.TagID:
try:
tag_ids.append(int(term.value))
except ValueError:
logger.error(
"[SQLBoolExpressionBuilder] Could not cast value to an int Tag ID",
value=term.value,
)
continue
case ConstraintType.Tag:
ids = self.__get_tag_ids(term.value)
if not only_single:
tag_ids.extend(ids)
continue
elif len(ids) == 1:
tag_ids.append(ids[0])
continue
bool_expressions.append(self.visit(term))
return tag_ids, bool_expressions
def __entry_has_all_tags(self, tag_ids: list[int]) -> ColumnElement[bool]:
"""Returns Binary Expression that is true if the Entry has all provided tag ids."""
# Relational Division Query
@@ -188,8 +195,9 @@ class SQLBoolExpressionBuilder(BaseVisitor[ColumnElement[bool]]):
.having(func.count(distinct(TagEntry.tag_id)) == len(tag_ids))
)
def __entry_has_any_tags(self, tag_ids: list[int]) -> ColumnElement[bool]:
"""Returns Binary Expression that is true if the Entry has any of the provided tag ids."""
return Entry.id.in_(
select(TagEntry.entry_id).where(TagEntry.tag_id.in_(tag_ids)).distinct()
)
def __entry_satisfies_expression(self, expr: ColumnElement[bool]) -> ColumnElement[bool]:
"""Returns Binary Expression that is true if the Entry satisfies the column expression.
Executed on: Entry ⟕ TagEntry (Entry LEFT OUTER JOIN TagEntry).
"""
return Entry.id.in_(select(Entry.id).outerjoin(TagEntry).where(expr))

View File

@@ -1,187 +0,0 @@
# Copyright (C) 2025 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from copy import deepcopy
from pathlib import Path
import structlog
import wcmatch.fnmatch as fnmatch
from wcmatch import glob, pathlib
from tagstudio.core.constants import IGNORE_NAME, TS_FOLDER_NAME
from tagstudio.core.singleton import Singleton
logger = structlog.get_logger()
PATH_GLOB_FLAGS = glob.GLOBSTARLONG | glob.DOTGLOB | glob.NEGATE | pathlib.MATCHBASE
GLOBAL_IGNORE = [
# TagStudio -------------------
f"{TS_FOLDER_NAME}",
# Trash -----------------------
".Trash-*",
".Trash",
".Trashes",
"$RECYCLE.BIN",
# System ----------------------
"._*",
".DS_Store",
".fseventsd",
".Spotlight-V100",
".TemporaryItems",
"desktop.ini",
"System Volume Information",
".localized",
]
def ignore_to_glob(ignore_patterns: list[str]) -> list[str]:
"""Convert .gitignore-like patterns to explicit glob syntax.
Args:
ignore_patterns (list[str]): The .gitignore-like patterns to convert.
"""
glob_patterns: list[str] = deepcopy(ignore_patterns)
additional_patterns: list[str] = []
# Mimic implicit .gitignore syntax behavior for the SQLite GLOB function.
for pattern in glob_patterns:
# Temporarily remove any exclusion character before processing
exclusion_char = ""
gp = pattern
if pattern.startswith("!"):
gp = pattern[1:]
exclusion_char = "!"
if not gp.startswith("**/") and not gp.startswith("*/") and not gp.startswith("/"):
# Create a version of a prefix-less pattern that starts with "**/"
gp = "**/" + gp
additional_patterns.append(exclusion_char + gp)
gp = gp.removesuffix("/**").removesuffix("/*").removesuffix("/")
additional_patterns.append(exclusion_char + gp)
gp = gp.removeprefix("**/").removeprefix("*/")
additional_patterns.append(exclusion_char + gp)
glob_patterns = glob_patterns + additional_patterns
# Add "/**" suffix to suffix-less patterns to match implicit .gitignore behavior.
for pattern in glob_patterns:
if pattern.endswith("/**"):
continue
glob_patterns.append(pattern.removesuffix("/*").removesuffix("/") + "/**")
glob_patterns = list(set(glob_patterns))
logger.info("[Ignore]", glob_patterns=glob_patterns)
return glob_patterns
class Ignore(metaclass=Singleton):
"""Class for processing and managing glob-like file ignore file patterns."""
_last_loaded: tuple[Path, float] | None = None
_patterns: list[str] = []
compiled_patterns: fnmatch.WcMatcher | None = None
@staticmethod
def read_ignore_file(library_dir: Path) -> list[str]:
"""Get the entire raw '.ts_ignore' file contents as a list of strings."""
ts_ignore_path = Path(library_dir / TS_FOLDER_NAME / IGNORE_NAME)
if not ts_ignore_path.exists():
logger.info(
"[Ignore] No .ts_ignore file found",
path=ts_ignore_path,
)
return []
with open(ts_ignore_path, encoding="utf8") as f:
return f.readlines()
@staticmethod
def write_ignore_file(library_dir: Path, lines: list[str]) -> None:
"""Write to the '.ts_ignore' file."""
ts_ignore_path = Path(library_dir / TS_FOLDER_NAME / IGNORE_NAME)
if not ts_ignore_path.exists():
logger.info(
"[Ignore] No .ts_ignore file found",
path=ts_ignore_path,
)
return
with open(ts_ignore_path, "w", encoding="utf8") as f:
f.writelines(lines)
@staticmethod
def get_patterns(library_dir: Path, include_global: bool = True) -> list[str]:
"""Get the ignore patterns for the given library directory.
Args:
library_dir (Path): The path of the library to load patterns from.
include_global (bool): Flag for including the global ignore set.
In most scenarios, this should be True.
"""
patterns = GLOBAL_IGNORE if include_global else []
ts_ignore_path = Path(library_dir / TS_FOLDER_NAME / IGNORE_NAME)
if not ts_ignore_path.exists():
logger.info(
"[Ignore] No .ts_ignore file found",
path=ts_ignore_path,
)
Ignore._last_loaded = None
Ignore._patterns = patterns
return Ignore._patterns
# Process the .ts_ignore file if the previous result is non-existent or outdated.
loaded = (ts_ignore_path, ts_ignore_path.stat().st_mtime)
if not Ignore._last_loaded or (Ignore._last_loaded and Ignore._last_loaded != loaded):
logger.info(
"[Ignore] Processing the .ts_ignore file...",
library=library_dir,
last_mtime=Ignore._last_loaded[1] if Ignore._last_loaded else None,
new_mtime=loaded[1],
)
Ignore._patterns = patterns + Ignore._load_ignore_file(ts_ignore_path)
Ignore.compiled_patterns = fnmatch.compile(
ignore_to_glob(Ignore._patterns),
PATH_GLOB_FLAGS,
)
else:
logger.info(
"[Ignore] No updates to the .ts_ignore detected",
library=library_dir,
last_mtime=Ignore._last_loaded[1],
new_mtime=loaded[1],
)
Ignore._last_loaded = loaded
return Ignore._patterns
@staticmethod
def _load_ignore_file(path: Path) -> list[str]:
"""Load and process the .ts_ignore file into a list of glob patterns.
Args:
path (Path): The path of the .ts_ignore file.
"""
patterns: list[str] = []
if path.exists():
with open(path, encoding="utf8") as f:
for line_raw in f.readlines():
line = line_raw.strip()
# Ignore blank lines and comments
if not line or line.startswith("#"):
continue
patterns.append(line)
return patterns

View File

@@ -1,27 +1,16 @@
# Copyright (C) 2025 Travis Abendshien (CyanVoxel).
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import logging
import mimetypes
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
import structlog
logging.basicConfig(format="%(message)s", level=logging.INFO)
logger = structlog.get_logger(__name__)
FILETYPE_EQUIVALENTS = [
set(["aif", "aiff", "aifc"]),
set(["html", "htm", "xhtml", "shtml", "dhtml"]),
set(["jfif", "jpeg_large", "jpeg", "jpg_large", "jpg"]),
set(["json", "jsonc", "json5"]),
set(["md", "markdown", "mkd", "rmd"]),
set(["tar.gz", "tgz"]),
set(["xml", "xul"]),
set(["yaml", "yml"]),
]
FILETYPE_EQUIVALENTS = [set(["jpg", "jpeg"])]
class MediaType(str, Enum):
@@ -33,7 +22,6 @@ class MediaType(str, Enum):
AUDIO_MIDI = "audio_midi"
AUDIO = "audio"
BLENDER = "blender"
CODE = "code"
DATABASE = "database"
DISK_IMAGE = "disk_image"
DOCUMENT = "document"
@@ -44,7 +32,6 @@ class MediaType(str, Enum):
IMAGE_VECTOR = "image_vector"
IMAGE = "image"
INSTALLER = "installer"
IWORK = "iwork"
MATERIAL = "material"
MODEL = "model"
OPEN_DOCUMENT = "open_document"
@@ -53,7 +40,6 @@ class MediaType(str, Enum):
PLAINTEXT = "plaintext"
PRESENTATION = "presentation"
PROGRAM = "program"
SHADER = "shader"
SHORTCUT = "shortcut"
SOURCE_ENGINE = "source_engine"
SPREADSHEET = "spreadsheet"
@@ -81,21 +67,6 @@ class MediaCategory:
name: str
is_iana: bool = False
def contains(self, ext: str, mime_fallback: bool = False) -> bool:
"""Check if an extension is a member of this MediaCategory.
Args:
ext (str): File extension with a leading "." and in all lowercase.
mime_fallback (bool): Flag to guess MIME type if no set matches are made.
"""
if ext in self.extensions:
return True
elif mime_fallback and self.is_iana:
mime_type: str | None = mimetypes.guess_type(Path("x" + ext), strict=False)[0]
if mime_type is not None and mime_type.startswith(self.media_type.value):
return True
return False
class MediaCategories:
"""Contain pre-made MediaCategory objects as well as methods to interact with them."""
@@ -109,7 +80,6 @@ class MediaCategories:
".psd",
}
_AFFINITY_PHOTO_SET: set[str] = {".afphoto"}
_KRITA_SET: set[str] = {".kra", ".krz"}
_ARCHIVE_SET: set[str] = {
".7z",
".gz",
@@ -126,10 +96,8 @@ class MediaCategories:
_AUDIO_SET: set[str] = {
".aac",
".aif",
".aifc",
".aiff",
".alac",
".caf",
".flac",
".m4a",
".m4p",
@@ -175,75 +143,13 @@ class MediaCategories:
".blend31",
".blend32",
}
_CODE_SET: set[str] = {
".bat",
".cfg",
".conf",
".cpp",
".cs",
".csh",
".css",
".d",
".dhtml",
".fgd",
".fish",
".gitignore",
".h",
".hpp",
".htm",
".html",
".inf",
".ini",
".js",
".json",
".json5",
".jsonc",
".jsx",
".kv3",
".lua",
".meta",
".nix",
".nu",
".nut",
".php",
".plist",
".prefs",
".ps1",
".py",
".pyi",
".qml",
".qrc",
".qss",
".rs",
".sh",
".shtml",
".sip",
".spec",
".tcl",
".timestamp",
".toml",
".ts",
".tsx",
".vcfg",
".vdf",
".vmt",
".vqlayout",
".vsc",
".vsnd_template",
".xhtml",
".xml",
".xul",
".yaml",
".yml",
}
_DATABASE_SET: set[str] = {
".accdb",
".mdb",
".pdb",
".sqlite",
".sqlite3",
}
_DISK_IMAGE_SET: set[str] = {".bios", ".dmg", ".fhdx", ".iso"}
_DISK_IMAGE_SET: set[str] = {".bios", ".dmg", ".iso"}
_DOCUMENT_SET: set[str] = {
".doc",
".docm",
@@ -260,23 +166,23 @@ class MediaCategories:
".wps",
}
_EBOOK_SET: set[str] = {
".azw",
".azw3",
".cb7",
".cba",
".cbr",
".cbt",
".cbz",
".djvu",
".epub",
".fb2",
".ibook",
".inf",
".kfx",
".lit",
".mobi",
".pdb",
".prc",
# ".azw",
# ".azw3",
# ".cb7",
# ".cba",
# ".cbr",
# ".cbt",
# ".cbz",
# ".djvu",
# ".fb2",
# ".ibook",
# ".inf",
# ".kfx",
# ".lit",
# ".mobi",
# ".pdb"
# ".prc",
}
_FONT_SET: set[str] = {
".fon",
@@ -298,15 +204,12 @@ class MediaCategories:
".crw",
".dng",
".nef",
".nrw",
".orf",
".raf",
".raw",
".rw2",
".srf",
".srf2",
}
_IMAGE_VECTOR_SET: set[str] = {".eps", ".epsf", ".epsi", ".svg", ".svgz"}
_IMAGE_VECTOR_SET: set[str] = {".svg"}
_IMAGE_RASTER_SET: set[str] = {
".apng",
".avif",
@@ -315,7 +218,6 @@ class MediaCategories:
".gif",
".heic",
".heif",
".icns",
".j2k",
".jfif",
".jp2",
@@ -333,7 +235,6 @@ class MediaCategories:
".webp",
}
_INSTALLER_SET: set[str] = {".appx", ".msi", ".msix"}
_IWORK_SET: set[str] = {".key", ".pages", ".numbers"}
_MATERIAL_SET: set[str] = {".mtl"}
_MODEL_SET: set[str] = {".3ds", ".fbx", ".obj", ".stl"}
_OPEN_DOCUMENT_SET: set[str] = {
@@ -347,7 +248,6 @@ class MediaCategories:
".odp",
".ods",
".odt",
".ora",
}
_PACKAGE_SET: set[str] = {
".aab",
@@ -358,22 +258,51 @@ class MediaCategories:
".pkg",
".xapk",
}
_PDF_SET: set[str] = {".pdf"}
_PDF_SET: set[str] = {
".pdf",
}
_PLAINTEXT_SET: set[str] = {
".bat",
".cfg",
".conf",
".cpp",
".cs",
".css",
".csv",
".i3u",
".lang",
".lock",
".log",
".markdown",
".fgd",
".gi",
".h",
".hpp",
".htm",
".html",
".inf",
".ini",
".js",
".json",
".jsonc",
".kv3",
".lua",
".md",
".mkd",
".rmd",
".text",
".nut",
".php",
".plist",
".prefs",
".py",
".pyc",
".qss",
".sh",
".toml",
".ts",
".txt",
"contributing",
"license",
"readme",
".vcfg",
".vdf",
".vmt",
".vqlayout",
".vsc",
".vsnd_template",
".xml",
".yaml",
".yml",
}
_PRESENTATION_SET: set[str] = {
".key",
@@ -381,16 +310,9 @@ class MediaCategories:
".ppt",
".pptx",
}
_PROGRAM_SET: set[str] = {".app", ".bin", ".exe"}
_SOURCE_ENGINE_SET: set[str] = {".vtf"}
_SHADER_SET: set[str] = {
".effect",
".frag",
".fsh",
".glsl",
".shader",
".vert",
".vsh",
_PROGRAM_SET: set[str] = {".app", ".exe"}
_SOURCE_ENGINE_SET: set[str] = {
".vtf",
}
_SHORTCUT_SET: set[str] = {".desktop", ".lnk", ".url"}
_SPREADSHEET_SET: set[str] = {
@@ -413,7 +335,6 @@ class MediaCategories:
".mp4",
".webm",
".wmv",
".ts",
}
ADOBE_PHOTOSHOP_TYPES = MediaCategory(
@@ -452,12 +373,6 @@ class MediaCategories:
is_iana=False,
name="blender",
)
CODE_TYPES = MediaCategory(
media_type=MediaType.CODE,
extensions=_CODE_SET,
is_iana=False,
name="code",
)
DATABASE_TYPES = MediaCategory(
media_type=MediaType.DATABASE,
extensions=_DATABASE_SET,
@@ -524,12 +439,6 @@ class MediaCategories:
is_iana=False,
name="installer",
)
IWORK_TYPES = MediaCategory(
media_type=MediaType.IWORK,
extensions=_IWORK_SET,
is_iana=False,
name="iwork",
)
MATERIAL_TYPES = MediaCategory(
media_type=MediaType.MATERIAL,
extensions=_MATERIAL_SET,
@@ -562,7 +471,7 @@ class MediaCategories:
)
PLAINTEXT_TYPES = MediaCategory(
media_type=MediaType.PLAINTEXT,
extensions=_PLAINTEXT_SET | _CODE_SET,
extensions=_PLAINTEXT_SET,
is_iana=False,
name="plaintext",
)
@@ -578,12 +487,6 @@ class MediaCategories:
is_iana=False,
name="program",
)
SHADER_TYPES = MediaCategory(
media_type=MediaType.SHADER,
extensions=_SHADER_SET,
is_iana=False,
name="shader",
)
SHORTCUT_TYPES = MediaCategory(
media_type=MediaType.SHORTCUT,
extensions=_SHORTCUT_SET,
@@ -614,12 +517,6 @@ class MediaCategories:
is_iana=True,
name="video",
)
KRITA_TYPES = MediaCategory(
media_type=MediaType.IMAGE,
extensions=_KRITA_SET,
is_iana=False,
name="krita",
)
ALL_CATEGORIES = [
ADOBE_PHOTOSHOP_TYPES,
@@ -638,7 +535,6 @@ class MediaCategories:
IMAGE_TYPES,
IMAGE_VECTOR_TYPES,
INSTALLER_TYPES,
IWORK_TYPES,
MATERIAL_TYPES,
MODEL_TYPES,
OPEN_DOCUMENT_TYPES,
@@ -647,14 +543,11 @@ class MediaCategories:
PLAINTEXT_TYPES,
PRESENTATION_TYPES,
PROGRAM_TYPES,
CODE_TYPES,
SHADER_TYPES,
SHORTCUT_TYPES,
SOURCE_ENGINE_TYPES,
SPREADSHEET_TYPES,
TEXT_TYPES,
VIDEO_TYPES,
KRITA_TYPES,
]
@staticmethod
@@ -666,11 +559,16 @@ class MediaCategories:
mime_fallback (bool): Flag to guess MIME type if no set matches are made.
"""
media_types: set[MediaType] = set()
# mime_guess: bool = False
for cat in MediaCategories.ALL_CATEGORIES:
if cat.contains(ext, mime_fallback):
if ext in cat.extensions:
media_types.add(cat.media_type)
elif mime_fallback and cat.is_iana:
mime_type: str = mimetypes.guess_type(Path("x" + ext), strict=False)[0]
if mime_type and mime_type.startswith(cat.media_type.value):
media_types.add(cat.media_type)
# mime_guess = True
return media_types
@staticmethod
@@ -682,4 +580,10 @@ class MediaCategories:
media_cat (MediaCategory): The MediaCategory to to check for extension membership.
mime_fallback (bool): Flag to guess MIME type if no set matches are made.
"""
return media_cat.contains(ext, mime_fallback)
if ext in media_cat.extensions:
return True
elif mime_fallback and media_cat.is_iana:
mime_type: str = mimetypes.guess_type(Path("x" + ext), strict=False)[0]
if mime_type and mime_type.startswith(media_cat.media_type.value):
return True
return False

View File

@@ -26,11 +26,9 @@ class UiColor(IntEnum):
THEME_DARK = 1
THEME_LIGHT = 2
RED = 3
ORANGE = 4
AMBER = 5
GREEN = 6
BLUE = 7
PURPLE = 8
GREEN = 4
BLUE = 5
PURPLE = 6
TAG_COLORS: dict[TagColorEnum, dict[ColorType, Any]] = {
@@ -56,18 +54,6 @@ UI_COLORS: dict[UiColor, dict[ColorType, Any]] = {
ColorType.LIGHT_ACCENT: "#f39caa",
ColorType.DARK_ACCENT: "#440d12",
},
UiColor.ORANGE: {
ColorType.PRIMARY: "#FF8020",
ColorType.BORDER: "#E86919",
ColorType.LIGHT_ACCENT: "#FFECB3",
ColorType.DARK_ACCENT: "#752809",
},
UiColor.AMBER: {
ColorType.PRIMARY: "#FFC107",
ColorType.BORDER: "#FFD54F",
ColorType.LIGHT_ACCENT: "#FFECB3",
ColorType.DARK_ACCENT: "#772505",
},
UiColor.GREEN: {
ColorType.PRIMARY: "#28bb48",
ColorType.BORDER: "#43c568",

View File

@@ -1,6 +1,6 @@
from abc import ABC, abstractmethod
from enum import Enum
from typing import Generic, TypeVar, Union
from typing import Generic, TypeVar
class ConstraintType(Enum):
@@ -12,7 +12,7 @@ class ConstraintType(Enum):
Special = 5
@staticmethod
def from_string(text: str) -> Union["ConstraintType", None]:
def from_string(text: str) -> "ConstraintType":
return {
"tag": ConstraintType.Tag,
"tag_id": ConstraintType.TagID,
@@ -24,7 +24,7 @@ class ConstraintType(Enum):
class AST:
parent: Union["AST", None] = None
parent: "AST" = None
def __str__(self):
class_name = self.__class__.__name__

View File

@@ -26,19 +26,19 @@ class Token:
start: int
end: int
def __init__(self, type: TokenType, value: Any, start: int, end: int) -> None:
def __init__(self, type: TokenType, value: Any, start: int = None, end: int = None) -> None:
self.type = type
self.value = value
self.start = start
self.end = end
@staticmethod
def from_type(type: TokenType, pos: int) -> "Token":
def from_type(type: TokenType, pos: int = None) -> "Token":
return Token(type, None, pos, pos)
@staticmethod
def EOF(pos: int) -> "Token": # noqa: N802
return Token.from_type(TokenType.EOF, pos)
def EOF() -> "Token": # noqa: N802
return Token.from_type(TokenType.EOF)
def __str__(self) -> str:
return f"Token({self.type}, {self.value}, {self.start}, {self.end})" # pragma: nocover
@@ -50,7 +50,7 @@ class Token:
class Tokenizer:
text: str
pos: int
current_char: str | None
current_char: str
ESCAPABLE_CHARS = ["\\", '"', '"']
NOT_IN_ULITERAL = [":", " ", "[", "]", "(", ")", "=", ","]
@@ -63,7 +63,7 @@ class Tokenizer:
def get_next_token(self) -> Token:
self.__skip_whitespace()
if self.current_char is None:
return Token.EOF(self.pos)
return Token.EOF()
if self.current_char in ("'", '"'):
return self.__quoted_string()
@@ -119,8 +119,6 @@ class Tokenizer:
out = ""
while escape or self.current_char != quote:
if self.current_char is None:
raise ParsingError(start, self.pos, "Unterminated quoted string")
if escape:
escape = False
if self.current_char not in Tokenizer.ESCAPABLE_CHARS:

View File

@@ -11,7 +11,7 @@ from tagstudio.core.constants import TS_FOLDER_NAME
from tagstudio.core.library.alchemy.fields import _FieldID
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.utils.unlinked_registry import logger
from tagstudio.core.utils.missing_files import logger
class TagStudioCore:

View File

@@ -4,7 +4,7 @@ from pathlib import Path
import structlog
from tagstudio.core.library.alchemy.enums import BrowsingState
from tagstudio.core.library.alchemy.enums import FilterState
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
@@ -52,15 +52,14 @@ class DupeRegistry:
continue
results = self.library.search_library(
BrowsingState.from_path(path_relative), 500
FilterState.from_path(path_relative),
)
entries = self.library.get_entries(results.ids)
if not results:
# file not in library
continue
files.append(entries[0])
files.append(results[0])
if not len(files) > 1:
# only one file in the group, nothing to do
@@ -80,7 +79,7 @@ class DupeRegistry:
)
for i, entries in enumerate(self.groups):
remove_ids = entries[1:]
remove_ids = [x.id for x in entries[1:]]
logger.info("Removing entries group", ids=remove_ids)
self.library.remove_entries(remove_ids)
yield i - 1 # The -1 waits for the next step to finish

View File

@@ -1,51 +0,0 @@
# Copyright (C) 2025
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
import structlog
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.library.ignore import Ignore
from tagstudio.core.utils.types import unwrap
logger = structlog.get_logger(__name__)
@dataclass
class IgnoredRegistry:
"""State tracker for ignored entries."""
lib: Library
ignored_entries: list[Entry] = field(default_factory=list)
@property
def ignored_count(self) -> int:
return len(self.ignored_entries)
def reset(self):
self.ignored_entries.clear()
def refresh_ignored_entries(self) -> Iterator[int]:
"""Track the number of entries that would otherwise be ignored by the current rules."""
logger.info("[IgnoredRegistry] Refreshing ignored entries...")
self.ignored_entries = []
library_dir: Path = unwrap(self.lib.library_dir)
for i, entry in enumerate(self.lib.all_entries()):
if not Ignore.compiled_patterns:
# If the compiled_patterns has malfunctioned, don't consider that a false positive
yield i
elif Ignore.compiled_patterns.match(library_dir / entry.path):
self.ignored_entries.append(entry)
yield i
def remove_ignored_entries(self) -> None:
self.lib.remove_entries(list(map(lambda ignored: ignored.id, self.ignored_entries)))
self.ignored_entries = []

View File

@@ -0,0 +1,89 @@
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
import structlog
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.utils.refresh_dir import GLOBAL_IGNORE_SET
logger = structlog.get_logger()
@dataclass
class MissingRegistry:
"""State tracker for unlinked and moved files."""
library: Library
files_fixed_count: int = 0
missing_file_entries: list[Entry] = field(default_factory=list)
@property
def missing_file_entries_count(self) -> int:
return len(self.missing_file_entries)
def refresh_missing_files(self) -> Iterator[int]:
"""Track the number of entries that point to an invalid filepath."""
logger.info("[refresh_missing_files] Refreshing missing files...")
self.missing_file_entries = []
for i, entry in enumerate(self.library.get_entries()):
full_path = self.library.library_dir / entry.path
if not full_path.exists() or not full_path.is_file():
self.missing_file_entries.append(entry)
yield i
def match_missing_file_entry(self, match_entry: Entry) -> list[Path]:
"""Try and match unlinked file entries with matching results in the library directory.
Works if files were just moved to different subfolders and don't have duplicate names.
"""
matches = []
for path in self.library.library_dir.glob(f"**/{match_entry.path.name}"):
# Ensure matched file isn't in a globally ignored folder
skip: bool = False
for part in path.parts:
if part in GLOBAL_IGNORE_SET:
skip = True
break
if skip:
continue
if path.name == match_entry.path.name:
new_path = Path(path).relative_to(self.library.library_dir)
matches.append(new_path)
logger.info("[MissingRegistry] Matches", matches=matches)
return matches
def fix_unlinked_entries(self) -> Iterator[int]:
"""Attempt to fix unlinked file entries by finding a match in the library directory."""
self.files_fixed_count = 0
matched_entries: list[Entry] = []
for i, entry in enumerate(self.missing_file_entries):
item_matches = self.match_missing_file_entry(entry)
if len(item_matches) == 1:
logger.info(
"[fix_unlinked_entries]",
entry=entry.path.as_posix(),
item_matches=item_matches[0].as_posix(),
)
if not self.library.update_entry_path(entry.id, item_matches[0]):
try:
match = self.library.get_entry_full_by_path(item_matches[0])
entry_full = self.library.get_entry_full(entry.id)
self.library.merge_entries(entry_full, match)
except AttributeError:
continue
self.files_fixed_count += 1
matched_entries.append(entry)
yield i
for entry in matched_entries:
self.missing_file_entries.remove(entry)
def execute_deletion(self) -> None:
self.library.remove_entries(
list(map(lambda missing: missing.id, self.missing_file_entries))
)
self.missing_file_entries = []

View File

@@ -1,9 +1,3 @@
# Copyright (C) 2025
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import shutil
from collections.abc import Iterator
from dataclasses import dataclass, field
from datetime import datetime as dt
@@ -11,15 +5,27 @@ from pathlib import Path
from time import time
import structlog
from wcmatch import pathlib
from tagstudio.core.constants import TS_FOLDER_NAME
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.library.ignore import PATH_GLOB_FLAGS, Ignore, ignore_to_glob
from tagstudio.qt.helpers.silent_popen import silent_run # pyright: ignore
logger = structlog.get_logger(__name__)
GLOBAL_IGNORE_SET: set[str] = set(
[
TS_FOLDER_NAME,
"$RECYCLE.BIN",
".Trashes",
".Trash",
"tagstudio_thumbs",
".fseventsd",
".Spotlight-V100",
"System Volume Information",
".DS_Store",
]
)
@dataclass
class RefreshDirTracker:
@@ -36,7 +42,7 @@ class RefreshDirTracker:
entries = [
Entry(
path=entry_path,
folder=self.library.folder, # pyright: ignore[reportArgumentType]
folder=self.library.folder,
fields=[],
date_added=dt.now(),
)
@@ -48,81 +54,18 @@ class RefreshDirTracker:
yield
def refresh_dir(self, library_dir: Path, force_internal_tools: bool = False) -> Iterator[int]:
"""Scan a directory for files, and add those relative filenames to internal variables.
Args:
library_dir (Path): The library directory.
force_internal_tools (bool): Option to force the use of internal tools for scanning
(i.e. wcmatch) instead of using tools found on the system (i.e. ripgrep).
"""
def refresh_dir(self, lib_path: Path) -> Iterator[int]:
"""Scan a directory for files, and add those relative filenames to internal variables."""
if self.library.library_dir is None:
raise ValueError("No library directory set.")
ignore_patterns = Ignore.get_patterns(library_dir)
if force_internal_tools:
return self.__wc_add(library_dir, ignore_to_glob(ignore_patterns))
dir_list: list[str] | None = self.__get_dir_list(library_dir, ignore_patterns)
# Use ripgrep if it was found and working, else fallback to wcmatch.
if dir_list is not None:
return self.__rg_add(library_dir, dir_list)
else:
return self.__wc_add(library_dir, ignore_to_glob(ignore_patterns))
def __get_dir_list(self, library_dir: Path, ignore_patterns: list[str]) -> list[str] | None:
"""Use ripgrep to return a list of matched directories and files.
Return `None` if ripgrep not found on system.
"""
rg_path = shutil.which("rg")
# Use ripgrep if found on system
if rg_path is not None:
logger.info("[Refresh: Using ripgrep for scanning]")
compiled_ignore_path = library_dir / ".TagStudio" / ".compiled_ignore"
# Write compiled ignore patterns (built-in + user) to a temp file to pass to ripgrep
with open(compiled_ignore_path, "w") as pattern_file:
pattern_file.write("\n".join(ignore_patterns))
result = silent_run(
" ".join(
[
"rg",
"--files",
"--follow",
"--hidden",
"--ignore-file",
f'"{str(compiled_ignore_path)}"',
]
),
cwd=library_dir,
capture_output=True,
text=True,
shell=True,
)
compiled_ignore_path.unlink()
if result.stderr:
logger.error(result.stderr)
return result.stdout.splitlines() # pyright: ignore [reportReturnType]
logger.warning("[Refresh: ripgrep not found on system]")
return None
def __rg_add(self, library_dir: Path, dir_list: list[str]) -> Iterator[int]:
start_time_total = time()
start_time_loop = time()
dir_file_count = 0
self.files_not_in_library = []
dir_file_count = 0
for r in dir_list:
f = pathlib.Path(r)
for f in lib_path.glob("**/*"):
end_time_loop = time()
# Yield output every 1/30 of a second
if (end_time_loop - start_time_loop) > 0.034:
@@ -138,62 +81,31 @@ class RefreshDirTracker:
if f.is_dir():
continue
dir_file_count += 1
self.library.included_files.add(f)
if not self.library.has_path_entry(f):
self.files_not_in_library.append(f)
end_time_total = time()
yield dir_file_count
logger.info(
"[Refresh]: Directory scan time",
path=library_dir,
duration=(end_time_total - start_time_total),
files_scanned=dir_file_count,
tool_used="ripgrep (system)",
)
def __wc_add(self, library_dir: Path, ignore_patterns: list[str]) -> Iterator[int]:
start_time_total = time()
start_time_loop = time()
dir_file_count = 0
self.files_not_in_library = []
logger.info("[Refresh]: Falling back to wcmatch for scanning")
for f in pathlib.Path(str(library_dir)).glob(
"***/*", flags=PATH_GLOB_FLAGS, exclude=ignore_patterns
):
end_time_loop = time()
# Yield output every 1/30 of a second
if (end_time_loop - start_time_loop) > 0.034:
yield dir_file_count
start_time_loop = time()
# Skip if the file/path is already mapped in the Library
if f in self.library.included_files:
dir_file_count += 1
continue
# Ignore if the file is a directory
if f.is_dir():
# Ensure new file isn't in a globally ignored folder
skip: bool = False
for part in f.parts:
# NOTE: Files starting with "._" are sometimes generated by macOS Finder.
# More info: https://lists.apple.com/archives/applescript-users/2006/Jun/msg00180.html
if part.startswith("._") or part in GLOBAL_IGNORE_SET:
skip = True
break
if skip:
continue
dir_file_count += 1
self.library.included_files.add(f)
relative_path = f.relative_to(library_dir)
relative_path = f.relative_to(lib_path)
# TODO - load these in batch somehow
if not self.library.has_path_entry(relative_path):
self.files_not_in_library.append(relative_path)
end_time_total = time()
yield dir_file_count
logger.info(
"[Refresh]: Directory scan time",
path=library_dir,
"Directory scan time",
path=lib_path,
duration=(end_time_total - start_time_total),
files_not_in_lib=self.files_not_in_library,
files_scanned=dir_file_count,
tool_used="wcmatch (internal)",
)

View File

@@ -1,14 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from typing import TypeVar
T = TypeVar("T")
def unwrap(optional: T | None, default: T | None = None) -> T:
if optional is not None:
return optional
if default is not None:
return default
raise ValueError("Expected a value, but got None and no default was provided.")

View File

@@ -1,93 +0,0 @@
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
import structlog
from wcmatch import pathlib
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.library.ignore import PATH_GLOB_FLAGS, Ignore
from tagstudio.core.utils.types import unwrap
logger = structlog.get_logger()
@dataclass
class UnlinkedRegistry:
"""State tracker for unlinked entries."""
lib: Library
files_fixed_count: int = 0
unlinked_entries: list[Entry] = field(default_factory=list)
@property
def unlinked_entries_count(self) -> int:
return len(self.unlinked_entries)
def reset(self):
self.unlinked_entries.clear()
def refresh_unlinked_files(self) -> Iterator[int]:
"""Track the number of entries that point to an invalid filepath."""
logger.info("[UnlinkedRegistry] Refreshing unlinked files...")
self.unlinked_entries = []
for i, entry in enumerate(self.lib.all_entries()):
full_path = unwrap(self.lib.library_dir) / entry.path
if not full_path.exists() or not full_path.is_file():
self.unlinked_entries.append(entry)
yield i
def match_unlinked_file_entry(self, match_entry: Entry) -> list[Path]:
"""Try and match unlinked file entries with matching results in the library directory.
Works if files were just moved to different subfolders and don't have duplicate names.
"""
library_dir = unwrap(self.lib.library_dir)
matches: list[Path] = []
ignore_patterns = Ignore.get_patterns(library_dir)
for path in pathlib.Path(str(library_dir)).glob(
f"***/{match_entry.path.name}",
flags=PATH_GLOB_FLAGS,
exclude=ignore_patterns,
):
if path.is_dir():
continue
if path.name == match_entry.path.name:
new_path = Path(path).relative_to(library_dir)
matches.append(new_path)
logger.info("[UnlinkedRegistry] Matches", matches=matches)
return matches
def fix_unlinked_entries(self) -> Iterator[int]:
"""Attempt to fix unlinked file entries by finding a match in the library directory."""
self.files_fixed_count = 0
matched_entries: list[Entry] = []
for i, entry in enumerate(self.unlinked_entries):
item_matches = self.match_unlinked_file_entry(entry)
if len(item_matches) == 1:
logger.info(
"[UnlinkedRegistry]",
entry=entry.path.as_posix(),
item_matches=item_matches[0].as_posix(),
)
if not self.lib.update_entry_path(entry.id, item_matches[0]):
try:
match = unwrap(self.lib.get_entry_full_by_path(item_matches[0]))
entry_full = unwrap(self.lib.get_entry_full(entry.id))
self.lib.merge_entries(entry_full, match)
except AttributeError:
continue
self.files_fixed_count += 1
matched_entries.append(entry)
yield i
for entry in matched_entries:
self.unlinked_entries.remove(entry)
def remove_unlinked_entries(self) -> None:
self.lib.remove_entries(list(map(lambda unlinked: unlinked.id, self.unlinked_entries)))
self.unlinked_entries = []

View File

@@ -7,14 +7,16 @@
"""TagStudio launcher."""
import argparse
import logging
import traceback
import structlog
from tagstudio.core.constants import VERSION, VERSION_BRANCH
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
structlog.configure(
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
)
def main():
@@ -30,19 +32,12 @@ def main():
type=str,
help="Path to a TagStudio Library folder to open on start.",
)
parser.add_argument(
"-s",
"--settings-file",
dest="settings_file",
type=str,
help="Path to a TagStudio .toml global settings file to use.",
)
parser.add_argument(
"-c",
"--cache-file",
dest="cache_file",
"--config-file",
dest="config_file",
type=str,
help="Path to a TagStudio .ini or .plist cache file to use.",
help="Path to a TagStudio .ini or .plist config file to use.",
)
# parser.add_argument('--browse', dest='browse', action='store_true',
@@ -56,11 +51,10 @@ def main():
help="Reveals additional internal data useful for debugging.",
)
parser.add_argument(
"-v",
"--version",
action="version",
help="Displays TagStudio version information.",
version=f"TagStudio v{VERSION} {VERSION_BRANCH}",
"--ui",
dest="ui",
type=str,
help="User interface option for TagStudio. Options: qt, cli (Default: qt)",
)
args = parser.parse_args()
@@ -72,7 +66,7 @@ def main():
driver.start()
except Exception:
traceback.print_exc()
logger.info(f"\nTagStudio Frontend ({ui_name}) Crashed! Press Enter to Continue...")
logging.info(f"\nTagStudio Frontend ({ui_name}) Crashed! Press Enter to Continue...")
input()

View File

@@ -2,170 +2,190 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import contextlib
import math
from collections.abc import Iterable
import typing
from datetime import datetime as dt
from pathlib import Path
from threading import RLock
import structlog
from PIL import Image
from tagstudio.core.constants import THUMB_CACHE_NAME, TS_FOLDER_NAME
from tagstudio.core.singleton import Singleton
# Only import for type checking/autocompletion, will not be imported at runtime.
if typing.TYPE_CHECKING:
from tagstudio.core.library import Library
logger = structlog.get_logger(__name__)
class CacheEntry:
def __init__(self, path: Path, size: int):
self.path: Path = path
self.size: int = size
class CacheManager(metaclass=Singleton):
FOLDER_SIZE = 10000000 # Each cache folder assumed to be 10 MiB
size_limit = 500000000 # 500 MiB default
folder_dict: dict[Path, int] = {}
class CacheManager:
DEFAULT_MAX_SIZE = 500_000_000
DEFAULT_MAX_FOLDER_SIZE = 10_000_000
def __init__(self):
self.lib: Library | None = None
self.last_lib_path: Path | None = None
def __init__(
self,
library_dir: Path,
max_size: int = DEFAULT_MAX_SIZE,
max_folder_size: int = DEFAULT_MAX_FOLDER_SIZE,
):
self._lock = RLock()
self.cache_folder = library_dir / TS_FOLDER_NAME / THUMB_CACHE_NAME
self.max_folder_size = max_folder_size
self.max_size = max(max_size, max_folder_size)
@staticmethod
def clear_cache(library_dir: Path) -> bool:
"""Clear all files and folders within the cached folder.
self.folders: list[CacheEntry] = []
self.current_size = 0
if self.cache_folder.exists():
for folder in self.cache_folder.iterdir():
if not folder.is_dir():
continue
folder_size = 0
for file in folder.iterdir():
folder_size += file.stat().st_size
self.folders.append(CacheEntry(folder, folder_size))
self.current_size += folder_size
Returns:
bool: True if successfully deleted, else False.
"""
cleared = True
def _set_mru(self, index: int):
"""Move entry at index so it's considered the most recently used."""
with self._lock as _lock:
if index == (len(self.folders) - 1):
return
entry = self.folders.pop(index)
self.folders.append(entry)
if library_dir:
tree: Path = library_dir / TS_FOLDER_NAME / THUMB_CACHE_NAME
def _mru(self) -> Iterable[int]:
"""Get each folders index sorted most recently used first."""
with self._lock as _lock:
return reversed(range(len(self.folders)))
def _lru(self) -> Iterable[int]:
"""Get each folders index sorted least recently used first."""
with self._lock as _lock:
return range(len(self.folders))
def clear_cache(self):
"""Clear all files and folders within the cached folder."""
with self._lock as _lock:
folders = []
for folder in self.folders:
if not self._remove_folder(folder):
folders.append(folders)
logger.warn("[CacheManager] Failed to remove folder", folder=folder)
self.folders = folders
logger.info("[CacheManager] Cleared cache!")
def _remove_folder(self, entry: CacheEntry) -> bool:
with self._lock as _lock:
self.current_size -= entry.size
if not entry.path.is_dir():
return True
is_empty = True
for file in entry.path.iterdir():
assert file.is_file() and file.suffix == ".webp"
for folder in tree.glob("*"):
for file in folder.glob("*"):
# NOTE: On macOS with non-native file systems, this will commonly raise
# FileNotFound errors due to trying to delete "._" files that have
# already been deleted: https://bugs.python.org/issue29699
with contextlib.suppress(FileNotFoundError):
file.unlink()
try:
file.unlink(missing_ok=True)
except BaseException as e:
is_empty = False
logger.warn("[CacheManager] Failed to remove file", file=file, error=e)
folder.rmdir()
with contextlib.suppress(KeyError):
CacheManager.folder_dict.pop(folder)
except Exception as e:
logger.error(
"[CacheManager] Couldn't unlink empty cache folder!",
error=e,
folder=folder,
tree=tree,
)
if is_empty:
entry.path.rmdir()
return True
for _ in tree.glob("*"):
cleared = False
if cleared:
logger.info("[CacheManager] Cleared cache!")
else:
size = 0
for file in entry.path.iterdir():
size += file.stat().st_size
entry.size = size
self.current_size += size
return False
logger.error("[CacheManager] Couldn't delete cache!", tree=tree)
def get_file_path(self, file_name: Path) -> Path | None:
with self._lock as _lock:
for i in self._mru():
entry = self.folders[i]
file_path = entry.path / file_name
if file_path.exists():
self._set_mru(i)
return file_path
return None
return cleared
def save_image(self, image: Image.Image, file_name: Path, mode: str = "RGBA"):
def set_library(self, library):
"""Set the TagStudio library for the cache manager."""
self.lib = library
self.last_lib_path = self.lib.library_dir
if library.library_dir:
self.check_folder_status()
def cache_dir(self) -> Path | None:
"""Return the current cache directory, not including folder slugs."""
if not self.lib.library_dir:
return None
return Path(self.lib.library_dir / TS_FOLDER_NAME / THUMB_CACHE_NAME)
def save_image(self, image: Image.Image, path: Path, mode: str = "RGBA"):
"""Save an image to the cache."""
with self._lock as _lock:
entry = self._get_current_folder()
file_path = entry.path / file_name
image.save(file_path, mode=mode)
folder = self.get_current_folder()
if folder:
image_path: Path = folder / path
image.save(image_path, mode=mode)
with contextlib.suppress(KeyError):
CacheManager.folder_dict[folder] += image_path.stat().st_size
size = file_path.stat().st_size
entry.size += size
self.current_size += size
self._cull_folders()
def check_folder_status(self):
"""Check the status of the cache folders.
def _create_folder(self) -> CacheEntry:
with self._lock as _lock:
folder = self.cache_folder / Path(str(math.floor(dt.timestamp(dt.now()))))
This includes registering existing ones and creating new ones if needed.
"""
if (
(self.last_lib_path != self.lib.library_dir)
or not self.cache_dir()
or not self.cache_dir().exists()
):
self.register_existing_folders()
def create_folder() -> Path | None:
"""Create a new cache folder."""
if not self.lib.library_dir:
return None
folder_path = Path(self.cache_dir() / str(math.floor(dt.timestamp(dt.now()))))
logger.info("[CacheManager] Creating new folder", folder=folder_path)
try:
folder.mkdir(parents=True)
except FileExistsError:
for entry in self.folders:
if entry.path == folder:
return entry
entry = CacheEntry(folder, 0)
self.folders.append(entry)
return entry
folder_path.mkdir(exist_ok=True)
except NotADirectoryError:
logger.error("[CacheManager] Not a directory", path=folder_path)
return folder_path
def _get_current_folder(self) -> CacheEntry:
with self._lock as _lock:
if len(self.folders) == 0:
return self._create_folder()
# Get size of most recent folder, if any exist.
if CacheManager.folder_dict:
last_folder = sorted(CacheManager.folder_dict.keys())[-1]
for i in self._mru():
entry = self.folders[i]
if entry.size < self.max_folder_size:
self._set_mru(i)
return entry
if CacheManager.folder_dict[last_folder] > CacheManager.FOLDER_SIZE:
new_folder = create_folder()
CacheManager.folder_dict[new_folder] = 0
else:
new_folder = create_folder()
CacheManager.folder_dict[new_folder] = 0
return self._create_folder()
def get_current_folder(self) -> Path:
"""Get the current cache folder path that should be used."""
self.check_folder_status()
self.cull_folders()
def _cull_folders(self):
return sorted(CacheManager.folder_dict.keys())[-1]
def register_existing_folders(self):
"""Scan and register any pre-existing cache folders with the most recent size."""
self.last_lib_path = self.lib.library_dir
CacheManager.folder_dict.clear()
# NOTE: The /dev/null check is a workaround for current test assumptions.
if self.last_lib_path and self.last_lib_path != Path("/dev/null"):
# Ensure thumbnail cache path exists.
self.cache_dir().mkdir(exist_ok=True)
# Registers any existing folders and counts the capacity of the most recent one.
for f in sorted(self.cache_dir().glob("*")):
if f.is_dir():
# A folder is found. Add it to the class dict.BlockingIOError
CacheManager.folder_dict[f] = 0
CacheManager.folder_dict = dict(
sorted(CacheManager.folder_dict.items(), key=lambda kv: kv[0])
)
if CacheManager.folder_dict:
last_folder = sorted(CacheManager.folder_dict.keys())[-1]
for f in last_folder.glob("*"):
if not f.is_dir():
with contextlib.suppress(KeyError):
CacheManager.folder_dict[last_folder] += f.stat().st_size
def cull_folders(self):
"""Remove folders and their cached context based on size or age limits."""
with self._lock as _lock:
if self.current_size < self.max_size:
return
# Ensure that the user's configured size limit isn't less than the internal folder size.
size_limit = max(CacheManager.size_limit, CacheManager.FOLDER_SIZE)
removed: list[int] = []
for i in self._lru():
entry = self.folders[i]
logger.info("[CacheManager] Removing folder due to size limit", folder=entry.path)
if self._remove_folder(entry):
removed.append(i)
if self.current_size < self.max_size:
break
if len(CacheManager.folder_dict) > (size_limit / CacheManager.FOLDER_SIZE):
f = sorted(CacheManager.folder_dict.keys())[0]
folder = self.cache_dir() / f
logger.info("[CacheManager] Removing folder due to size limit", folder=folder)
for index in sorted(removed, reverse=True):
self.folders.pop(index)
for file in folder.glob("*"):
try:
file.unlink()
except Exception as e:
logger.error(
"[CacheManager] Couldn't cull file inside of folder!",
error=e,
file=file,
folder=folder,
)
try:
folder.rmdir()
with contextlib.suppress(KeyError):
CacheManager.folder_dict.pop(f)
self.cull_folders()
except Exception as e:
logger.error("[CacheManager] Couldn't cull folder!", error=e, folder=folder)
pass

View File

@@ -1,99 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from typing import TYPE_CHECKING, override
import structlog
from PySide6.QtCore import Signal
from tagstudio.core.enums import TagClickActionOption
from tagstudio.core.library.alchemy.enums import BrowsingState
from tagstudio.core.library.alchemy.models import Tag
from tagstudio.core.utils.types import unwrap
from tagstudio.qt.modals.build_tag import BuildTagPanel
from tagstudio.qt.view.components.tag_box_view import TagBoxWidgetView
from tagstudio.qt.widgets.panel import PanelModal
if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
class TagBoxWidget(TagBoxWidgetView):
on_update = Signal()
__entries: list[int] = []
def __init__(self, title: str, driver: "QtDriver"):
super().__init__(title, driver)
self.__driver = driver
def set_entries(self, entries: list[int]) -> None:
self.__entries = entries
@override
def _on_click(self, tag: Tag) -> None: # type: ignore[misc]
match self.__driver.settings.tag_click_action:
case TagClickActionOption.OPEN_EDIT:
self._on_edit(tag)
case TagClickActionOption.SET_SEARCH:
self.__driver.update_browsing_state(
BrowsingState.from_tag_id(tag.id, self.__driver.browsing_history.current)
)
case TagClickActionOption.ADD_TO_SEARCH:
# NOTE: modifying the ast and then setting that would be nicer
# than this string manipulation, but also much more complex,
# due to needing to implement a visitor that turns an AST to a string
# So if that exists when you read this, change the following accordingly.
current = self.__driver.browsing_history.current
suffix = unwrap(
BrowsingState.from_tag_id(tag.id, self.__driver.browsing_history.current).query
)
self.__driver.update_browsing_state(
current.with_search_query(
f"{current.query} {suffix}" if current.query else suffix
)
)
@override
def _on_remove(self, tag: Tag) -> None: # type: ignore[misc]
logger.info(
"[TagBoxWidget] remove_tag",
selected=self.__entries,
)
for entry_id in self.__entries:
self.__driver.lib.remove_tags_from_entries(entry_id, tag.id)
self.on_update.emit()
@override
def _on_edit(self, tag: Tag) -> None: # type: ignore[misc]
build_tag_panel = BuildTagPanel(self.__driver.lib, tag=tag)
edit_modal = PanelModal(
build_tag_panel,
self.__driver.lib.tag_display_name(tag),
"Edit Tag",
done_callback=self.on_update.emit,
has_save=True,
)
# TODO - this was update_tag()
edit_modal.saved.connect(
lambda: self.__driver.lib.update_tag(
build_tag_panel.build_tag(),
parent_ids=set(build_tag_panel.parent_ids),
alias_names=set(build_tag_panel.alias_names),
alias_ids=set(build_tag_panel.alias_ids),
)
)
edit_modal.show()
@override
def _on_search(self, tag: Tag) -> None: # type: ignore[misc]
self.__driver.main_window.search_field.setText(f"tag_id:{tag.id}")
self.__driver.update_browsing_state(
BrowsingState.from_tag_id(tag.id, self.__driver.browsing_history.current)
)

View File

@@ -1,94 +0,0 @@
# Copyright (C) 2025 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from typing import TYPE_CHECKING, override
import structlog
from PySide6 import QtGui
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.utils.ignored_registry import IgnoredRegistry
from tagstudio.qt.modals.remove_ignored_modal import RemoveIgnoredModal
from tagstudio.qt.translations import Translations
from tagstudio.qt.view.widgets.fix_ignored_modal_view import FixIgnoredEntriesModalView
from tagstudio.qt.widgets.progress import ProgressWidget
# Only import for type checking/autocompletion, will not be imported at runtime.
if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
class FixIgnoredEntriesModal(FixIgnoredEntriesModalView):
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__(library, driver)
self.tracker = IgnoredRegistry(self.lib)
self.remove_modal = RemoveIgnoredModal(self.driver, self.tracker)
self.remove_modal.done.connect(
lambda: (
self.update_ignored_count(),
self.driver.update_browsing_state(),
self.driver.library_info_window.update_cleanup(),
self.refresh_ignored(),
)
)
self.refresh_ignored_button.clicked.connect(self.refresh_ignored)
self.remove_button.clicked.connect(self.remove_modal.show)
self.done_button.clicked.connect(self.hide)
self.update_ignored_count()
def refresh_ignored(self):
pw = ProgressWidget(
cancel_button_text=None,
minimum=0,
maximum=self.lib.entries_count,
)
pw.setWindowTitle(Translations["library.scan_library.title"])
pw.update_label(Translations["entries.ignored.scanning"])
def update_driver_widgets():
if (
hasattr(self.driver, "library_info_window")
and self.driver.library_info_window.isVisible()
):
self.driver.library_info_window.update_cleanup()
pw.from_iterable_function(
self.tracker.refresh_ignored_entries,
None,
self.set_ignored_count,
self.update_ignored_count,
self.remove_modal.refresh_list,
update_driver_widgets,
)
def set_ignored_count(self):
"""Sets the ignored_entries_count in the Library to the tracker's value."""
self.lib.ignored_entries_count = self.tracker.ignored_count
def update_ignored_count(self):
"""Updates the UI to reflect the Library's current ignored_entries_count."""
# Indicates that the library is new compared to the last update.
# NOTE: Make sure set_ignored_count() is called before this!
if self.tracker.ignored_count > 0 and self.lib.ignored_entries_count < 0:
self.tracker.reset()
count: int = self.lib.ignored_entries_count
self.remove_button.setDisabled(count < 1)
count_text: str = Translations.format(
"entries.ignored.ignored_count", count=count if count >= 0 else ""
)
self.ignored_count_label.setText(f"<h3>{count_text}</h3>")
@override
def showEvent(self, event: QtGui.QShowEvent) -> None: # type: ignore
self.update_ignored_count()
return super().showEvent(event)

View File

@@ -1,50 +0,0 @@
# Copyright (C) 2025 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from pathlib import Path
import structlog
from PySide6 import QtGui
from PySide6.QtCore import Signal
from tagstudio.core.constants import IGNORE_NAME, TS_FOLDER_NAME
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Tag
from tagstudio.core.library.ignore import Ignore
from tagstudio.qt.helpers import file_opener
from tagstudio.qt.view.widgets.ignore_modal_view import IgnoreModalView
logger = structlog.get_logger(__name__)
class IgnoreModal(IgnoreModalView):
on_edit = Signal(Tag)
def __init__(self, library: Library) -> None:
super().__init__(library)
self.open_button.clicked.connect(self.__open_file)
def __load_file(self):
if not self.lib.library_dir:
return
ts_ignore: list[str] = Ignore.read_ignore_file(self.lib.library_dir)
self.text_edit.setPlainText("".join(ts_ignore))
def __open_file(self):
if not self.lib.library_dir:
return
ts_ignore_path = Path(self.lib.library_dir / TS_FOLDER_NAME / IGNORE_NAME)
file_opener.open_file(ts_ignore_path, file_manager=True)
def save(self):
if not self.lib.library_dir:
return
lines = self.text_edit.toPlainText().split("\n")
lines = [f"{line}\n" for line in lines]
Ignore.write_ignore_file(self.lib.library_dir, lines)
def showEvent(self, event: QtGui.QShowEvent) -> None: # noqa N802
self.__load_file()
return super().showEvent(event)

View File

@@ -1,166 +0,0 @@
# Copyright (C) 2025 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import os
from pathlib import Path
from typing import TYPE_CHECKING, override
from warnings import catch_warnings
import structlog
from humanfriendly import format_size # pyright: ignore[reportUnknownVariableType]
from PySide6 import QtGui
from tagstudio.core.constants import BACKUP_FOLDER_NAME, TS_FOLDER_NAME
from tagstudio.core.library.alchemy.constants import (
DB_VERSION,
DB_VERSION_CURRENT_KEY,
JSON_FILENAME,
)
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.utils.types import unwrap
from tagstudio.qt.helpers import file_opener
from tagstudio.qt.translations import Translations
from tagstudio.qt.view.widgets.library_info_window_view import LibraryInfoWindowView
# Only import for type checking/autocompletion, will not be imported at runtime.
if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
class LibraryInfoWindow(LibraryInfoWindowView):
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__(library, driver)
# Statistics Buttons
self.manage_tags_button.clicked.connect(
self.driver.main_window.menu_bar.tag_manager_action.trigger
)
self.manage_colors_button.clicked.connect(
self.driver.main_window.menu_bar.color_manager_action.trigger
)
# Cleanup Buttons
self.fix_unlinked_entries.clicked.connect(
self.driver.main_window.menu_bar.fix_unlinked_entries_action.trigger
)
self.fix_ignored_entries.clicked.connect(
self.driver.main_window.menu_bar.fix_ignored_entries_action.trigger
)
self.fix_dupe_files.clicked.connect(
self.driver.main_window.menu_bar.fix_dupe_files_action.trigger
)
# General Buttons
self.close_button.clicked.connect(lambda: self.close())
def update_title(self):
assert self.lib.library_dir
title: str = Translations.format(
"library_info.title", library_dir=self.lib.library_dir.stem
)
self.title_label.setText(f"<h2>{title}</h2>")
def update_stats(self):
self.entry_count_label.setText(f"<b>{self.lib.entries_count}</b>")
self.tag_count_label.setText(f"<b>{len(self.lib.tags)}</b>")
self.field_count_label.setText(f"<b>{len(self.lib.field_types)}</b>")
self.namespaces_count_label.setText(f"<b>{len(self.lib.namespaces)}</b>")
colors_total = 0
for c in self.lib.tag_color_groups.values():
colors_total += len(c)
self.color_count_label.setText(f"<b>{colors_total}</b>")
self.macros_count_label.setText("<b>1</b>") # TODO: Implement macros system
def update_cleanup(self):
# Unlinked Entries
unlinked_count: str = (
str(self.lib.unlinked_entries_count) if self.lib.unlinked_entries_count >= 0 else ""
)
self.unlinked_count_label.setText(f"<b>{unlinked_count}</b>")
# Ignored Entries
ignored_count: str = (
str(self.lib.ignored_entries_count) if self.lib.ignored_entries_count >= 0 else ""
)
self.ignored_count_label.setText(f"<b>{ignored_count}</b>")
# Duplicate Files
dupe_files_count: str = (
str(self.lib.dupe_files_count) if self.lib.dupe_files_count >= 0 else ""
)
self.dupe_files_count_label.setText(f"<b>{dupe_files_count}</b>")
# Legacy JSON Library Present
json_library_text: str = (
Translations["generic.yes"]
if self.__is_json_library_present
else Translations["generic.no"]
)
self.legacy_json_status_label.setText(f"<b>{json_library_text}</b>")
# Backups
self.backups_count_label.setText(
f"<b>{self.__backups_count}</b> ({format_size(self.__backups_size)})"
)
# Buttons
with catch_warnings(record=True):
self.view_legacy_json_file.clicked.disconnect()
self.open_backups_folder.clicked.disconnect()
if self.__is_json_library_present:
self.view_legacy_json_file.setEnabled(True)
self.view_legacy_json_file.clicked.connect(
lambda: file_opener.open_file(
unwrap(self.lib.library_dir) / TS_FOLDER_NAME / JSON_FILENAME, file_manager=True
)
)
else:
self.view_legacy_json_file.setEnabled(False)
self.open_backups_folder.clicked.connect(
lambda: file_opener.open_file(
unwrap(self.lib.library_dir) / TS_FOLDER_NAME / BACKUP_FOLDER_NAME
)
)
def update_version(self):
version_text: str = f"<b>{self.lib.get_version(DB_VERSION_CURRENT_KEY)}</b> / {DB_VERSION}"
self.version_label.setText(
Translations.format("library_info.version", version=version_text)
)
def refresh(self):
self.update_title()
self.update_stats()
self.update_cleanup()
self.update_version()
@property
def __is_json_library_present(self):
json_path = unwrap(self.lib.library_dir) / TS_FOLDER_NAME / JSON_FILENAME
return json_path.exists()
@property
def __backups_count(self):
backups_path = unwrap(self.lib.library_dir) / TS_FOLDER_NAME / BACKUP_FOLDER_NAME
return len(os.listdir(backups_path))
@property
def __backups_size(self):
backups_path = unwrap(self.lib.library_dir) / TS_FOLDER_NAME / BACKUP_FOLDER_NAME
size: int = 0
for f in backups_path.glob("*"):
if not f.is_dir() and f.exists():
size += Path(f).stat().st_size
return size
@override
def showEvent(self, event: QtGui.QShowEvent): # type: ignore
self.refresh()
return super().showEvent(event)

View File

@@ -1,157 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import io
from pathlib import Path
from typing import TYPE_CHECKING
import cv2
import rawpy
import structlog
from PIL import Image, UnidentifiedImageError
from PIL.Image import DecompressionBombError
from PySide6.QtCore import QSize
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.media_types import MediaCategories
from tagstudio.qt.helpers.file_opener import open_file
from tagstudio.qt.helpers.file_tester import is_readable_video
from tagstudio.qt.view.widgets.preview.preview_thumb_view import PreviewThumbView
from tagstudio.qt.widgets.preview.file_attributes import FileAttributeData
if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
Image.MAX_IMAGE_PIXELS = None
class PreviewThumb(PreviewThumbView):
__current_file: Path
def __init__(self, library: Library, driver: "QtDriver"):
super().__init__(library, driver)
self.__driver: QtDriver = driver
def __get_image_stats(self, filepath: Path) -> FileAttributeData:
"""Get width and height of an image as dict."""
stats = FileAttributeData()
ext = filepath.suffix.lower()
if filepath.is_dir():
pass
elif MediaCategories.IMAGE_RAW_TYPES.contains(ext, mime_fallback=True):
try:
with rawpy.imread(str(filepath)) as raw:
rgb = raw.postprocess()
image = Image.new("L", (rgb.shape[1], rgb.shape[0]), color="black")
stats.width = image.width
stats.height = image.height
except (
rawpy._rawpy._rawpy.LibRawIOError, # pyright: ignore[reportAttributeAccessIssue]
rawpy._rawpy.LibRawFileUnsupportedError, # pyright: ignore[reportAttributeAccessIssue]
FileNotFoundError,
):
pass
elif MediaCategories.IMAGE_RASTER_TYPES.contains(ext, mime_fallback=True):
try:
image = Image.open(str(filepath))
stats.width = image.width
stats.height = image.height
except (
DecompressionBombError,
FileNotFoundError,
NotImplementedError,
UnidentifiedImageError,
) as e:
logger.error("[PreviewThumb] Could not get image stats", filepath=filepath, error=e)
elif MediaCategories.IMAGE_VECTOR_TYPES.contains(ext, mime_fallback=True):
pass # TODO
return stats
def __get_gif_data(self, filepath: Path) -> tuple[bytes, tuple[int, int]] | None:
"""Loads an animated image and returns gif data and size, if successful."""
ext = filepath.suffix.lower()
try:
image: Image.Image = Image.open(filepath)
if ext == ".apng":
image_bytes_io = io.BytesIO()
image.save(
image_bytes_io,
"GIF",
lossless=True,
save_all=True,
loop=0,
disposal=2,
)
image.close()
image_bytes_io.seek(0)
return (image_bytes_io.read(), (image.width, image.height))
else:
image.close()
with open(filepath, "rb") as f:
return (f.read(), (image.width, image.height))
except (UnidentifiedImageError, FileNotFoundError) as e:
logger.error("[PreviewThumb] Could not load animated image", filepath=filepath, error=e)
return None
def __get_video_res(self, filepath: str) -> tuple[bool, QSize]:
video = cv2.VideoCapture(filepath, cv2.CAP_FFMPEG)
success, frame = video.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(frame)
return (success, QSize(image.width, image.height))
def display_file(self, filepath: Path) -> FileAttributeData:
"""Render a single file preview."""
self.__current_file = filepath
ext = filepath.suffix.lower()
# Video
if MediaCategories.VIDEO_TYPES.contains(ext, mime_fallback=True) and is_readable_video(
filepath
):
size: QSize | None = None
try:
success, size = self.__get_video_res(str(filepath))
if not success:
size = None
except cv2.error as e:
logger.error("[PreviewThumb] Could not play video", filepath=filepath, error=e)
return self._display_video(filepath, size)
# Audio
elif MediaCategories.AUDIO_TYPES.contains(ext, mime_fallback=True):
return self._display_audio(filepath)
# Animated Images
elif MediaCategories.IMAGE_ANIMATED_TYPES.contains(ext, mime_fallback=True):
if (ret := self.__get_gif_data(filepath)) and (
stats := self._display_gif(ret[0], ret[1])
) is not None:
return stats
else:
self._display_image(filepath)
return self.__get_image_stats(filepath)
# Other Types (Including Images)
else:
self._display_image(filepath)
return self.__get_image_stats(filepath)
def _open_file_action_callback(self):
open_file(self.__current_file)
def _open_explorer_action_callback(self):
open_file(self.__current_file, file_manager=True)
def _delete_action_callback(self):
if bool(self.__current_file):
self.__driver.delete_files_callback(self.__current_file)
def _button_wrapper_callback(self):
open_file(self.__current_file)

View File

@@ -1,47 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import typing
from warnings import catch_warnings
from PySide6.QtWidgets import QListWidgetItem
from tagstudio.core.library.alchemy.library import Library
from tagstudio.qt.modals.add_field import AddFieldModal
from tagstudio.qt.modals.tag_search import TagSearchModal
from tagstudio.qt.view.widgets.preview_panel_view import PreviewPanelView
if typing.TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
class PreviewPanel(PreviewPanelView):
def __init__(self, library: Library, driver: "QtDriver"):
super().__init__(library, driver)
self.__add_field_modal = AddFieldModal(self.lib)
self.__add_tag_modal = TagSearchModal(self.lib, is_tag_chooser=True)
def _add_field_button_callback(self):
self.__add_field_modal.show()
def _add_tag_button_callback(self):
self.__add_tag_modal.show()
def _set_selection_callback(self):
with catch_warnings(record=True):
self.__add_field_modal.done.disconnect()
self.__add_tag_modal.tsp.tag_chosen.disconnect()
self.__add_field_modal.done.connect(self._add_field_to_selected)
self.__add_tag_modal.tsp.tag_chosen.connect(self._add_tag_to_selected)
def _add_field_to_selected(self, field_list: list[QListWidgetItem]):
self._fields.add_field_to_selected(field_list)
if len(self._selected) == 1:
self._fields.update_from_entry(self._selected[0])
def _add_tag_to_selected(self, tag_id: int):
self._fields.add_tags_to_selected(tag_id)
if len(self._selected) == 1:
self._fields.update_from_entry(self._selected[0])

View File

@@ -5,28 +5,24 @@
"""PySide6 port of the widgets/layouts/flowlayout example from Qt v6.x."""
from typing import Literal, override
from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt
from PySide6.QtWidgets import QLayout, QLayoutItem, QSizePolicy, QWidget
IGNORE_SIZE = "ignore_size"
from PySide6.QtWidgets import QLayout, QSizePolicy, QWidget
class FlowWidget(QWidget):
def __init__(self, parent: QWidget | None = None) -> None:
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setProperty(IGNORE_SIZE, False) # noqa: FBT003
self.ignore_size: bool = False
class FlowLayout(QLayout):
def __init__(self, parent: QWidget | None = None) -> None:
def __init__(self, parent=None):
super().__init__(parent)
if parent is not None:
self.setContentsMargins(QMargins(0, 0, 0, 0))
self._item_list: list[QLayoutItem] = []
self._item_list = []
self.grid_efficiency = False
def __del__(self):
@@ -34,56 +30,46 @@ class FlowLayout(QLayout):
while item:
item = self.takeAt(0)
@override
def addItem(self, arg__1: QLayoutItem) -> None:
self._item_list.append(arg__1)
def addItem(self, item): # noqa: N802
self._item_list.append(item)
@override
def count(self) -> int:
def count(self):
return len(self._item_list)
@override
def itemAt(self, index: int) -> QLayoutItem | None: # pyright: ignore[reportIncompatibleMethodOverride]
def itemAt(self, index): # noqa: N802
if 0 <= index < len(self._item_list):
return self._item_list[index]
return None
@override
def takeAt(self, index: int) -> QLayoutItem | None: # pyright: ignore[reportIncompatibleMethodOverride]
def takeAt(self, index): # noqa: N802
if 0 <= index < len(self._item_list):
return self._item_list.pop(index)
return None
@override
def expandingDirections(self) -> Qt.Orientation:
return Qt.Orientation.Horizontal
def expandingDirections(self): # noqa: N802
return Qt.Orientation(0)
@override
def hasHeightForWidth(self) -> Literal[True]:
def hasHeightForWidth(self): # noqa: N802
return True
@override
def heightForWidth(self, arg__1: int) -> int:
height = self._do_layout(QRect(0, 0, arg__1, 0), test_only=True)
return int(height)
def heightForWidth(self, width): # noqa: N802
height = self._do_layout(QRect(0, 0, width, 0), test_only=True)
return height
@override
def setGeometry(self, arg__1: QRect) -> None:
super().setGeometry(arg__1)
self._do_layout(arg__1, test_only=False)
def setGeometry(self, rect): # noqa: N802
super().setGeometry(rect)
self._do_layout(rect, test_only=False)
def enable_grid_optimizations(self, value: bool) -> None:
def enable_grid_optimizations(self, value: bool):
"""Enable or Disable efficiencies when all objects are equally sized."""
self.grid_efficiency = value
@override
def sizeHint(self) -> QSize:
def sizeHint(self): # noqa: N802
return self.minimumSize()
@override
def minimumSize(self) -> QSize:
def minimumSize(self): # noqa: N802
if self.grid_efficiency:
if self._item_list:
return self._item_list[0].minimumSize()
@@ -103,8 +89,8 @@ class FlowLayout(QLayout):
y = rect.y()
line_height = 0
spacing = self.spacing()
layout_spacing_x = 0
layout_spacing_y = 0
layout_spacing_x = None
layout_spacing_y = None
if self.grid_efficiency and self._item_list:
item = self._item_list[0]
@@ -122,12 +108,12 @@ class FlowLayout(QLayout):
for item in self._item_list:
skip_count = 0
ignore_size: bool | None = item.widget().property(IGNORE_SIZE)
if ignore_size:
if issubclass(type(item.widget()), FlowWidget) and item.widget().ignore_size:
skip_count += 1
else:
if (issubclass(type(item.widget()), FlowWidget) and not item.widget().ignore_size) or (
not issubclass(type(item.widget()), FlowWidget)
):
if not self.grid_efficiency:
style = item.widget().style()
layout_spacing_x = style.layoutSpacing(

View File

@@ -35,7 +35,7 @@ def theme_fg_overlay(image: Image.Image, use_alpha: bool = True) -> Image.Image:
return _apply_overlay(image, im)
def gradient_overlay(image: Image.Image, gradient: list[str]) -> Image.Image:
def gradient_overlay(image: Image.Image, gradient=list[str]) -> Image.Image:
"""Overlay a color gradient onto an image.
Args:

View File

@@ -3,14 +3,12 @@
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import os
import logging
from pathlib import Path
from platform import system
import structlog
from send2trash import send2trash
logger = structlog.get_logger(__name__)
logging.basicConfig(format="%(message)s", level=logging.INFO)
def delete_file(path: str | Path) -> bool:
@@ -21,38 +19,13 @@ def delete_file(path: str | Path) -> bool:
"""
_path = Path(path)
try:
if _path.is_dir():
return False
logger.info(f"[delete_file] Sending to Trash: {_path}")
logging.info(f"[delete_file] Sending to Trash: {_path}")
send2trash(_path)
return True
except PermissionError as e:
logger.error(f"[delete_file] PermissionError: {e}")
logging.error(f"[delete_file][ERROR] PermissionError: {e}")
except FileNotFoundError:
logger.error(f"[delete_file] File Not Found: {_path}")
except OSError as e:
if system() == "Darwin" and _path.exists():
logger.info(
f'[delete_file] Encountered "{e}" on macOS and file exists; '
"Assuming it's on a network volume and proceeding to delete..."
)
return _hard_delete_file(_path)
else:
logger.error("[delete_file] OSError", error=e)
logging.error(f"[delete_file][ERROR] File Not Found: {_path}")
except Exception as e:
logger.error("[delete_file] Unknown Error", error_type=type(e).__name__, error=e)
logging.error(e)
return False
def _hard_delete_file(path: Path) -> bool:
"""Hard delete a file from the system. Does NOT send to system trash.
Args:
path (str | Path): The path of the file to delete.
"""
try:
os.remove(path)
return True
except Exception as e:
logger.error("[hard_delete_file] Error", error_type=type(e).__name__, error=e)
return False

View File

@@ -7,14 +7,11 @@ import subprocess
import sys
import traceback
from pathlib import Path
from typing import override
import structlog
from PySide6.QtCore import Qt
from PySide6.QtGui import QMouseEvent
from PySide6.QtWidgets import QLabel, QWidget
from PySide6.QtWidgets import QLabel
from tagstudio.core.utils.types import unwrap
from tagstudio.qt.helpers.silent_popen import silent_Popen
logger = structlog.get_logger(__name__)
@@ -110,27 +107,23 @@ class FileOpenerHelper:
def open_file(self):
"""Open the file in the default application."""
if Path(self.filepath).is_file():
open_file(self.filepath)
open_file(self.filepath)
def open_explorer(self):
"""Open the file in the default file explorer."""
if Path(self.filepath).is_file():
open_file(self.filepath, file_manager=True)
open_file(self.filepath, file_manager=True)
class FileOpenerLabel(QLabel):
def __init__(self, parent: QWidget | None = None) -> None:
def __init__(self, parent=None):
"""Initialize the FileOpenerLabel.
Args:
parent (QWidget, optional): The parent widget. Defaults to None.
"""
self.filepath: str | Path | None = None
super().__init__(parent)
def set_file_path(self, filepath: str | Path) -> None:
def set_file_path(self, filepath):
"""Set the filepath to open.
Args:
@@ -138,21 +131,20 @@ class FileOpenerLabel(QLabel):
"""
self.filepath = filepath
@override
def mousePressEvent(self, ev: QMouseEvent) -> None:
def mousePressEvent(self, event): # noqa: N802
"""Handle mouse press events.
On a left click, open the file in the default file explorer.
On a right click, show a context menu.
Args:
ev (QMouseEvent): The mouse press event.
event (QMouseEvent): The mouse press event.
"""
if ev.button() == Qt.MouseButton.LeftButton:
opener = FileOpenerHelper(unwrap(self.filepath))
super().mousePressEvent(event)
if event.button() == Qt.MouseButton.LeftButton:
opener = FileOpenerHelper(self.filepath)
opener.open_explorer()
elif ev.button() == Qt.MouseButton.RightButton:
elif event.button() == Qt.MouseButton.RightButton:
# Show context menu
pass
else:
super().mousePressEvent(ev)

View File

@@ -7,7 +7,7 @@ from pathlib import Path
import ffmpeg
from tagstudio.qt.helpers.vendored.ffmpeg import probe
from tagstudio.qt.helpers.vendored.ffmpeg import _probe
def is_readable_video(filepath: Path | str):
@@ -19,8 +19,8 @@ def is_readable_video(filepath: Path | str):
filepath (Path | str): The filepath of the video to check.
"""
try:
result = probe(Path(filepath))
for stream in result["streams"]:
probe = _probe(Path(filepath))
for stream in probe["streams"]:
# DRM check
if stream.get("codec_tag_string") in [
"drma",

View File

@@ -49,8 +49,8 @@ def four_corner_gradient(
def linear_gradient(
size: tuple[int, int],
colors: list[str],
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")

View File

@@ -13,8 +13,6 @@ class QPushButtonWrapper(QPushButton):
the warning that is triggered by disconnecting a signal that is not currently connected.
"""
is_connected: bool
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_connected = False

View File

@@ -1,51 +0,0 @@
# Copyright (C) 2025
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from typing import override
import structlog
from PySide6.QtGui import QMouseEvent
from PySide6.QtWidgets import QSlider, QStyle, QStyleOptionSlider
logger = structlog.get_logger(__name__)
class QClickSlider(QSlider):
"""Custom QSlider wrapper.
The purpose of this wrapper is to allow us to set slider positions
based on click events.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@override
def mousePressEvent(self, ev: QMouseEvent):
"""Override to handle mouse clicks.
Overriding the mousePressEvent allows us to seek
directly to the position the user clicked instead
of stepping.
"""
opt = QStyleOptionSlider()
self.initStyleOption(opt)
handle_rect = self.style().subControlRect(
QStyle.ComplexControl.CC_Slider, opt, QStyle.SubControl.SC_SliderHandle, self
)
was_slider_clicked = handle_rect.contains(int(ev.position().x()), int(ev.position().y()))
if not was_slider_clicked:
self.setSliderDown(True)
self.setValue(
QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width())
)
super().mousePressEvent(ev)
@override
def mouseReleaseEvent(self, ev: QMouseEvent) -> None:
self.setSliderDown(False)
return super().mouseReleaseEvent(ev)

View File

@@ -84,79 +84,3 @@ def silent_Popen( # noqa: N802
pipesize=pipesize,
process_group=process_group,
)
def silent_run(
args,
bufsize=-1,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=True,
shell=False,
cwd=None,
env=None,
universal_newlines=None,
startupinfo=None,
creationflags=0,
restore_signals=True,
start_new_session=False,
pass_fds=(),
*,
capture_output=False,
group=None,
extra_groups=None,
user=None,
umask=-1,
encoding=None,
errors=None,
text=None,
pipesize=-1,
process_group=None,
):
"""Call subprocess.run without creating a console window."""
if sys.platform == "win32":
creationflags |= subprocess.CREATE_NO_WINDOW
import ctypes
ctypes.windll.kernel32.SetDllDirectoryW(None)
elif (
sys.platform == "linux"
or sys.platform.startswith("freebsd")
or sys.platform.startswith("openbsd")
):
# pass clean environment to the subprocess
env = os.environ
original_env = env.get("LD_LIBRARY_PATH_ORIG")
env["LD_LIBRARY_PATH"] = original_env if original_env else ""
return subprocess.run(
args=args,
bufsize=bufsize,
executable=executable,
stdin=stdin,
stdout=stdout,
stderr=stderr,
preexec_fn=preexec_fn,
close_fds=close_fds,
shell=shell,
cwd=cwd,
env=env,
startupinfo=startupinfo,
creationflags=creationflags,
restore_signals=restore_signals,
start_new_session=start_new_session,
pass_fds=pass_fds,
capture_output=capture_output,
group=group,
extra_groups=extra_groups,
user=user,
umask=umask,
encoding=encoding,
errors=errors,
text=text,
pipesize=pipesize,
process_group=process_group,
)

View File

@@ -6,11 +6,11 @@
from PIL import Image, ImageDraw, ImageFont
def wrap_line(
def wrap_line( # type: ignore
text: str,
font: ImageFont.ImageFont,
width: int = 256,
draw: ImageDraw.ImageDraw | None = None,
draw: ImageDraw.ImageDraw = None,
) -> int:
"""Take in a single text line and return the index it should be broken up at.
@@ -27,14 +27,15 @@ def wrap_line(
):
if draw.textlength(text[:i], font=font) < width:
return i
return -1
else:
return -1
def wrap_full_text(
text: str,
font: ImageFont.ImageFont,
width: int = 256,
draw: ImageDraw.ImageDraw | None = None,
draw: ImageDraw.ImageDraw = None,
) -> str:
"""Break up a string to fit the canvas given a kerning value, font size, etc."""
lines = []

View File

@@ -2,39 +2,29 @@
# Licensed under the GPL-3.0 License.
# Vendored from ffmpeg-python and ffmpeg-python PR#790 by amamic1803
import contextlib
import json
import os
import platform
import shutil
import subprocess
from shutil import which
import ffmpeg
import structlog
from tagstudio.qt.helpers.silent_popen import silent_Popen, silent_run
from tagstudio.qt.helpers.silent_popen import silent_Popen
logger = structlog.get_logger(__name__)
user = os.environ.get("USER", None)
FFMPEG_MACOS_LOCATIONS: list[str] = [
"",
"/opt/homebrew/bin/",
"/usr/local/bin/",
f"/etc/profiles/per-user/{user}/bin",
]
FFMPEG_MACOS_LOCATIONS: list[str] = ["", "/opt/homebrew/bin/", "/usr/local/bin/"]
def _get_ffprobe_location() -> str:
cmd: str = "ffprobe"
if platform.system() == "Darwin":
for loc in FFMPEG_MACOS_LOCATIONS:
if which(loc + cmd):
if shutil.which(loc + cmd):
cmd = loc + cmd
break
logger.info(
f"[FFmpeg] Using FFprobe location: {cmd}{' (Found)' if which(cmd) else ' (Not Found)'}"
)
logger.info(f"[FFMPEG] Using FFprobe location: {cmd}")
return cmd
@@ -42,12 +32,10 @@ def _get_ffmpeg_location() -> str:
cmd: str = "ffmpeg"
if platform.system() == "Darwin":
for loc in FFMPEG_MACOS_LOCATIONS:
if which(loc + cmd):
if shutil.which(loc + cmd):
cmd = loc + cmd
break
logger.info(
f"[FFmpeg] Using FFmpeg location: {cmd}{' (Found)' if which(cmd) else ' (Not Found)'}"
)
logger.info(f"[FFMPEG] Using FFmpeg location: {cmd}")
return cmd
@@ -55,7 +43,7 @@ FFPROBE_CMD = _get_ffprobe_location()
FFMPEG_CMD = _get_ffmpeg_location()
def probe(filename, cmd=FFPROBE_CMD, timeout=None, **kwargs):
def _probe(filename, cmd=FFPROBE_CMD, timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
@@ -65,7 +53,7 @@ def probe(filename, cmd=FFPROBE_CMD, timeout=None, **kwargs):
``stderr`` property of the exception.
"""
args = [cmd, "-show_format", "-show_streams", "-of", "json"]
args += ffmpeg._utils.convert_kwargs_to_cmd_line_args(kwargs) # pyright: ignore[reportAttributeAccessIssue]
args += ffmpeg._utils.convert_kwargs_to_cmd_line_args(kwargs)
args += [filename]
# PATCHED
@@ -77,22 +65,3 @@ def probe(filename, cmd=FFPROBE_CMD, timeout=None, **kwargs):
if p.returncode != 0:
raise ffmpeg.Error("ffprobe", out, err)
return json.loads(out.decode("utf-8"))
def version():
"""Checks the version of FFmpeg and FFprobe and returns None if they dont exist."""
version: dict[str, str | None] = {"ffmpeg": None, "ffprobe": None}
if which(FFMPEG_CMD):
ret = silent_run([FFMPEG_CMD, "-version"], shell=False, capture_output=True, text=True)
if ret.returncode == 0:
with contextlib.suppress(Exception):
version["ffmpeg"] = str(ret.stdout).split(" ")[2]
if which(FFPROBE_CMD):
ret = silent_run([FFPROBE_CMD, "-version"], shell=False, capture_output=True, text=True)
if ret.returncode == 0:
with contextlib.suppress(Exception):
version["ffprobe"] = str(ret.stdout).split(" ")[2]
return version

View File

@@ -3,15 +3,10 @@
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import logging
import typing
from collections.abc import Callable
from pathlib import Path
import structlog
from PIL import Image, ImageQt
from PySide6 import QtCore
from PySide6.QtCore import QMetaObject, QSize, QStringListModel, Qt
from PySide6.QtGui import QAction, QPixmap
from PySide6.QtCore import QMetaObject, QRect, QSize, QStringListModel, Qt
from PySide6.QtWidgets import (
QComboBox,
QCompleter,
@@ -21,8 +16,6 @@ from PySide6.QtWidgets import (
QLayout,
QLineEdit,
QMainWindow,
QMenu,
QMenuBar,
QPushButton,
QScrollArea,
QSizePolicy,
@@ -33,15 +26,7 @@ from PySide6.QtWidgets import (
QWidget,
)
from tagstudio.core.enums import ShowFilepathOption
from tagstudio.core.library.alchemy.enums import SortingModeEnum
from tagstudio.qt.controller.widgets.preview_panel_controller import PreviewPanel
from tagstudio.qt.flowlayout import FlowLayout
from tagstudio.qt.helpers.color_overlay import theme_fg_overlay
from tagstudio.qt.mnemonics import assign_mnemonics
from tagstudio.qt.pagination import Pagination
from tagstudio.qt.platform_strings import trash_term
from tagstudio.qt.resource_manager import ResourceManager
from tagstudio.qt.translations import Translations
from tagstudio.qt.widgets.landing import LandingWidget
@@ -49,452 +34,15 @@ from tagstudio.qt.widgets.landing import LandingWidget
if typing.TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
logger = structlog.get_logger(__name__)
logging.basicConfig(format="%(message)s", level=logging.INFO)
class MainMenuBar(QMenuBar):
file_menu: QMenu
open_library_action: QAction
open_recent_library_menu: QMenu
save_library_backup_action: QAction
settings_action: QAction
open_on_start_action: QAction
refresh_dir_action: QAction
close_library_action: QAction
edit_menu: QMenu
new_tag_action: QAction
select_all_action: QAction
select_inverse_action: QAction
clear_select_action: QAction
copy_fields_action: QAction
paste_fields_action: QAction
add_tag_to_selected_action: QAction
delete_file_action: QAction
ignore_modal_action: QAction
tag_manager_action: QAction
color_manager_action: QAction
view_menu: QMenu
show_filenames_action: QAction
tools_menu: QMenu
fix_unlinked_entries_action: QAction
fix_ignored_entries_action: QAction
fix_dupe_files_action: QAction
clear_thumb_cache_action: QAction
macros_menu: QMenu
folders_to_tags_action: QAction
help_menu: QMenu
about_action: QAction
def __init__(self, parent: QWidget | None = None):
class Ui_MainWindow(QMainWindow):
def __init__(self, driver: "QtDriver", parent=None) -> None:
super().__init__(parent)
self.setup_file_menu()
self.setup_edit_menu()
self.setup_view_menu()
self.setup_tools_menu()
self.setup_macros_menu()
self.setup_help_menu()
def setup_file_menu(self):
self.file_menu = QMenu(Translations["menu.file"], self)
# Open/Create Library
self.open_library_action = QAction(Translations["menu.file.open_create_library"], self)
self.open_library_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_O,
)
)
self.open_library_action.setToolTip("Ctrl+O")
self.file_menu.addAction(self.open_library_action)
# Open Recent
self.open_recent_library_menu = QMenu(Translations["menu.file.open_recent_library"], self)
self.file_menu.addMenu(self.open_recent_library_menu)
# Save Library Backup
self.save_library_backup_action = QAction(Translations["menu.file.save_backup"], self)
self.save_library_backup_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(
QtCore.Qt.KeyboardModifier.ControlModifier
| QtCore.Qt.KeyboardModifier.ShiftModifier
),
QtCore.Qt.Key.Key_S,
)
)
self.save_library_backup_action.setStatusTip("Ctrl+Shift+S")
self.save_library_backup_action.setEnabled(False)
self.file_menu.addAction(self.save_library_backup_action)
self.file_menu.addSeparator()
# Settings...
self.settings_action = QAction(Translations["menu.settings"], self)
self.file_menu.addAction(self.settings_action)
# Open Library on Start
self.open_on_start_action = QAction(Translations["settings.open_library_on_start"], self)
self.open_on_start_action.setCheckable(True)
self.file_menu.addAction(self.open_on_start_action)
self.file_menu.addSeparator()
# Refresh Directories
self.refresh_dir_action = QAction(Translations["menu.file.refresh_directories"], self)
self.refresh_dir_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_R,
)
)
self.refresh_dir_action.setStatusTip("Ctrl+R")
self.refresh_dir_action.setEnabled(False)
self.file_menu.addAction(self.refresh_dir_action)
self.file_menu.addSeparator()
# Close Library
self.close_library_action = QAction(Translations["menu.file.close_library"], self)
self.close_library_action.setEnabled(False)
self.file_menu.addAction(self.close_library_action)
self.file_menu.addSeparator()
assign_mnemonics(self.file_menu)
self.addMenu(self.file_menu)
def setup_edit_menu(self):
self.edit_menu = QMenu(Translations["generic.edit_alt"], self)
# New Tag
self.new_tag_action = QAction(Translations["menu.edit.new_tag"], self)
self.new_tag_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_T,
)
)
self.new_tag_action.setToolTip("Ctrl+T")
self.new_tag_action.setEnabled(False)
self.edit_menu.addAction(self.new_tag_action)
self.edit_menu.addSeparator()
# Select All
self.select_all_action = QAction(Translations["select.all"], self)
self.select_all_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_A,
)
)
self.select_all_action.setToolTip("Ctrl+A")
self.select_all_action.setEnabled(False)
self.edit_menu.addAction(self.select_all_action)
# Invert Selection
self.select_inverse_action = QAction(Translations["select.inverse"], self)
self.select_inverse_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(
QtCore.Qt.KeyboardModifier.ControlModifier
^ QtCore.Qt.KeyboardModifier.ShiftModifier
),
QtCore.Qt.Key.Key_I,
)
)
self.select_inverse_action.setToolTip("Ctrl+Shift+I")
self.select_inverse_action.setEnabled(False)
self.edit_menu.addAction(self.select_inverse_action)
# Clear Selection
self.clear_select_action = QAction(Translations["select.clear"], self)
self.clear_select_action.setShortcut(QtCore.Qt.Key.Key_Escape)
self.clear_select_action.setToolTip("Esc")
self.clear_select_action.setEnabled(False)
self.edit_menu.addAction(self.clear_select_action)
# Copy Fields
self.copy_fields_action = QAction(Translations["edit.copy_fields"], self)
self.copy_fields_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_C,
)
)
self.copy_fields_action.setToolTip("Ctrl+C")
self.copy_fields_action.setEnabled(False)
self.edit_menu.addAction(self.copy_fields_action)
# Paste Fields
self.paste_fields_action = QAction(Translations["edit.paste_fields"], self)
self.paste_fields_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_V,
)
)
self.paste_fields_action.setToolTip("Ctrl+V")
self.paste_fields_action.setEnabled(False)
self.edit_menu.addAction(self.paste_fields_action)
# Add Tag to Selected
self.add_tag_to_selected_action = QAction(Translations["select.add_tag_to_selected"], self)
self.add_tag_to_selected_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(
QtCore.Qt.KeyboardModifier.ControlModifier
^ QtCore.Qt.KeyboardModifier.ShiftModifier
),
QtCore.Qt.Key.Key_T,
)
)
self.add_tag_to_selected_action.setToolTip("Ctrl+Shift+T")
self.add_tag_to_selected_action.setEnabled(False)
self.edit_menu.addAction(self.add_tag_to_selected_action)
self.edit_menu.addSeparator()
# Move Files to trash
self.delete_file_action = QAction(
Translations.format("menu.delete_selected_files_ambiguous", trash_term=trash_term()),
self,
)
self.delete_file_action.setShortcut(QtCore.Qt.Key.Key_Delete)
self.delete_file_action.setEnabled(False)
self.edit_menu.addAction(self.delete_file_action)
self.edit_menu.addSeparator()
# Ignore Files and Directories (.ts_ignore System)
self.ignore_modal_action = QAction(Translations["menu.edit.ignore_files"], self)
self.ignore_modal_action.setEnabled(False)
self.edit_menu.addAction(self.ignore_modal_action)
# Manage Tags
self.tag_manager_action = QAction(Translations["menu.edit.manage_tags"], self)
self.tag_manager_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_M,
)
)
self.tag_manager_action.setEnabled(False)
self.tag_manager_action.setToolTip("Ctrl+M")
self.edit_menu.addAction(self.tag_manager_action)
# Color Manager
self.color_manager_action = QAction(Translations["edit.color_manager"], self)
self.color_manager_action.setEnabled(False)
self.edit_menu.addAction(self.color_manager_action)
assign_mnemonics(self.edit_menu)
self.addMenu(self.edit_menu)
def setup_view_menu(self):
self.view_menu = QMenu(Translations["menu.view"], self)
self.library_info_action = QAction(Translations["menu.view.library_info"])
self.view_menu.addAction(self.library_info_action)
# show_libs_list_action = QAction(Translations["settings.show_recent_libraries"], menu_bar)
# show_libs_list_action.setCheckable(True)
# show_libs_list_action.setChecked(self.settings.show_library_list)
self.show_filenames_action = QAction(Translations["settings.show_filenames_in_grid"], self)
self.show_filenames_action.setCheckable(True)
self.view_menu.addAction(self.show_filenames_action)
self.view_menu.addSeparator()
self.increase_thumbnail_size_action = QAction(
Translations["menu.view.increase_thumbnail_size"], self
)
self.increase_thumbnail_size_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_Plus,
)
)
self.increase_thumbnail_size_action.setToolTip("Ctrl++")
self.view_menu.addAction(self.increase_thumbnail_size_action)
self.decrease_thumbnail_size_action = QAction(
Translations["menu.view.decrease_thumbnail_size"], self
)
self.decrease_thumbnail_size_action.setShortcut(
QtCore.QKeyCombination(
QtCore.Qt.KeyboardModifier(QtCore.Qt.KeyboardModifier.ControlModifier),
QtCore.Qt.Key.Key_Minus,
)
)
self.decrease_thumbnail_size_action.setToolTip("Ctrl+-")
self.view_menu.addAction(self.decrease_thumbnail_size_action)
self.view_menu.addSeparator()
assign_mnemonics(self.view_menu)
self.addMenu(self.view_menu)
def setup_tools_menu(self):
self.tools_menu = QMenu(Translations["menu.tools"], self)
# Fix Unlinked Entries
self.fix_unlinked_entries_action = QAction(
Translations["menu.tools.fix_unlinked_entries"], self
)
self.fix_unlinked_entries_action.setEnabled(False)
self.tools_menu.addAction(self.fix_unlinked_entries_action)
# Fix Ignored Entries
self.fix_ignored_entries_action = QAction(
Translations["menu.tools.fix_ignored_entries"], self
)
self.fix_ignored_entries_action.setEnabled(False)
self.tools_menu.addAction(self.fix_ignored_entries_action)
# Fix Duplicate Files
self.fix_dupe_files_action = QAction(Translations["menu.tools.fix_duplicate_files"], self)
self.fix_dupe_files_action.setEnabled(False)
self.tools_menu.addAction(self.fix_dupe_files_action)
self.tools_menu.addSeparator()
# Clear Thumbnail Cache
self.clear_thumb_cache_action = QAction(
Translations["settings.clear_thumb_cache.title"], self
)
self.clear_thumb_cache_action.setEnabled(False)
self.tools_menu.addAction(self.clear_thumb_cache_action)
assign_mnemonics(self.tools_menu)
self.addMenu(self.tools_menu)
def setup_macros_menu(self):
self.macros_menu = QMenu(Translations["menu.macros"], self)
self.folders_to_tags_action = QAction(Translations["menu.macros.folders_to_tags"], self)
self.folders_to_tags_action.setEnabled(False)
self.macros_menu.addAction(self.folders_to_tags_action)
assign_mnemonics(self.macros_menu)
self.addMenu(self.macros_menu)
def setup_help_menu(self):
self.help_menu = QMenu(Translations["menu.help"], self)
self.about_action = QAction(Translations["menu.help.about"], self)
self.help_menu.addAction(self.about_action)
assign_mnemonics(self.help_menu)
self.addMenu(self.help_menu)
def rebuild_open_recent_library_menu(
self,
libraries: list[Path],
show_filepath: ShowFilepathOption,
open_library_callback: Callable[[Path], None],
clear_libraries_callback: Callable[[], None],
):
actions: list[QAction] = []
for path in libraries:
action = QAction(self.open_recent_library_menu)
if show_filepath == ShowFilepathOption.SHOW_FULL_PATHS:
action.setText(str(path))
else:
action.setText(str(path.name))
action.triggered.connect(lambda checked=False, p=path: open_library_callback(p))
actions.append(action)
clear_recent_action = QAction(
Translations["menu.file.clear_recent_libraries"], self.open_recent_library_menu
)
clear_recent_action.triggered.connect(clear_libraries_callback)
actions.append(clear_recent_action)
# Clear previous actions
for action in self.open_recent_library_menu.actions():
self.open_recent_library_menu.removeAction(action)
# Add new actions
for action in actions:
self.open_recent_library_menu.addAction(action)
# Only enable add "clear recent" if there are still recent libraries.
if len(actions) > 1:
self.open_recent_library_menu.setDisabled(False)
self.open_recent_library_menu.addSeparator()
self.open_recent_library_menu.addAction(clear_recent_action)
else:
self.open_recent_library_menu.setDisabled(True)
# View Component
class MainWindow(QMainWindow):
THUMB_SIZES: list[tuple[str, int]] = [
(Translations["home.thumbnail_size.extra_large"], 256),
(Translations["home.thumbnail_size.large"], 192),
(Translations["home.thumbnail_size.medium"], 128),
(Translations["home.thumbnail_size.small"], 96),
(Translations["home.thumbnail_size.mini"], 76),
]
def __init__(self, driver: "QtDriver", parent: QWidget | None = None) -> None:
super().__init__(parent)
self.rm = ResourceManager()
# region Type declarations for variables that will be initialized in methods
# initialized in setup_search_bar
self.search_bar_layout: QHBoxLayout
self.back_button: QPushButton
self.forward_button: QPushButton
self.search_field: QLineEdit
self.search_field_completion_list: QStringListModel
self.search_field_completer: QCompleter
self.search_button: QPushButton
# initialized in setup_extra_input_bar
self.extra_input_layout: QHBoxLayout
self.sorting_mode_combobox: QComboBox
self.sorting_direction_combobox: QComboBox
self.thumb_size_combobox: QComboBox
# initialized in setup_content
self.content_layout: QHBoxLayout
self.content_splitter: QSplitter
# initialized in setup_entry_list
self.entry_list_container: QWidget
self.entry_list_layout: QVBoxLayout
self.entry_scroll_area: QScrollArea
self.thumb_grid: QWidget
self.thumb_layout: FlowLayout
self.landing_widget: LandingWidget
self.pagination: Pagination
# initialized in setup_preview_panel
self.preview_panel: PreviewPanel
# endregion
if not self.objectName():
self.setObjectName("MainWindow")
self.resize(1300, 720)
self.setup_menu_bar()
self.setup_central_widget(driver)
self.setup_status_bar()
QMetaObject.connectSlotsByName(self)
self.driver: "QtDriver" = driver
self.setupUi(self)
# NOTE: These are old attempts to allow for a translucent/acrylic
# window effect. This may be attempted again in the future.
@@ -506,207 +54,155 @@ class MainWindow(QMainWindow):
# self.windowFX = WindowEffect()
# self.windowFX.setAcrylicEffect(self.winId(), isEnableShadow=False)
# region UI Setup Methods
# region Menu Bar
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(1300, 720)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.gridLayout = QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(u"gridLayout")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
# ComboBox group for search type and thumbnail size
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
# left side spacer
spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem)
# Sorting Dropdowns
self.sorting_mode_combobox = QComboBox(self.centralwidget)
self.sorting_mode_combobox.setObjectName(u"sortingModeComboBox")
self.horizontalLayout_3.addWidget(self.sorting_mode_combobox)
self.sorting_direction_combobox = QComboBox(self.centralwidget)
self.sorting_direction_combobox.setObjectName(u"sortingDirectionCombobox")
self.horizontalLayout_3.addWidget(self.sorting_direction_combobox)
def setup_menu_bar(self):
self.menu_bar = MainMenuBar(self)
self.setMenuBar(self.menu_bar)
self.menu_bar.setNativeMenuBar(True)
# endregion
def setup_central_widget(self, driver: "QtDriver"):
self.central_widget = QWidget(self)
self.central_widget.setObjectName("central_widget")
self.central_layout = QGridLayout(self.central_widget)
self.central_layout.setObjectName("central_layout")
self.setup_search_bar()
self.setup_extra_input_bar()
self.setup_content(driver)
self.setCentralWidget(self.central_widget)
def setup_search_bar(self):
"""Sets up Nav Buttons, Search Field, Search Button."""
self.search_bar_layout = QHBoxLayout()
self.search_bar_layout.setObjectName("search_bar_layout")
self.search_bar_layout.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize)
self.back_button = QPushButton(self.central_widget)
back_icon: Image.Image = self.rm.get("bxs-left-arrow") # pyright: ignore[reportAssignmentType]
back_icon = theme_fg_overlay(back_icon, use_alpha=False)
self.back_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(back_icon)))
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.get("bxs-right-arrow") # pyright: ignore[reportAssignmentType]
forward_icon = theme_fg_overlay(forward_icon, use_alpha=False)
self.forward_button.setIcon(QPixmap.fromImage(ImageQt.ImageQt(forward_icon)))
self.forward_button.setIconSize(QSize(16, 16))
self.forward_button.setObjectName("forward_button")
self.forward_button.setMinimumSize(QSize(32, 32))
self.forward_button.setMaximumSize(QSize(32, 16777215))
self.search_bar_layout.addWidget(self.forward_button)
self.search_field = QLineEdit(self.central_widget)
self.search_field.setPlaceholderText(Translations["home.search_entries"])
self.search_field.setObjectName("search_field")
self.search_field.setMinimumSize(QSize(0, 32))
self.search_field_completion_list = QStringListModel()
self.search_field_completer = QCompleter(
self.search_field_completion_list, self.search_field
)
self.search_field_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.search_field.setCompleter(self.search_field_completer)
self.search_bar_layout.addWidget(self.search_field)
self.search_button = QPushButton(Translations["home.search"], self.central_widget)
self.search_button.setObjectName("search_button")
self.search_button.setMinimumSize(QSize(0, 32))
self.search_bar_layout.addWidget(self.search_button)
self.central_layout.addLayout(self.search_bar_layout, 3, 0, 1, 1)
def setup_extra_input_bar(self):
"""Sets up inputs for sorting settings and thumbnail size."""
self.extra_input_layout = QHBoxLayout()
self.extra_input_layout.setObjectName("extra_input_layout")
## left side spacer
self.extra_input_layout.addItem(
QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
)
## Sorting Mode Dropdown
self.sorting_mode_combobox = QComboBox(self.central_widget)
self.sorting_mode_combobox.setObjectName("sorting_mode_combobox")
for sort_mode in SortingModeEnum:
self.sorting_mode_combobox.addItem(Translations[sort_mode.value], sort_mode)
self.extra_input_layout.addWidget(self.sorting_mode_combobox)
## Sorting Direction Dropdown
self.sorting_direction_combobox = QComboBox(self.central_widget)
self.sorting_direction_combobox.setObjectName("sorting_direction_combobox")
self.sorting_direction_combobox.addItem(
Translations["sorting.direction.ascending"], userData=True
)
self.sorting_direction_combobox.addItem(
Translations["sorting.direction.descending"], userData=False
)
self.sorting_direction_combobox.setCurrentIndex(1) # Default: Descending
self.extra_input_layout.addWidget(self.sorting_direction_combobox)
## Thumbnail Size placeholder
self.thumb_size_combobox = QComboBox(self.central_widget)
self.thumb_size_combobox.setObjectName("thumb_size_combobox")
# Thumbnail Size placeholder
self.thumb_size_combobox = QComboBox(self.centralwidget)
self.thumb_size_combobox.setObjectName(u"thumbSizeComboBox")
self.thumb_size_combobox.setPlaceholderText(Translations["home.thumbnail_size"])
self.thumb_size_combobox.setCurrentText("")
size_policy = QSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(self.thumb_size_combobox.sizePolicy().hasHeightForWidth())
self.thumb_size_combobox.setSizePolicy(size_policy)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.thumb_size_combobox.sizePolicy().hasHeightForWidth())
self.thumb_size_combobox.setSizePolicy(sizePolicy)
self.thumb_size_combobox.setMinimumWidth(128)
self.thumb_size_combobox.setMaximumWidth(352)
self.extra_input_layout.addWidget(self.thumb_size_combobox)
for size in MainWindow.THUMB_SIZES:
self.thumb_size_combobox.addItem(size[0], size[1])
self.thumb_size_combobox.setCurrentIndex(2) # Default: Medium
self.horizontalLayout_3.addWidget(self.thumb_size_combobox)
self.gridLayout.addLayout(self.horizontalLayout_3, 5, 0, 1, 1)
self.central_layout.addLayout(self.extra_input_layout, 5, 0, 1, 1)
self.splitter = QSplitter()
self.splitter.setObjectName(u"splitter")
self.splitter.setHandleWidth(12)
def setup_content(self, driver: "QtDriver"):
self.content_layout = QHBoxLayout()
self.content_layout.setObjectName("content_layout")
self.frame_container = QWidget()
self.frame_layout = QVBoxLayout(self.frame_container)
self.frame_layout.setSpacing(0)
self.content_splitter = QSplitter()
self.content_splitter.setObjectName("content_splitter")
self.content_splitter.setHandleWidth(12)
self.setup_entry_list(driver)
self.setup_preview_panel(driver)
self.content_splitter.setStretchFactor(0, 1)
self.content_layout.addWidget(self.content_splitter)
self.central_layout.addLayout(self.content_layout, 10, 0, 1, 1)
def setup_entry_list(self, driver: "QtDriver"):
self.entry_list_container = QWidget()
self.entry_list_layout = QVBoxLayout(self.entry_list_container)
self.entry_list_layout.setSpacing(0)
self.entry_scroll_area = QScrollArea()
self.entry_scroll_area.setObjectName("entry_scroll_area")
self.entry_scroll_area.setFocusPolicy(Qt.FocusPolicy.WheelFocus)
self.entry_scroll_area.setFrameShape(QFrame.Shape.NoFrame)
self.entry_scroll_area.setFrameShadow(QFrame.Shadow.Plain)
self.entry_scroll_area.setWidgetResizable(True)
self.entry_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.thumb_grid = QWidget()
self.thumb_grid.setObjectName("thumb_grid")
self.thumb_layout = FlowLayout()
self.thumb_layout.enable_grid_optimizations(value=True)
self.thumb_layout.setSpacing(min(self.thumb_size // 10, 12))
self.thumb_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.thumb_grid.setLayout(self.thumb_layout)
self.entry_scroll_area.setWidget(self.thumb_grid)
self.entry_list_layout.addWidget(self.entry_scroll_area)
self.landing_widget = LandingWidget(driver, self.devicePixelRatio())
self.entry_list_layout.addWidget(self.landing_widget)
self.scrollArea = QScrollArea()
self.scrollArea.setObjectName(u"scrollArea")
self.scrollArea.setFocusPolicy(Qt.WheelFocus)
self.scrollArea.setFrameShape(QFrame.NoFrame)
self.scrollArea.setFrameShadow(QFrame.Plain)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollAreaWidgetContents.setObjectName(
u"scrollAreaWidgetContents")
self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 1260, 590))
self.gridLayout_2 = QGridLayout(self.scrollAreaWidgetContents)
self.gridLayout_2.setSpacing(8)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.gridLayout_2.setContentsMargins(0, 0, 0, 8)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.frame_layout.addWidget(self.scrollArea)
self.landing_widget: LandingWidget = LandingWidget(self.driver, self.devicePixelRatio())
self.frame_layout.addWidget(self.landing_widget)
self.pagination = Pagination()
self.entry_list_layout.addWidget(self.pagination)
self.content_splitter.addWidget(self.entry_list_container)
self.frame_layout.addWidget(self.pagination)
def setup_preview_panel(self, driver: "QtDriver"):
self.preview_panel = PreviewPanel(driver.lib, driver)
self.content_splitter.addWidget(self.preview_panel)
self.horizontalLayout.addWidget(self.splitter)
self.splitter.addWidget(self.frame_container)
self.splitter.setStretchFactor(0, 1)
self.gridLayout.addLayout(self.horizontalLayout, 10, 0, 1, 1)
def setup_status_bar(self):
self.status_bar = QStatusBar(self)
self.status_bar.setObjectName("status_bar")
status_bar_size_policy = QSizePolicy(
QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum
)
status_bar_size_policy.setHorizontalStretch(0)
status_bar_size_policy.setVerticalStretch(0)
status_bar_size_policy.setHeightForWidth(self.status_bar.sizePolicy().hasHeightForWidth())
self.status_bar.setSizePolicy(status_bar_size_policy)
self.status_bar.setSizeGripEnabled(False)
self.setStatusBar(self.status_bar)
nav_button_style = "font-size:14;font-weight:bold;"
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalLayout_2.setSizeConstraint(QLayout.SetMinimumSize)
self.backButton = QPushButton("<", self.centralwidget)
self.backButton.setObjectName(u"backButton")
self.backButton.setMinimumSize(QSize(0, 32))
self.backButton.setMaximumSize(QSize(32, 16777215))
self.backButton.setStyleSheet(nav_button_style)
self.horizontalLayout_2.addWidget(self.backButton)
# endregion
self.forwardButton = QPushButton(">", self.centralwidget)
self.forwardButton.setObjectName(u"forwardButton")
self.forwardButton.setMinimumSize(QSize(0, 32))
self.forwardButton.setMaximumSize(QSize(32, 16777215))
self.forwardButton.setStyleSheet(nav_button_style)
self.horizontalLayout_2.addWidget(self.forwardButton)
self.searchField = QLineEdit(self.centralwidget)
self.searchField.setPlaceholderText(Translations["home.search_entries"])
self.searchField.setObjectName(u"searchField")
self.searchField.setMinimumSize(QSize(0, 32))
self.searchFieldCompletionList = QStringListModel()
self.searchFieldCompleter = QCompleter(self.searchFieldCompletionList, self.searchField)
self.searchFieldCompleter.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.searchField.setCompleter(self.searchFieldCompleter)
self.horizontalLayout_2.addWidget(self.searchField)
self.searchButton = QPushButton(Translations["home.search"], self.centralwidget)
self.searchButton.setObjectName(u"searchButton")
self.searchButton.setMinimumSize(QSize(0, 32))
self.horizontalLayout_2.addWidget(self.searchButton)
self.gridLayout.addLayout(self.horizontalLayout_2, 3, 0, 1, 1)
self.gridLayout_2.setContentsMargins(6, 6, 6, 6)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
sizePolicy1.setHeightForWidth(
self.statusbar.sizePolicy().hasHeightForWidth())
self.statusbar.setSizePolicy(sizePolicy1)
self.statusbar.setSizeGripEnabled(False)
MainWindow.setStatusBar(self.statusbar)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def moveEvent(self, event) -> None:
# time.sleep(0.02) # sleep for 20ms
pass
def resizeEvent(self, event) -> None:
# time.sleep(0.02) # sleep for 20ms
pass
def toggle_landing_page(self, enabled: bool):
if enabled:
self.entry_scroll_area.setHidden(True)
self.scrollArea.setHidden(True)
self.landing_widget.setHidden(False)
self.landing_widget.animate_logo_in()
else:
self.landing_widget.setHidden(True)
self.landing_widget.set_status_label("")
self.entry_scroll_area.setHidden(False)
@property
def sorting_mode(self) -> SortingModeEnum:
"""What to sort by."""
return self.sorting_mode_combobox.currentData()
@property
def sorting_direction(self) -> bool:
"""Whether to Sort the results in ascending order."""
return self.sorting_direction_combobox.currentData()
@property
def thumb_size(self) -> int:
return self.thumb_size_combobox.currentData()
self.scrollArea.setHidden(False)

View File

@@ -1,142 +0,0 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QMenu
def remove_mnemonic_marker(label: str) -> str:
"""Remove existing accelerator markers (&) from a label."""
result = ""
skip = False
for i, ch in enumerate(label):
if skip:
skip = False
continue
if ch == "&":
# escaped ampersand "&&"
if i + 1 < len(label) and label[i + 1] == "&":
result += "&"
skip = True
# otherwise skip this '&'
continue
result += ch
return result
# Additional weight for first character in string
FIRST_CHARACTER_EXTRA_WEIGHT = 50
# Additional weight for the beginning of a word
WORD_BEGINNING_EXTRA_WEIGHT = 50
# Additional weight for a 'wanted' accelerator ie string with '&'
WANTED_ACCEL_EXTRA_WEIGHT = 150
def calculate_weights(text: str):
weights: dict[int, str] = {}
pos = 0
start_character = True
wanted_character = False
while pos < len(text):
c = text[pos]
# skip non typeable characters
if not c.isalnum() and c != "&":
start_character = True
pos += 1
continue
weight = 1
# add special weight to first character
if pos == 0:
weight += FIRST_CHARACTER_EXTRA_WEIGHT
elif start_character: # add weight to word beginnings
weight += WORD_BEGINNING_EXTRA_WEIGHT
start_character = False
# add weight to characters that have an & beforehand
if wanted_character:
weight += WANTED_ACCEL_EXTRA_WEIGHT
wanted_character = False
# add decreasing weight to left characters
if pos < 50:
weight += 50 - pos
# try to preserve the wanted accelerators
if c == "&" and (pos != len(text) - 1 and text[pos + 1] != "&" and text[pos + 1].isalnum()):
wanted_character = True
pos += 1
continue
while weight in weights:
weight += 1
if c != "&":
weights[weight] = c
pos += 1
# update our maximum weight
max_weight = 0 if len(weights) == 0 else max(weights.keys())
return max_weight, weights
def insert_mnemonic(label: str, char: str) -> str:
pos = label.lower().find(char)
if pos >= 0:
return label[:pos] + "&" + label[pos:]
return label
def assign_mnemonics(menu: QMenu):
# Collect actions
actions = [a for a in menu.actions() if not a.isSeparator()]
# Sequence map: mnemonic key -> QAction
sequence_to_action: dict[str, QAction] = {}
final_text: dict[QAction, str] = {}
actions.reverse()
while len(actions) > 0:
action = actions.pop()
label = action.text()
_, weights = calculate_weights(label)
chosen_char = None
# Try candidates, starting from highest weight
for weight in sorted(weights.keys(), reverse=True):
c = weights[weight].lower()
other = sequence_to_action.get(c)
if other is None:
chosen_char = c
sequence_to_action[c] = action
break
else:
# Compare weights with existing action
other_max, _ = calculate_weights(remove_mnemonic_marker(other.text()))
if weight > other_max:
# Take over from weaker action
actions.append(other)
sequence_to_action[c] = action
chosen_char = c
# Apply mnemonic if found
if chosen_char:
plain = remove_mnemonic_marker(label)
new_label = insert_mnemonic(plain, chosen_char)
final_text[action] = new_label
else:
# No mnemonic assigned → clean text
final_text[action] = remove_mnemonic_marker(label)
for a, t in final_text.items():
a.setText(t)

View File

@@ -21,7 +21,7 @@ from PySide6.QtWidgets import (
from tagstudio.core.constants import VERSION, VERSION_BRANCH
from tagstudio.core.enums import Theme
from tagstudio.core.palette import ColorType, UiColor, get_ui_color
from tagstudio.qt.helpers.vendored import ffmpeg
from tagstudio.qt.modals.ffmpeg_checker import FfmpegChecker
from tagstudio.qt.resource_manager import ResourceManager
from tagstudio.qt.translations import Translations
@@ -31,15 +31,14 @@ class AboutModal(QWidget):
super().__init__()
self.setWindowTitle(Translations["about.title"])
self.fc: FfmpegChecker = FfmpegChecker()
self.rm: ResourceManager = ResourceManager()
# TODO: There should be a global button theme somewhere.
self.form_content_style = (
f"background-color:{
Theme.COLOR_BG.value
if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark
else Theme.COLOR_BG_LIGHT.value
};"
f"background-color:{Theme.COLOR_BG.value
if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark
else Theme.COLOR_BG_LIGHT.value};"
"border-radius:3px;"
"font-weight: 500;"
"padding: 2px;"
@@ -81,7 +80,7 @@ class AboutModal(QWidget):
self.desc_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
# System Info ----------------------------------------------------------
ff_version = ffmpeg.version()
ff_version = self.fc.version()
red = get_ui_color(ColorType.PRIMARY, UiColor.RED)
green = get_ui_color(ColorType.PRIMARY, UiColor.GREEN)
missing = Translations["generic.missing"]
@@ -104,14 +103,14 @@ class AboutModal(QWidget):
self.system_info_layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
# License
license_title = QLabel(f"{Translations['about.license']}")
license_title = QLabel(f'{Translations["about.license"]}')
license_content = QLabel("GPLv3")
license_content.setStyleSheet(self.form_content_style)
license_content.setMaximumWidth(license_content.sizeHint().width())
self.system_info_layout.addRow(license_title, license_content)
# Config Path
config_path_title = QLabel(f"{Translations['about.config_path']}")
config_path_title = QLabel(f'{Translations["about.config_path"]}')
config_path_content = QLabel(f"{config_path}")
config_path_content.setStyleSheet(self.form_content_style)
config_path_content.setWordWrap(True)

View File

@@ -87,8 +87,6 @@ class AddFieldModal(QWidget):
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: # noqa N802
if event.key() == QtCore.Qt.Key.Key_Escape:
self.cancel_button.click()
elif event.key() in (QtCore.Qt.Key.Key_Enter, QtCore.Qt.Key.Key_Return):
self.save_button.click()
else: # Other key presses
pass
return super().keyPressEvent(event)

View File

@@ -30,7 +30,7 @@ from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Tag, TagColorGroup
from tagstudio.core.palette import ColorType, UiColor, get_tag_color, get_ui_color
from tagstudio.qt.modals.tag_color_selection import TagColorSelection
from tagstudio.qt.modals.tag_search import TagSearchModal, TagSearchPanel
from tagstudio.qt.modals.tag_search import TagSearchPanel
from tagstudio.qt.translations import Translations
from tagstudio.qt.widgets.panel import PanelModal, PanelWidget
from tagstudio.qt.widgets.tag import (
@@ -166,8 +166,11 @@ class BuildTagPanel(PanelWidget):
if tag is not None:
exclude_ids.append(tag.id)
self.add_tag_modal = TagSearchModal(self.lib, exclude_ids)
self.add_tag_modal.tsp.tag_chosen.connect(lambda x: self.add_parent_tag_callback(x))
tsp = TagSearchPanel(self.lib, exclude_ids)
tsp.tag_chosen.connect(lambda x: self.add_parent_tag_callback(x))
self.add_tag_modal = PanelModal(tsp)
self.add_tag_modal.setTitle(Translations["tag.parent_tags.add"])
self.add_tag_modal.setWindowTitle(Translations["tag.parent_tags.add"])
self.parent_tags_add_button.clicked.connect(self.add_tag_modal.show)
# Color ----------------------------------------------------------------
@@ -385,11 +388,10 @@ class BuildTagPanel(PanelWidget):
tag_widget = TagWidget(
tag,
library=self.lib,
has_edit=True,
has_edit=False,
has_remove=True,
)
tag_widget.on_remove.connect(lambda t=parent_id: self.remove_parent_tag_callback(t))
tag_widget.on_edit.connect(lambda t=tag: TagSearchPanel(library=self.lib).edit_tag(t))
row.addWidget(tag_widget)
# Add Disambiguation Tag Button

View File

@@ -17,7 +17,7 @@ from PySide6.QtWidgets import (
QWidget,
)
from tagstudio.core.utils.ignored_registry import IgnoredRegistry
from tagstudio.core.utils.missing_files import MissingRegistry
from tagstudio.qt.helpers.custom_runnable import CustomRunnable
from tagstudio.qt.translations import Translations
from tagstudio.qt.widgets.progress import ProgressWidget
@@ -27,14 +27,14 @@ if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
class RemoveIgnoredModal(QWidget):
class DeleteUnlinkedEntriesModal(QWidget):
done = Signal()
def __init__(self, driver: "QtDriver", tracker: IgnoredRegistry):
def __init__(self, driver: "QtDriver", tracker: MissingRegistry):
super().__init__()
self.driver = driver
self.tracker = tracker
self.setWindowTitle(Translations["entries.ignored.remove"])
self.setWindowTitle(Translations["entries.unlinked.delete"])
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setMinimumSize(500, 400)
self.root_layout = QVBoxLayout(self)
@@ -42,8 +42,8 @@ class RemoveIgnoredModal(QWidget):
self.desc_widget = QLabel(
Translations.format(
"entries.remove.plural.confirm",
count=self.tracker.ignored_count,
"entries.unlinked.delete.confirm",
count=self.tracker.missing_file_entries_count,
)
)
self.desc_widget.setObjectName("descriptionLabel")
@@ -64,7 +64,7 @@ class RemoveIgnoredModal(QWidget):
self.cancel_button.clicked.connect(self.hide)
self.button_layout.addWidget(self.cancel_button)
self.delete_button = QPushButton(Translations["generic.remove_alt"])
self.delete_button = QPushButton(Translations["generic.delete_alt"])
self.delete_button.clicked.connect(self.hide)
self.delete_button.clicked.connect(lambda: self.delete_entries())
self.button_layout.addWidget(self.delete_button)
@@ -75,11 +75,13 @@ class RemoveIgnoredModal(QWidget):
def refresh_list(self):
self.desc_widget.setText(
Translations.format("entries.remove.plural.confirm", count=self.tracker.ignored_count)
Translations.format(
"entries.unlinked.delete.confirm", count=self.tracker.missing_file_entries_count
)
)
self.model.clear()
for i in self.tracker.ignored_entries:
for i in self.tracker.missing_file_entries:
item = QStandardItem(str(i.path))
item.setEditable(False)
self.model.appendRow(item)
@@ -90,15 +92,11 @@ class RemoveIgnoredModal(QWidget):
minimum=0,
maximum=0,
)
pw.setWindowTitle(Translations["entries.generic.remove.removing"])
pw.update_label(
Translations.format(
"entries.generic.remove.removing_count", count=self.tracker.ignored_count
)
)
pw.setWindowTitle(Translations["entries.unlinked.delete.deleting"])
pw.update_label(Translations["entries.unlinked.delete.deleting"])
pw.show()
r = CustomRunnable(self.tracker.remove_ignored_entries)
r = CustomRunnable(self.tracker.execute_deletion)
QThreadPool.globalInstance().start(r)
r.done.connect(
lambda: (

View File

@@ -1,3 +1,5 @@
import contextlib
import subprocess
from shutil import which
import structlog
@@ -5,9 +7,7 @@ from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import QMessageBox
from tagstudio.core.palette import ColorType, UiColor, get_ui_color
from tagstudio.qt.helpers.vendored.ffmpeg import FFMPEG_CMD, FFPROBE_CMD
from tagstudio.qt.translations import Translations
logger = structlog.get_logger(__name__)
@@ -20,11 +20,10 @@ class FfmpegChecker(QMessageBox):
def __init__(self):
super().__init__()
ffmpeg = "FFmpeg"
ffprobe = "FFprobe"
title = Translations.format("dependency.missing.title", dependency=ffmpeg)
self.setWindowTitle(title)
self.setWindowTitle("Warning: Missing dependency")
self.setText("Warning: Could not find FFmpeg installation")
self.setIcon(QMessageBox.Icon.Warning)
# Blocks other application interactions until resolved
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setStandardButtons(
@@ -35,19 +34,52 @@ class FfmpegChecker(QMessageBox):
self.setDefaultButton(QMessageBox.StandardButton.Ignore)
# Enables the cancel button but hides it to allow for click X to close dialog
self.button(QMessageBox.StandardButton.Cancel).hide()
self.button(QMessageBox.StandardButton.Help).clicked.connect(
lambda: QDesktopServices.openUrl(QUrl(self.HELP_URL))
)
red = get_ui_color(ColorType.PRIMARY, UiColor.RED)
green = get_ui_color(ColorType.PRIMARY, UiColor.GREEN)
missing = f"<span style='color:{red}'>{Translations['generic.missing']}</span>"
found = f"<span style='color:{green}'>{Translations['about.module.found']}</span>"
status = Translations.format(
"ffmpeg.missing.status",
ffmpeg=ffmpeg,
ffmpeg_status=found if which(FFMPEG_CMD) else missing,
ffprobe=ffprobe,
ffprobe_status=found if which(FFPROBE_CMD) else missing,
)
self.setText(f"{Translations['ffmpeg.missing.description']}<br><br>{status}")
self.ffmpeg = False
self.ffprobe = False
def installed(self):
"""Checks if both FFmpeg and FFprobe are installed and in the PATH."""
if which(FFMPEG_CMD):
self.ffmpeg = True
if which(FFPROBE_CMD):
self.ffprobe = True
logger.info("FFmpeg found: {self.ffmpeg}, FFprobe found: {self.ffprobe}")
return self.ffmpeg and self.ffprobe
def version(self):
"""Checks the version of ffprobe and ffmpeg and returns None if they dont exist."""
version: dict[str, str | None] = {"ffprobe": None, "ffmpeg": None}
self.installed()
if self.ffprobe:
ret = subprocess.run(
[FFPROBE_CMD, "-show_program_version"], shell=False, capture_output=True, text=True
)
if ret.returncode == 0:
with contextlib.suppress(Exception):
version["ffprobe"] = ret.stdout.split("\n")[1].replace("-", "=").split("=")[1]
if self.ffmpeg:
ret = subprocess.run(
[FFMPEG_CMD, "-version"], shell=False, capture_output=True, text=True
)
if ret.returncode == 0:
with contextlib.suppress(Exception):
version["ffmpeg"] = ret.stdout.replace("-", " ").split(" ")[2]
return version
def show_warning(self):
"""Displays the warning to the user and awaits response."""
missing = "FFmpeg"
# If ffmpeg is installed but not ffprobe
if not self.ffprobe and self.ffmpeg:
missing = "FFprobe"
self.setText(f"Warning: Could not find {missing} installation")
self.setInformativeText(f"{missing} is required for multimedia thumbnails and playback")
# Shows the dialog
selection = self.exec()
# Selection will either be QMessageBox.Help or (QMessageBox.Ignore | QMessageBox.Cancel)
if selection == QMessageBox.StandardButton.Help:
QDesktopServices.openUrl(QUrl(self.HELP_URL))

View File

@@ -0,0 +1,112 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QComboBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QStyledItemDelegate,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from tagstudio.core.enums import LibraryPrefs
from tagstudio.core.library.alchemy.library import Library
from tagstudio.qt.translations import Translations
from tagstudio.qt.widgets.panel import PanelWidget
class FileExtensionItemDelegate(QStyledItemDelegate):
def setModelData(self, editor, model, index): # noqa: N802
if isinstance(editor, QLineEdit) and editor.text() and not editor.text().startswith("."):
editor.setText(f".{editor.text()}")
super().setModelData(editor, model, index)
class FileExtensionModal(PanelWidget):
done = Signal()
def __init__(self, library: "Library"):
super().__init__()
# Initialize Modal =====================================================
self.lib = library
self.setWindowTitle(Translations["ignore_list.title"])
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setMinimumSize(240, 400)
self.root_layout = QVBoxLayout(self)
self.root_layout.setContentsMargins(6, 6, 6, 6)
# Create Table Widget --------------------------------------------------
self.table = QTableWidget(len(self.lib.prefs(LibraryPrefs.EXTENSION_LIST)), 1)
self.table.horizontalHeader().setVisible(False)
self.table.verticalHeader().setVisible(False)
self.table.horizontalHeader().setStretchLastSection(True)
self.table.setItemDelegate(FileExtensionItemDelegate())
# Create "Add Button" Widget -------------------------------------------
self.add_button = QPushButton(Translations["ignore_list.add_extension"])
self.add_button.clicked.connect(self.add_item)
self.add_button.setDefault(True)
self.add_button.setMinimumWidth(100)
# Create Mode Widgets --------------------------------------------------
self.mode_widget = QWidget()
self.mode_layout = QHBoxLayout(self.mode_widget)
self.mode_layout.setContentsMargins(0, 0, 0, 0)
self.mode_layout.setSpacing(12)
self.mode_label = QLabel(Translations["ignore_list.mode.label"])
self.mode_combobox = QComboBox()
self.mode_combobox.setEditable(False)
self.mode_combobox.addItem("")
self.mode_combobox.addItem("")
self.mode_combobox.setItemText(0, Translations["ignore_list.mode.include"])
self.mode_combobox.setItemText(1, Translations["ignore_list.mode.exclude"])
is_exclude_list = int(bool(self.lib.prefs(LibraryPrefs.IS_EXCLUDE_LIST)))
self.mode_combobox.setCurrentIndex(is_exclude_list)
self.mode_combobox.currentIndexChanged.connect(lambda i: self.update_list_mode(i))
self.mode_layout.addWidget(self.mode_label)
self.mode_layout.addWidget(self.mode_combobox)
self.mode_layout.setStretch(1, 1)
# Add Widgets To Layout ------------------------------------------------
self.root_layout.addWidget(self.mode_widget)
self.root_layout.addWidget(self.table)
self.root_layout.addWidget(self.add_button, alignment=Qt.AlignmentFlag.AlignCenter)
# Finalize Modal -------------------------------------------------------
self.refresh_list()
def update_list_mode(self, mode: int):
"""Update the mode of the extension list: "Exclude" or "Include".
Args:
mode (int): The list mode, given by the index of the mode inside
the mode combobox. 1 for "Exclude", 0 for "Include".
"""
self.lib.set_prefs(LibraryPrefs.IS_EXCLUDE_LIST, bool(mode))
def refresh_list(self):
for i, ext in enumerate(self.lib.prefs(LibraryPrefs.EXTENSION_LIST)):
self.table.setItem(i, 0, QTableWidgetItem(ext))
def add_item(self):
self.table.insertRow(self.table.rowCount())
def save(self):
extensions = []
for i in range(self.table.rowCount()):
ext = self.table.item(i, 0)
if ext and ext.text().strip():
extensions.append(ext.text().strip().lstrip(".").lower())
# save preference
self.lib.set_prefs(LibraryPrefs.EXTENSION_LIST, extensions)

View File

@@ -18,7 +18,7 @@ from PySide6.QtWidgets import (
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.utils.dupe_files import DupeRegistry
from tagstudio.qt.modals.mirror_entries_modal import MirrorEntriesModal
from tagstudio.qt.modals.mirror_entities import MirrorEntriesModal
from tagstudio.qt.translations import Translations
# Only import for type checking/autocompletion, will not be imported at runtime.
@@ -26,7 +26,6 @@ if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
# TODO: Break up into MVC classes, similar to fix_ignored_modal
class FixDupeFilesModal(QWidget):
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__()

View File

@@ -10,10 +10,10 @@ from PySide6.QtCore import Qt
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.utils.unlinked_registry import UnlinkedRegistry
from tagstudio.core.utils.missing_files import MissingRegistry
from tagstudio.qt.modals.delete_unlinked import DeleteUnlinkedEntriesModal
from tagstudio.qt.modals.merge_dupe_entries import MergeDuplicateEntries
from tagstudio.qt.modals.relink_entries_modal import RelinkUnlinkedEntries
from tagstudio.qt.modals.remove_unlinked_modal import RemoveUnlinkedEntriesModal
from tagstudio.qt.modals.relink_unlinked import RelinkUnlinkedEntries
from tagstudio.qt.translations import Translations
from tagstudio.qt.widgets.progress import ProgressWidget
@@ -22,16 +22,15 @@ if TYPE_CHECKING:
from tagstudio.qt.ts_qt import QtDriver
# TODO: Break up into MVC classes, similar to fix_ignored_modal
class FixUnlinkedEntriesModal(QWidget):
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__()
self.lib = library
self.driver = driver
self.tracker = UnlinkedRegistry(lib=self.lib)
self.tracker = MissingRegistry(library=self.lib)
self.unlinked_count = -1
self.missing_count = -1
self.dupe_count = -1
self.setWindowTitle(Translations["entries.unlinked.title"])
self.setWindowModality(Qt.WindowModality.ApplicationModal)
@@ -44,16 +43,18 @@ class FixUnlinkedEntriesModal(QWidget):
self.unlinked_desc_widget.setWordWrap(True)
self.unlinked_desc_widget.setStyleSheet("text-align:left;")
self.unlinked_count_label = QLabel()
self.unlinked_count_label.setObjectName("unlinkedCountLabel")
self.unlinked_count_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.missing_count_label = QLabel()
self.missing_count_label.setObjectName("missingCountLabel")
self.missing_count_label.setStyleSheet("font-weight:bold;font-size:14px;")
self.missing_count_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.dupe_count_label = QLabel()
self.dupe_count_label.setObjectName("dupeCountLabel")
self.dupe_count_label.setStyleSheet("font-weight:bold;font-size:14px;")
self.dupe_count_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.refresh_unlinked_button = QPushButton(Translations["entries.generic.refresh_alt"])
self.refresh_unlinked_button.clicked.connect(self.refresh_unlinked)
self.refresh_unlinked_button = QPushButton(Translations["entries.unlinked.refresh_all"])
self.refresh_unlinked_button.clicked.connect(self.refresh_missing_files)
self.merge_class = MergeDuplicateEntries(self.lib, self.driver)
self.relink_class = RelinkUnlinkedEntries(self.tracker)
@@ -62,8 +63,8 @@ class FixUnlinkedEntriesModal(QWidget):
self.relink_class.done.connect(
# refresh the grid
lambda: (
self.driver.update_browsing_state(),
self.refresh_unlinked(),
self.driver.filter_items(),
self.refresh_missing_files(),
)
)
self.search_button.clicked.connect(self.relink_class.repair_entries)
@@ -71,17 +72,16 @@ class FixUnlinkedEntriesModal(QWidget):
self.manual_button = QPushButton(Translations["entries.unlinked.relink.manual"])
self.manual_button.setHidden(True)
self.remove_button = QPushButton(Translations["entries.unlinked.remove_alt"])
self.remove_modal = RemoveUnlinkedEntriesModal(self.driver, self.tracker)
self.remove_modal.done.connect(
self.delete_button = QPushButton(Translations["entries.unlinked.delete_alt"])
self.delete_modal = DeleteUnlinkedEntriesModal(self.driver, self.tracker)
self.delete_modal.done.connect(
lambda: (
self.set_unlinked_count(),
self.set_missing_count(),
# refresh the grid
self.driver.update_browsing_state(),
self.refresh_unlinked(),
self.driver.filter_items(),
)
)
self.remove_button.clicked.connect(self.remove_modal.show)
self.delete_button.clicked.connect(self.delete_modal.show)
self.button_container = QWidget()
self.button_layout = QHBoxLayout(self.button_container)
@@ -93,19 +93,19 @@ class FixUnlinkedEntriesModal(QWidget):
self.done_button.clicked.connect(self.hide)
self.button_layout.addWidget(self.done_button)
self.root_layout.addWidget(self.unlinked_count_label)
self.root_layout.addWidget(self.missing_count_label)
self.root_layout.addWidget(self.unlinked_desc_widget)
self.root_layout.addWidget(self.refresh_unlinked_button)
self.root_layout.addWidget(self.search_button)
self.root_layout.addWidget(self.manual_button)
self.root_layout.addWidget(self.remove_button)
self.root_layout.addWidget(self.delete_button)
self.root_layout.addStretch(1)
self.root_layout.addStretch(2)
self.root_layout.addWidget(self.button_container)
self.update_unlinked_count()
self.set_missing_count(self.missing_count)
def refresh_unlinked(self):
def refresh_missing_files(self):
pw = ProgressWidget(
cancel_button_text=None,
minimum=0,
@@ -114,47 +114,30 @@ class FixUnlinkedEntriesModal(QWidget):
pw.setWindowTitle(Translations["library.scan_library.title"])
pw.update_label(Translations["entries.unlinked.scanning"])
def update_driver_widgets():
if (
hasattr(self.driver, "library_info_window")
and self.driver.library_info_window.isVisible()
):
self.driver.library_info_window.update_cleanup()
pw.from_iterable_function(
self.tracker.refresh_unlinked_files,
self.tracker.refresh_missing_files,
None,
self.set_unlinked_count,
self.update_unlinked_count,
self.remove_modal.refresh_list,
update_driver_widgets,
self.set_missing_count,
self.delete_modal.refresh_list,
)
def set_unlinked_count(self):
"""Sets the unlinked_entries_count in the Library to the tracker's value."""
self.lib.unlinked_entries_count = self.tracker.unlinked_entries_count
def set_missing_count(self, count: int | None = None):
if count is not None:
self.missing_count = count
else:
self.missing_count = self.tracker.missing_file_entries_count
def update_unlinked_count(self):
"""Updates the UI to reflect the Library's current unlinked_entries_count."""
# Indicates that the library is new compared to the last update.
# NOTE: Make sure set_unlinked_count() is called before this!
if self.tracker.unlinked_entries_count > 0 and self.lib.unlinked_entries_count < 0:
self.tracker.reset()
count: int = self.lib.unlinked_entries_count
self.search_button.setDisabled(count < 1)
self.remove_button.setDisabled(count < 1)
count_text: str = Translations.format(
"entries.unlinked.unlinked_count", count=count if count >= 0 else ""
)
self.unlinked_count_label.setText(f"<h3>{count_text}</h3>")
@override
def showEvent(self, event: QtGui.QShowEvent) -> None:
self.update_unlinked_count()
return super().showEvent(event)
if self.missing_count < 0:
self.search_button.setDisabled(True)
self.delete_button.setDisabled(True)
self.missing_count_label.setText(Translations["entries.unlinked.missing_count.none"])
else:
# disable buttons if there are no files to fix
self.search_button.setDisabled(self.missing_count == 0)
self.delete_button.setDisabled(self.missing_count == 0)
self.missing_count_label.setText(
Translations.format("entries.unlinked.missing_count.some", count=self.missing_count)
)
@override
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: # noqa N802

View File

@@ -26,7 +26,6 @@ from tagstudio.core.library.alchemy.enums import TagColorEnum
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Tag
from tagstudio.core.palette import ColorType, get_tag_color
from tagstudio.core.utils.types import unwrap
from tagstudio.qt.flowlayout import FlowLayout
from tagstudio.qt.translations import Translations
@@ -45,14 +44,14 @@ class BranchData:
def add_folders_to_tree(library: Library, tree: BranchData, items: tuple[str, ...]) -> BranchData:
branch = tree
parent_tag = None
for folder in items:
if folder not in branch.dirs:
new_tag = Tag(name=folder, parent_tags=({parent_tag} if parent_tag else None))
# TODO: Reimplement parent tags
new_tag = Tag(name=folder)
library.add_tag(new_tag)
branch.dirs[folder] = BranchData(tag=new_tag)
branch.tag = new_tag
branch = branch.dirs[folder]
parent_tag = branch.tag
return branch
@@ -71,8 +70,8 @@ def folders_to_tags(library: Library):
reversed_tag = reverse_tag(library, tag, None)
add_tag_to_tree(reversed_tag)
for entry in library.all_entries():
folders = entry.path.parts[0:-1]
for entry in library.get_entries():
folders = entry.path.parts[1:-1]
if not folders:
continue
@@ -91,10 +90,9 @@ def reverse_tag(library: Library, tag: Tag, items: list[Tag] | None) -> list[Tag
items.reverse()
return items
parent_tag = None # to avoid subtag unbound error
for parent_tag_id in tag.parent_ids:
parent_tag = library.get_tag(parent_tag_id)
return reverse_tag(library, unwrap(parent_tag), items)
for subtag_id in tag.parent_ids:
subtag = library.get_tag(subtag_id)
return reverse_tag(library, subtag, items)
# =========== UI ===========
@@ -125,8 +123,8 @@ def generate_preview_data(library: Library) -> BranchData:
reversed_tag = reverse_tag(library, tag, None)
add_tag_to_tree(reversed_tag)
for entry in library.all_entries():
folders = entry.path.parts[0:-1]
for entry in library.get_entries():
folders = entry.path.parts[1:-1]
if not folders:
continue
@@ -134,7 +132,7 @@ def generate_preview_data(library: Library) -> BranchData:
if branch:
has_tag = False
for tag in entry.tags:
if branch.tag and tag.name == branch.tag.name:
if tag.name == branch.tag.name:
has_tag = True
break
if not has_tag:
@@ -218,21 +216,20 @@ class FoldersToTagsModal(QWidget):
self.apply_button.setMinimumWidth(100)
self.apply_button.clicked.connect(self.on_apply)
self.showEvent = self.on_open # type: ignore
self.root_layout.addWidget(self.title_widget)
self.root_layout.addWidget(self.desc_widget)
self.root_layout.addWidget(self.open_close_button_w)
self.root_layout.addWidget(self.scroll_area)
self.root_layout.addWidget(self.apply_button, alignment=Qt.AlignmentFlag.AlignCenter)
def on_apply(self):
def on_apply(self, event):
folders_to_tags(self.library)
self.close()
self.driver.main_window.preview_panel.set_selection(
self.driver.selected, update_preview=False
)
self.driver.preview_panel.update_widgets(update_preview=False)
@override
def showEvent(self, event: QtGui.QShowEvent):
def on_open(self, event):
for i in reversed(range(self.scroll_layout.count())):
self.scroll_layout.itemAt(i).widget().setParent(None)
@@ -274,7 +271,7 @@ class TreeItem(QWidget):
self.label = QLabel()
self.tag_layout.addWidget(self.label)
self.tag_widget = ModifiedTagWidget(unwrap(data.tag), unwrap(parent_tag))
self.tag_widget = ModifiedTagWidget(data.tag, parent_tag)
self.tag_widget.bg_button.clicked.connect(lambda: self.hide_show())
self.tag_layout.addWidget(self.tag_widget)
@@ -326,7 +323,10 @@ class ModifiedTagWidget(QWidget):
self.bg_button = QPushButton(self)
self.bg_button.setFlat(True)
text = f"{tag.name} ({parent_tag.name})".replace("&", "&&")
if parent_tag is not None:
text = f"{tag.name} ({parent_tag.name})".replace("&", "&&")
else:
text = tag.name.replace("&", "&&")
self.bg_button.setText(text)
self.bg_button.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)

View File

@@ -87,7 +87,7 @@ class MirrorEntriesModal(QWidget):
pw.from_iterable_function(
self.mirror_entries_runnable,
displayed_text,
lambda s=self.driver.selected: self.driver.main_window.preview_panel.set_selection(s),
self.driver.preview_panel.update_widgets,
self.done.emit,
)

Some files were not shown because too many files have changed in this diff Show More