Compare commits

...

108 Commits

Author SHA1 Message Date
Travis Abendshien
50fc325d80 chore: bump version to v9.4.2 2024-12-01 12:57:04 -08:00
Travis Abendshien
140645943c feat: create auto-backup of library for use in save failures (Fix #343) (#554)
* fix: move `self.to_json()` outside `with` block

* feat: add library autosave on start

* fix: check if `backup_folder` exists before loading backup
2024-11-04 12:20:14 -08:00
Travis Abendshien
2fc0dd03aa ui: increase thumbnail edge contrast 2024-09-13 17:39:46 -07:00
Travis Abendshien
90b9af48e3 chore: bump version to v9.4.1 2024-09-13 17:31:49 -07:00
Sean Krueger
b2dbc5722b feat(ui): warn user if FFmpeg not installed (#441)
* feat: Warn user if FFmpeg is not installed

Creates a Warning dialog on startup if the program cannot find FFmpeg or
FFprobe in the PATH. Other interactions with the program are blocked
until the issue is either ignore or resolved.

* docs: Add FFmpeg installation guide

* ruff formatting

* chore: Cleanup missing logic and warning message

* chore: Remove custom icon

Per QT docs, handling custom iconPixmap requires multiple icons per
platform. Easier to just use universal, default warning icon (yellow
triangle)

* fix: Ignore dialog with X button

* fix: Move startup checks after CI

* chore: Unreverse install check logic

* doc: Improve docs formatting

* docs: Point help url to new docs sites

* Remove ffmpeg docs page

* Use which from python stdlib
2024-09-13 17:25:09 -07:00
Travis Abendshien
6490cc905d feat: increase file scanning performance (#486)
* feat: increase file scanning performance

* fix: correct typo in comment

* refactor: use `continue` in place of nested `ifs`
2024-09-12 14:52:27 -07:00
Sean Krueger
dfa4079b23 fix(ui): retain filter on directory refresh (#483)
* fix(QtDriver): Retain filter on directory refresh

* ruff formatting
2024-09-10 01:46:59 -07:00
Travis Abendshien
6ff7303321 fix: use birthtime for default library sorting
The cutoff for how many files get sorted also changes to 150,000.
2024-09-09 12:09:59 -07:00
Travis Abendshien
4d405b5d77 feat: add .raf file to _IMAGE_RAW_SET 2024-09-07 21:45:06 -07:00
Sean Krueger
bf8816f715 fix(ui): use default audio icon if ffmpeg is absent (#471)
* fix(ThumbRenderer): Use audio icon when no ffmpeg

When ffmpeg is missing, Popen raises a FileNotFound error. This would
be caught as an Unlinked file and use the broken file icon. The
exception is now caught and a more appropriate exception is raised in
its place.

* ruff formatting
2024-09-07 20:24:10 -07:00
Sean Krueger
8c9b04d1ec fix(ui): use birthtime for creation time on mac & win (#472)
* fix(PreviewPanel): Use birthtime for creation time

st_ctime does not provide accurate creation time on MacOS, and as of
Python 3.12 is deprecated for Windows. On these two platforms use
st_birthtime, but fall back to st_ctime on linux.

* mypy errors
2024-09-07 20:17:18 -07:00
Travis Abendshien
5995e4d416 feat: add .orf file to _IMAGE_RAW_SET 2024-09-07 00:59:28 -07:00
Sean Krueger
fc714e02e6 fix: Do not create command prompt window on subprocess (#436)
* fix: Do not create command prompt window on subcmd

Patches files from abandoned libraries are located and updated in
src/qt/helpers/vendored with modified sections labeld PATCHED. A wrapper
around subprocess.Popen automatically sets the creation flag to no
window on windows.

* fix: Replace Popen in mediainfo_json decoder

* fixup: Pipe stdin to stdin

* chore: Exclude vendored dir from tooling checks

* suppress mypy warnings
2024-09-02 23:40:52 -07:00
Travis Abendshien
85b6d9decc Merge branch 'main' into Alpha-v9.4 2024-09-02 23:39:39 -07:00
xarvex
3e2fb1282c feat(flake): expose formatter
Fixes: #433
2024-09-03 00:12:03 -05:00
Travis Abendshien
9a78bf3066 feat(ui): show file creation/modified dates + restyle path label (#430)
* feat(ui): show file dates, change path look

* use `os.path.sep`

* refactor: simplify file label cases
2024-09-02 14:30:29 -07:00
Travis Abendshien
1c53f05e4f chore: ensure splash width is int 2024-09-02 00:43:11 -07:00
Travis Abendshien
1e4883c577 fix(ui): scale splash screen with screen width 2024-09-02 00:32:36 -07:00
xarvex
3e950a0cbe fix(direnv)!: gitignore .envrc
A common workflow is to have a local .envrc, allow contributors to do
so. Still provide the recommended Nix-based setup, for those who wish to
use it.
That file can then be copied to or symlinked to `.envrc`.
2024-09-01 21:28:58 -05:00
yed
ca08ce57b6 ui: postpone creating modals (#425) 2024-09-01 16:17:19 -07:00
Travis Abendshien
7f3b3d06af ui: update splash 2024-08-31 23:11:42 -07:00
Travis Abendshien
3d427997ea fix(ui): remove default video border 2024-08-31 22:40:55 -07:00
Travis Abendshien
65237ed106 fix(ui): seek next valid video frame for thumbs 2024-08-31 22:29:19 -07:00
Travis Abendshien
cb12956309 fix(ui): deleting files will not reset search 2024-08-31 21:32:00 -07:00
Travis Abendshien
cc2e9f97c4 ui: increase thumbnail edge contrast 2024-08-31 21:14:24 -07:00
Travis Abendshien
81ddf5366c fix(ui): unlinked videos use correct icon 2024-08-31 20:52:19 -07:00
Travis Abendshien
8219ffc416 feat: expanded file deletion/trashing (#409)
* feat: send deleted files to system trash

This refactors the file deletion code to send files to the system trash instead of performing a hard deletion. It also fixes deleting video files and GIFs loaded in the Preview Panel.

* feat(ui): add file deletion confirmation boxes

* feat(ui): add delete file menu option + shortcut

* ui: update file deletion message boxes

* fix(ui): same default confirm button on win/mac

- Make "Yes" the default choice in the delete file modal for both Windows and macOS (Linux untested)
- Change status messages to be more broad, since they also are displayed when cancelling the operation

* ui: show perm deletion warning on all platforms
2024-08-31 17:26:24 -07:00
Jann Stute
85d62e6519 fix: gdl sidecar files load properly
* fix: run_macro didn't work for files that aren't in a sub directory

* fix: add_generic_data_to_entry would add a new Content Tags Field if the Content Tags field was the first field

* fix: get_gdl_sidecar used wrong file extension for discovering gdl side car files

* run_macro: ensure that source folder parameter is case insensitive

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

---------

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-08-31 17:17:29 -07:00
EJ Stinson
341aa92ecb feat(ui): preview support for source engine files
* Fix text and RAW image handling

- Fix RAW images not being loaded correctly in the preview panel
- Fix trying to read size data from null images
- Refactor `os.stat` to `<Path object>.stat()`
- Remove unnecessary upper/lower conversions
- Improve encoding compatibility beyond UTF-8 when reading text files
- Code cleanup

* Use chardet for character encoding detection

* Add support for waveform + album cover thumbnails

* Rename "cover" variables for MyPy

* Rename "audio_tags" variables for MyPy + typing

* Add # type: ignore to fromstring method

* Add GIF preview support

* Add rough check for invalid video codecs

* Add ".plist" to PLAINTEXT_TYPES

* Add readable video tester

* Add ".psd" to IMAGE_TYPES; Handle ID3NoHeaderError

* Improve and style waveform previews

* Add final return statement to _album_artwork()

* Add final return statement to _audio_waveform()

* Tweak waveform color and size

* Fix ItemThumb label text color in light mode

* Fix most theme UI legibility issues

* Match additional UI to color scheme

* ruff format

* feat(ui): add UI color palette dict

* feat(ui) center and color small font previews

* fix(ui): large font previews follow app theme

* fix(ui): blender previews follow app theme

* feat(ui): add resizable thumbnail options

* fix: mkv files with "[0][0][0][0]" codec load properly

* fix: missing audio files properly handled

* feat(ui): use system accent color for thumb selections

* fix(ui): hide gif preview in multi-selections

* feat(ui): add dynamic file thumb icons

* fix(ui): hide previous thumbnail before resizing

* (fix): catch ffmpeg errors in file tester

* Squashed commit of the following:

commit 9a3c19d398
Author: Travis Abendshien <lvnvtravis@gmail.com>
Date:   Wed Jul 24 22:57:32 2024 -0700

    fix: add missing comma + sort extensions

commit 53b2db9b5f
Author: Travis Abendshien <lvnvtravis@gmail.com>
Date:   Wed Jul 24 14:46:16 2024 -0700

    refactor: move type constants to new media classes

* feat(ui): add media types and icon resources

* feat(ui): add more default media types and icons

Add additional default icons for:
- Blender
- Presentation
- Program
- Spreadsheet
Add/expand additional media types:
- PDF
- Packages

* fix: remove leading dot in preview panel ext

* refactor: remove edge from `four_corner_gradient()`

* fix: handle missing files in `resource_manager`

* fix(ui): thumb edges fading on refresh

* feat(ui): add default icons for audio+vector thumbs

* feat(ui): apply edge to default icon thumbs

* chore: remove unused code

* refactor(ui): move loading icon to `ResourceManager`

* added support for Source 1 + 2 file thumbnails 

All plaintext variants and VTF file conversions.

* Added render code for VTF files

Added support for VTF files by using the vtf2img library for PIL

* Add files via upload

* fixed Ruff errors

* fixed Ruff errors

* chore: organize imports, lists; ruff formatting

* Change references of Source to Source Engine

* Added error handler + changed source to source engine

* add struct to import and docstring for source_engine

* complying to the demigod ruff

* chore: format with ruff

---------

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-08-31 17:15:33 -07:00
SupKittyMeow
dcb8ded987 ui: "open in explorer" action follows os name (#370)
* Update item_thumb.py

* Update preview_panel.py

* Update video_player.py

* made it so preview_panel.py uses self.open_explorer_action instead of just normal open_explorer_action
2024-08-31 16:47:26 -07:00
Travis Abendshien
569390ea72 fix: correct behavior for tag widget search options (#398)
* fix(tags): include cluster in tag_id search

* fix(ui): remove unused tag context menu item

Remove unused "Add to Search" context menu item for tag widgets.

* fix(ui): add tag search from tag_database

Add missing functionality for the "Search for Tag" context menu option + left click functionality inside `tag_database.py` aka the "Tag Manager" panel.

* fix: verify `tag_id:` input in search

* style: remove commented code

* fix: change `Library` import to type check only
2024-08-31 13:11:54 -07:00
Travis Abendshien
4590226bca feat(ui): expanded thumbnail and preview features (#390)
* Fix text and RAW image handling

- Fix RAW images not being loaded correctly in the preview panel
- Fix trying to read size data from null images
- Refactor `os.stat` to `<Path object>.stat()`
- Remove unnecessary upper/lower conversions
- Improve encoding compatibility beyond UTF-8 when reading text files
- Code cleanup

* Use chardet for character encoding detection

* Add support for waveform + album cover thumbnails

* Rename "cover" variables for MyPy

* Rename "audio_tags" variables for MyPy + typing

* Add # type: ignore to fromstring method

* Add GIF preview support

* Add rough check for invalid video codecs

* Add ".plist" to PLAINTEXT_TYPES

* Add readable video tester

* Add ".psd" to IMAGE_TYPES; Handle ID3NoHeaderError

* Improve and style waveform previews

* Add final return statement to _album_artwork()

* Add final return statement to _audio_waveform()

* Tweak waveform color and size

* Fix ItemThumb label text color in light mode

* Fix most theme UI legibility issues

* Match additional UI to color scheme

* ruff format

* feat(ui): add UI color palette dict

* feat(ui) center and color small font previews

* fix(ui): large font previews follow app theme

* fix(ui): blender previews follow app theme

* feat(ui): add resizable thumbnail options

* fix: mkv files with "[0][0][0][0]" codec load properly

* fix: missing audio files properly handled

* feat(ui): use system accent color for thumb selections

* fix(ui): hide gif preview in multi-selections

* feat(ui): add dynamic file thumb icons

* fix(ui): hide previous thumbnail before resizing

* (fix): catch ffmpeg errors in file tester

* Squashed commit of the following:

commit 9a3c19d398
Author: Travis Abendshien <lvnvtravis@gmail.com>
Date:   Wed Jul 24 22:57:32 2024 -0700

    fix: add missing comma + sort extensions

commit 53b2db9b5f
Author: Travis Abendshien <lvnvtravis@gmail.com>
Date:   Wed Jul 24 14:46:16 2024 -0700

    refactor: move type constants to new media classes

* feat(ui): add media types and icon resources

* feat(ui): add more default media types and icons

Add additional default icons for:
- Blender
- Presentation
- Program
- Spreadsheet
Add/expand additional media types:
- PDF
- Packages

* fix: remove leading dot in preview panel ext

* refactor: remove edge from `four_corner_gradient()`

* fix: handle missing files in `resource_manager`

* fix(ui): thumb edges fading on refresh

* feat(ui): add default icons for audio+vector thumbs

* feat(ui): apply edge to default icon thumbs

* chore: remove unused code

* refactor(ui): move loading icon to `ResourceManager`

* fix(ui) color for default icons follow theme

* fix: remove `theme_color` redef

* refactor: make some consts and args clearer

* refactor: organize arguments, update docstrings

The ability to pass a border radius scaling argument is also included.

* chore: format docstrings with ruff

* refactor: replace magic numbers with named values

* refactor: remove unused code, comments, & imports

* refactor: rename args to not shadow builtins

* refactor: remove unused vars from `thumb_renderer`

* fix: handle ValueError in `render()`

Handle ValueErrors in `render()`. This case was encountered when attempting to render an `XPM` file during testing.

* docs: add FFmpeg requirement to README
2024-08-31 13:08:27 -07:00
Tobias Berger
d8ef54392b fix(dupes): fix duplicate file matching (#410)
chore: remove constant newline printing in file matching
2024-08-31 12:42:19 -07:00
Travis Abendshien
41087b14c6 Merge branch 'main' into Alpha-v9.4 2024-08-31 12:29:17 -07:00
xarvex
38626ac690 chore(direnv): update .envrc
- Cleanup direnv-root file
- Set filetype for vi-like editors
- Format and lint according to shellcheck and shfmt
2024-08-31 13:16:30 -05:00
xarvex
bc38e568fa feat(flake): remove impurity, update nix-direnv
Use path as an input that can be overriden automatically when direnv is
in use.
nix-direnv version present in .envrc has been updated, using watch_file on the flake is already handled.
2024-08-30 14:44:22 -05:00
Florian Zier
4b35df0924 fix(flake): GPU hardware acceleration
* Enable hardware acceleration for Nix devenv

Section "nativeBuildInputs" needs the dependency "qt6.full" to provide hardware acceleration in QT.
Library "wayland" is needed to create a proper OpenGL context under Wayland as well.

Provide a check for open AMD driver and use it for VDPAU video hardware acceleration.

Move "wrapQtAppsHook" to it's correct place under "nativeBuildInputs".

* Add xorg.libXrandr for hardware accelerated video playback.

Using libva and openssl libraries eliminates the need for a dependency on the qt6.full library.
2024-08-29 23:49:00 -05:00
xarvex
750cbf0f9c fix(flake): add missing media dependencies
Fixes: #417

Did not opt for setting VDPAU_DRIVER, should be done on user side
See: https://wiki.archlinux.org/title/Hardware_video_acceleration#Configuring_VA-API
2024-08-29 19:38:23 -05:00
Björn Out
5ac40f5b11 Add the ability to create tags when adding a tag to a file (#262)
* Add the ability to create tags when adding a tag to a file.

* ui: unify tag widget appearance

Unify the tag widget appearance and remove unnecessary "*1" multiplication.

* refactor: change some var names & add docstrings

* feat: edit panel is opened before adding tag

* feat(ui): focus save button on add panel

Focus the save button on the Add Tag panel. This allows the user to promptly hit enter to add the tag as-is.

---------

Co-authored-by: bjorn-out <b.g.out@uva.nl>
Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-08-27 21:59:21 -07:00
Travis Abendshien
fda6077b20 chore: bump version to v9.4.0 2024-08-25 17:11:57 -07:00
xarvex
cb4798b715 feat(flake): complete revamp with devenv/direnv
Not perfect, and mostly a port of the previous edition. Hours have
already been sunk into this, and need to get this out for consumption,
and for ironing out.
For more information see: https://devenv.sh

NOTE: impure is used only because of the devenv-managed state, do not be
alarmed!
2024-08-24 22:57:00 -05:00
Travis Abendshien
c51f9869b2 Merge branch 'main' into Alpha-v9.4 2024-08-24 17:28:57 -07:00
Xarvex
e1b1ef9888 Merge pull request #229 from seakrueger/flake-setup-venv
ci(flake): create and activate venv via Nix Flake
2024-08-22 20:09:24 -05:00
UnusualEgg
3fcf6022b9 refactor: combine open launch args (#364)
Combine the `--open` and `-o` launch arguments into a single argument option.
2024-08-22 18:02:03 -07:00
Travis Abendshien
938832505b Merge branch 'main' into Alpha-v9.4 2024-08-21 00:41:10 -07:00
Travis Abendshien
b107fb5809 refactor: move type constants to new media classes (#331)
* refactor: move type constants to new media classes

* fix: add missing comma + sort extensions
2024-08-20 23:31:31 -07:00
Travis Abendshien
ec960f2372 (fix): use .get() to avoid KeyError (#347) 2024-08-11 19:01:08 -07:00
Sam
30b60a0d31 feat(ui): sort tags in add tag panel by color/alphabetical (close #327) (#329)
* Implement #327

Sort tags in the Library Tags panel and the Add Parent Tags panel with Archived and Favorite at the top, then sort by color, and then sort alphabetically.

* Sort tags alphabetically when a search is performed

* Format with Ruff

* Prioritize tags whose names match the query over tags that match the query in other ways
2024-07-29 16:56:14 -07:00
Sam
ce87b11fbd Fix #2 for Add Library Tags panel (#328)
The "Add Tags" panel displays all tags when no search has been performed. Modifies the "Add Library Tags panel" to be the same.
2024-07-22 06:59:43 -07:00
Theasacraft
e463635cc0 Add font thumbnail preview support (#307)
* Add font thumbnail preview support

* Add multiple font sizes to thumbnail

* Ruff reformat

* Ruff reformat

* Added Metadata to info

* Change the way thumbnails are structured

* Small performance improvement

* changed Metadata display structure

* added copyright notice to added file

* fix(ui): dynamically scale font previews; add .woff2, .ttc

---------

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-07-19 07:22:15 -07:00
Creepler13
aa0aad4300 Copy and Paste + Shortcuts (#79)
* Fixed merge conflicts

* fixed format?

* Improve readability (Apply suggestions from code review)

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* bug fix: Copy last selected not first

* Fix copy entanglement; Fix paste overwriting

* Change multi-selection copy to merge data

- Multi-selection copy now merges fields of all selected entries
- Action states are now handled

---------

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>
Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-07-18 23:33:52 -07:00
yed
bebca634de use list widget for selecting fields to add (#134)
* use list widget for selecting fields to add

* fix(ui): allow list widget resizing
2024-07-18 21:40:17 -07:00
Travis Abendshien
92a6e1130c Merge branch 'main' into Alpha-v9.4 2024-07-18 18:23:16 -07:00
Travis Abendshien
c79086f715 Fix collation data not clearing on library close 2024-07-04 17:40:19 -07:00
Travis Abendshien
9ce07bd369 Bump version to 9.3.2 2024-07-03 17:41:21 -07:00
Theasacraft
33ee27a84f Fix small bug (#306) 2024-07-03 17:02:59 -07:00
Ethnogeny
883354b263 Blender thumbnail support (#273)
* Update thumb_renderer.py

Included support for rendering blender thumbnails

* Add files via upload

Add functions that get the thumbnail's data

* Update thumb_renderer.py

* Update blender_thumbnailer.py

* Update thumb_renderer.py

* Update thumb_renderer.py

Changed where imports are according to feedback

* Update thumb_renderer.py

Changed blender thumbnail function name to reduce ambiguity

* Update blender_thumbnailer.py

Updated function name

* Update blender_thumbnailer.py

* Update blender_thumbnailer.py

Ruff format

* Update thumb_renderer.py

Ruff format

* Update constants.py

Add .blend1, 2, 3 etc file support

* Update blender_thumbnailer.py

Refactor to follow requested changes

* Update thumb_renderer.py

More refactoring

* Update blender_thumbnailer.py

Ruff format

* Update thumb_renderer.py

Ruff format
2024-07-03 16:50:59 -07:00
Travis Abendshien
6862f89d1a Merge branch 'main' into Alpha-v9.4 2024-07-03 16:47:16 -07:00
Travis Abendshien
1204d2b7b5 Fix search ignoring case of extension list 2024-06-21 11:28:12 -07:00
Sean Krueger
15ee13c7b4 Bump Qt6 version to 6.7.1 2024-06-17 13:05:17 -05:00
Xarvex
49ad8117ef fix(flake): resolve mypy access to libraries 2024-06-17 13:05:17 -05:00
Sean Krueger
4f193613de Update Contributing documentation for dev on Nix
Moves the previous updated blurb from the README to the new CONTRIBUTING
file. Also reworks some wording to link to the Flake nix wiki page for
nix users who haven't enable flakes yet.
2024-06-17 13:05:17 -05:00
Sean Krueger
31038711f2 Install ruff via nixpkgs 2024-06-17 13:05:17 -05:00
Sean Krueger
cc827108ef Add xcb as fallback when wayland fails to load
Mostly as a fallback for xserver.
2024-06-17 13:05:17 -05:00
Sean Krueger
9fec4822c1 Setup and activate virtual environment via flake
When using the nix flake to generate a development shell, the python
virtual environment will now automatically be created and dependecies
from both requirements.txt and requirements-dev.txt will be installed.
This removes the need for using the setup script after entering the
dev shell. Exec bash must be the last thing called, as any other
commands past it will not get executed by the shell hook. Also removes
some duplicate dependencies that I found.
2024-06-17 13:05:17 -05:00
Travis Abendshien
501ab1f977 Update issue templates to ask for title 2024-06-16 19:54:56 -07:00
Theasacraft
b3c01e180a Update to pyside6 version 6.7.1 (#223)
* Update to pyside6.7.1

* Fix Ruff

* Fix MyPy

* Update mypy job to also use PySide6 6.7.1

* Remove unused imports

* Add Description to class

* Ruff format

* Fix Warning in pagination.py

* Probably fix Pyside app test

* Rename CustomQPushButton to QPushButtonWrapper
also renamed custom_qbutton.py to qbutton_wrapper.py
2024-06-16 16:53:38 -07:00
Jiri
4c6ebec529 refactoring: centralize field IDs (#157)
* use enum with named fields instead of ad-hoc numbers

* move tag ids into constants file
2024-06-16 14:24:48 -07:00
Travis Abendshien
5c25666e67 Fix TypeError in folders_to_tags.py
- Additionally use proper comparison syntax
2024-06-15 13:19:28 -07:00
Lennart S
fae65bd9e9 docs: Fixed broken markdown doc link (#291) 2024-06-15 13:10:55 -07:00
Jiri
8e065ca8ac create testing library files ad-hoc (#292) 2024-06-14 10:11:00 -07:00
Hayden Andreyka
888b674f05 fix: backslashes in f-string error on file drop dupe widget (#289)
* fix: python complaining about backslashes inside f-string expressions
refactor excessively long f-string into separate variables

* fix: missing f on f-string

* Format with Ruff
2024-06-13 18:34:44 -07:00
Travis Abendshien
82946cb0b8 Update CONTRIBUTING.md with PyTest info 2024-06-13 15:39:13 -07:00
Jiri
aa2925cde0 add pytest to CI pipeline (#286) 2024-06-13 15:29:22 -07:00
Creepler13
e5a0e5aa9b Drag and drop files in and out of TagStudio (#153)
* Ability to drop local files in to TagStudio to add to library

* Added renaming option to drop import

* Improved readability and switched to pathLib

* format

* Apply suggestions from code review

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* Revert Change

* Update tagstudio/src/qt/modals/drop_import.py

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* Added support for folders

* formatting

* Progress bars added

* Added Ability to Drag out of window

* f

* format

* Ability to drop local files in to TagStudio to add to library

* Added renaming option to drop import

* Improved readability and switched to pathLib

* format

* Apply suggestions from code review

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* Revert Change

* Update tagstudio/src/qt/modals/drop_import.py

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* Added support for folders

* formatting

* Progress bars added

* Added Ability to Drag out of window

* f

* format

* format

* formatting and refactor

* format again

* formatting for mypy

* convert lambda to func for clarity

* mypy fixes

* fixed dragout only worked on selected

* Refactor typo, Add license

* Reformat QMessageBox

* Disable drops when no library is open

---------

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>
Co-authored-by: Travis Abendshien <lvnvtravis@gmail.com>
2024-06-13 10:59:10 -07:00
Travis Abendshien
5bc80a043f Update tagstudio.spec 2024-06-13 09:17:14 -07:00
Travis Abendshien
65d88b9987 Refactor video_player.py (Fix #270) (#274)
* Refactor video_player.py

- Move icons files to qt/images folder, some being renamed
- Reduce icon loading to single initial import
- Tweak icon dimensions and animation timings
- Remove unnecessary commented code
- Remove unused/duplicate imports
- Add license info to file

* Add basic ResourceManager, use in video_player.py

* Revert tagstudio.spec changes

* Change tuple usage to dicts

* Move ResourceManager initialization steps

* Fix errant list notation
2024-06-12 23:20:17 -07:00
Travis Abendshien
37ff35fcf6 Set mouse event transparency on ItemThumbs (#279) 2024-06-12 02:00:16 -07:00
Xarvex
9b13e338bb Use bug report and feature request forms for issues (#277)
* Initial bug report

* Images can be attached in description

* Enclose label in quotes

* Wikis are no longer being used

* Use footnote to clarify what is up-to-date

* Footnotes not supported in checklist

* Initial feature request form

* Fixup grammar/wording
2024-06-11 19:32:18 -07:00
Travis Abendshien
a47b0adb6e Update icon.ico 2024-06-11 17:29:30 -07:00
Travis Abendshien
9f39bf6fdc Update README: Correct version number in figure 2024-06-11 01:27:21 -07:00
Andrew Arneson
e375166bfe Raise error if video file has 0 frames or is in valid. (#275)
video.get(cv2.CAP_PROP_FRAME_COUNT) returns 0 or -1
2024-06-10 18:10:57 -07:00
Sean Krueger
7054ffd227 Separately pin QT nixpkg version (#244)
* Add missing libraries for video player

* Pin qt6 package version to 6.6.3

Currently, this succesfully launches the program. Pinning qt seperatly
allows the rest of unstable nixpkgs to be updated even after the qt
package version has been bumped. This fixes vim failing to launch in the
nix shell because of a bad gcc version. Bumping the package version to
qt6.7.1 also will require bumping PySide to 6.7.1, otherwise it will
fail to find qt. Qt 6.7.1 nixpkg commit is 47da0aee5616a063015f10ea593688646f2377e4

* fixup: Pin Qtcreator also

QtCreator was still against nixpkgs not the specific qt variant.
2024-06-10 14:52:13 -07:00
Travis Abendshien
6d283d1f2d Add CONTRIBUTING.md, update README 2024-06-10 02:30:16 -07:00
Travis Abendshien
a0baf015db Bump version to v9.3.1 Pre-Release 2024-06-08 15:34:29 -07:00
Travis Abendshien
58be4cdb4b Bump version to v9.3.0 2024-06-08 15:21:37 -07:00
Travis Abendshien
08761d5f8a Add Landing Page When No Library Is Opened (#258)
* Add landing page when no library is open

- Add landing page when no library is open
- Add linear_gradient method
- Reformat main_window.py with spaces instead of tabs because apparently it wasn't formatted already?

* Add color_overlay methods, ClickableLabel widget

- Add color_overlay helper methods
- Add clickable_label widget
- Add docstrings to landing.py methods
- Add logo easter egg
- Refactor landing.py content

* Fix redefinition

* Fix macOS shortcut text
2024-06-08 15:18:40 -07:00
Travis Abendshien
6a680ad3d1 Increase shown tag limit from 29 to 100 (#227) 2024-06-08 12:40:37 -07:00
PencilVoid
b5ec3598e1 Add "Clear Selection" button (#259)
* Add "Clear Selection" button

* Change clear select keybind to Esc
2024-06-08 10:51:39 -07:00
Theasacraft
926dfffebe Add option to use a allowed extensions instead of ignored extensions (#251)
* Add option to use a whitelist instead of a blacklist

* maybe fix mypy?

* Fix Mypy and rename ignored_extensions

* This should fix mypy

* Update checkbox text

* Update window title

* shorten if statment and update text

* update variable names

* Fix Mypy

* hopefully fix mypy

* Fix mypy

* deprecate ignored_extensions

Co-authored-by: Jiri <yedpodtrzitko@users.noreply.github.com>

* polishing

* polishing

* Fix mypy

* finishing touches

Co-authored-by: Jiri <yedpodtrzitko@users.noreply.github.com>

* Fix boolean loading

* UI/UX + ext list loading tweaks

- Change extension list mode setting from Checkbox to ComboBox to help better convey its purpose
- Change and simplify wording
- Add type hints to extension variables and change loading to use `get()` with default values
- Sanitize older extension lists that don't use extensions with a leading "."
- Misc. code organization and docstrings

---------

Co-authored-by: Jiri <yedpodtrzitko@users.noreply.github.com>
Co-authored-by: Travis Abendshien <lvnvtravis@gmail.com>
2024-06-07 18:02:28 -07:00
Xarvex
461906c349 Workflows: attempt fix for mismatched hashes in pip and bump MacOS version (#255)
* Attempted fix at mismatched hashes
Due to the seemingly random nature of the bug, this cannot be tested

* macos-11 runner has been deprecated, bump to 12
2024-06-06 12:51:08 -07:00
Travis Abendshien
2dc5197fbd Add upcoming feature documentation 2024-06-04 15:59:39 -07:00
PossiblePanda
11f0c7f9b8 Added various file formats to constants.py (#231)
* Added various file formats to constants.py

* Update tagstudio/src/core/constants.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/core/constants.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

---------

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>
2024-06-04 14:13:57 -07:00
Andrew Arneson
fb445e6ab0 Fix Default Ignored File Extension (#245)
Add item delegate for Ignored File Extension to add leading `.` if left off extension
2024-06-03 21:47:56 -07:00
Giochino Danilo Ramos Silva
6e96a0ff61 Multi mode search system (#232)
* multi search mode system

A way to change the search from requiring all tags to and of the tags

* better wording

* Update start_win.bat

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Fix home_ui.py using PySide6 instead of PyQt5

* Refresh search on mode change

* Search mode selections naming fix

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* converted SearchMode from constants to enums
2024-06-03 15:37:56 -07:00
Travis Abendshien
c75aff4db3 Rename "Subtags" to "Parent Tags"
Mentioned change in #211
2024-06-03 13:30:15 -07:00
Travis Abendshien
84a4b2f0cf Merge pull request #240 from Loran425/bugfix/cancel_library_dialog
Bugfix Open Library Dialog
2024-06-02 22:54:51 -07:00
Andrew Arneson
10b90dcc74 Bugfix for recent library re-creating a library at the last library location. (#238)
* Prevent Automatic opening of a Library if the ".TagStudio" folder has been deleted.
If the library no longer has a `.TagStudio` folder clear the Last_Library value

* Add disabling recent libraries that are missing or have missing `.TagStudio` folders

* Fix bug where this would crash if an empty library was passed

* Grabbed the wrong color
2024-06-02 22:53:42 -07:00
Andrew Arneson
2d89df620e Fix Open Library Dialog
Resolve issues where the open library dialog will try to open `.` if no path is returned from the dialog
2024-06-02 22:43:10 -06:00
Travis Abendshien
0646508c24 Fix Raw Image Handling and Improve Text File Encoding Compatibility (#233)
* Fix text and RAW image handling

- Fix RAW images not being loaded correctly in the preview panel
- Fix trying to read size data from null images
- Refactor `os.stat` to `<Path object>.stat()`
- Remove unnecessary upper/lower conversions
- Improve encoding compatibility beyond UTF-8 when reading text files
- Code cleanup

* Use chardet for character encoding detection
2024-06-02 20:18:40 -07:00
Travis Abendshien
0137ed5be8 Update README.md 2024-06-01 21:09:55 -07:00
Theasacraft
779a251c09 Fix small bugs (#228) 2024-05-31 16:45:13 -07:00
Travis Abendshien
868b553670 Duplicate Entry Handling (Fixes #179) (#204)
* Reapply "Add duplicate entry handling (Fix #179)"

This reverts commit 66ec0913b6.

* Reapply "Fix create library + type checks"

This reverts commit 57e27bb51f.

* Type and hint changes

* Remove object cast

* MyPy wrestling

* Remove type: ignore, change __eq__ cast

- Remove `type: ignore` comments from `Entry`'s `__eq__` method
- Change the cast in this method from `__value = cast(Self, object)` to `__value = cast(Self, __value)`

Co-Authored-By: Jiri <yedpodtrzitko@users.noreply.github.com>

* Fix formatting + mypy

---------

Co-authored-by: Jiri <yedpodtrzitko@users.noreply.github.com>
2024-05-29 15:47:37 -07:00
DrRetro
9f630fe315 Video Player (#149)
* Basic Video Player

* Fixes and Comments

* Fixed Bug Where Video's Audio did not stop when switching to a Image.

* Redo on VideoPlayer. Now with rounded corners.

* Fixed size not being correct when first starting video player.

* Ruff Check Fix

* Fixed Sizing Issue, and added Autoplay option in right click menu.

* Autoplay Toggle and Fixed Issue with video not stoping after closing library.

* Ruff Format

* Suggested Changes Done

* Commented out useless code that cause first warning.

* Fixed Album Art Error

* Might have found solution to Autoplay Inconsistency

* Ruff Format

* Finally Fixed Autoplay Inconsistency

* Fixed Merge Conficts

* Requested Changes and Ruff Format

* Test for new check

* Fix for PySide App Test

* More typing fixes and a few other changes.

* Ruff Format

* MyPy Fix

* MyPy Fix

* Ruff Format

* MyPy Fix

* MyPy and Ruff Fix

* Code Clean-Up and Requests completed.

* Conflict Fixes

* MyPy Fix

* Confict Fix

It appears one of the commits from main fixed the autoplay issue.
2024-05-29 13:58:09 -07:00
Icosahunter
6798ffd0a7 Replace use of os.path with pathlib (#156)
* Replace usage of os.path with usage of pathlib.Path in ts_cli.py

* Replace use of os.path with pathlib in Library.py

* Replace use of os.path with pathlib in ts_core.py

* resolve entry path/filename on creation/update

* Fix errors and bugs related to move from os.path to pathlib.

* Remove most uses of '.resolve()' as it didn't do what I thought it did

* Fix filtering in refresh directories to not need to cast to string.

* Some work on ts_qt, thumbnails don't load...

* Fixed the thumbnail issue, things seem to be working.

* Fix some bugs

* Replace some isfile with is_file ts_cli.py

* Update tagstudio/src/core/library.py

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>

* Update library.py

* Update library.py

* Update library.py

* Update ts_cli.py

* Update library.py

* Update ts_qt

* Fix path display in delete unlinked entries modal

* Ruff formatting

* Builds and opens/creates library now

* Fix errors

* Fix ruff and mypy issues (hopefully)

* Fixed some things, broke some things

* Fixed the thumbnails not working

* Fix some new os.path instances in qt files

* Fix MyPy issues

* Fix ruff and mypy issues

* Fix some issues

* Update tagstudio/src/qt/widgets/preview_panel.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/qt/widgets/preview_panel.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/qt/widgets/preview_panel.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/qt/widgets/preview_panel.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/qt/widgets/thumb_renderer.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Update tagstudio/src/qt/widgets/thumb_renderer.py

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

* Fix refresh_dupe_files issue

* Ruff format

* Tweak filepaths

- Suffix comparisons are now case-insensitive
- Restore original thumbnail extension label behavior
- Fix preview panel trying to read file size from missing files

---------

Co-authored-by: yed podtrzitko <yedpodtrzitko@users.noreply.github.com>
Co-authored-by: Travis Abendshien <lvnvtravis@gmail.com>
2024-05-26 16:17:05 -07:00
Jiri
2e8678414b feat: add select all hotkey (#217)
* add select all hotkey

* add item to selected
2024-05-26 01:00:56 -07:00
Gawi
e1cd46d010 Wiki/Docs Updates (#194)
* split file + link fix

* Cleanup & Minimum Fill

* polish & link

* Update doc/Tag.md

Co-authored-by: Travis Abendshien <46939827+CyanVoxel@users.noreply.github.com>

---------
2024-05-25 13:49:12 -07:00
Travis Abendshien
9879697c95 Bump version to v9.2.2 2024-05-23 00:42:00 -07:00
128 changed files with 34187 additions and 16904 deletions

16
.envrc.recommended Normal file
View File

@@ -0,0 +1,16 @@
# vi: ft=bash
#
# 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.5; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.5/direnvrc" "sha256-RuwIS+QKFj/T9M2TFXScjBsLR6V3A17YVoEW/Q6AZ1w="
fi
devenv_root_file="$(mktemp -t devenv-root-XXXXXXXX)"
printf %s "${PWD}" >"${devenv_root_file}"
if ! use flake . --override-input devenv-root "file+file://${devenv_root_file}"; then
printf '%s\n' "devenv could not be built. The devenv environment was not loaded. Make the necessary changes to devenv.nix and hit enter to try again." >&2
fi
rm "${devenv_root_file}"
unset devenv_root_file

64
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
name: Bug Report
description: File a bug or issue report.
title: '[Bug]: '
labels: ['Type: Bug']
body:
- type: markdown
attributes:
value: |
*Please add an appropriate title for this issue.*
Before reporting, read the [documentation](https://github.com/TagStudioDev/TagStudio/blob/main/doc/index.md) and search existing [issues](https://github.com/TagStudioDev/TagStudio/issues).
Validate that you are using an up-to-date version[^1], your issue might already be fixed!
Questions, guidance, and usage goes in [discussions](https://github.com/TagStudioDev/TagStudio/discussions). Invalid issues will be closed.
[^1]: This can mean latest release, pre-release, or git commit.
- type: checkboxes
attributes:
label: Checklist
description: Make sure you've checked (and actually did) all of the below.
options:
- label: I am using an up-to-date version.
required: true
- label: I have read the [documentation](https://github.com/TagStudioDev/TagStudio/blob/main/doc/index.md).
required: true
- label: I have searched existing [issues](https://github.com/TagStudioDev/TagStudio/issues).
required: true
- type: input
attributes:
label: TagStudio Version
placeholder: Alpha 9.1.0
validations:
required: true
- type: input
attributes:
label: Operating System & Version
placeholder: TagOS 3.14
validations:
required: true
- type: textarea
attributes:
label: Description
description: Clear and concise description of the problem. Attach screenshots if needed, and include any errors you see.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: Clear and concise description of what you think should happen.
validations:
required: true
- type: textarea
attributes:
label: Steps to Reproduce
description: Minimal steps neded for the problem to occur.
placeholder: |
1.
2.
3.
validations:
required: true
- type: textarea
attributes:
label: Logs
description: Provide any logs, if applicable.

View File

@@ -0,0 +1,40 @@
name: Feature Request
description: Suggest a new feature.
title: '[Feature Request]: '
labels: ['Type: Enhancement']
body:
- type: markdown
attributes:
value: |
*Please add an appropriate title for this feature request.*
Before suggesting, read the [documentation](https://github.com/TagStudioDev/TagStudio/blob/main/doc/index.md) and search existing [issues](https://github.com/TagStudioDev/TagStudio/issues).
Validate that you are using an up-to-date version[^1], your feature might already be implemented!
Questions, guidance, and usage goes in [discussions](https://github.com/TagStudioDev/TagStudio/discussions). Invalid issues will be closed.
[^1]: This can mean latest release, pre-release, or git commit.
- type: checkboxes
attributes:
label: Checklist
description: Make sure you've checked (and actually did) all of the below.
options:
- label: I am using an up-to-date version.
required: true
- label: I have read the [documentation](https://github.com/TagStudioDev/TagStudio/blob/main/doc/index.md).
required: true
- label: I have searched existing [issues](https://github.com/TagStudioDev/TagStudio/issues).
required: true
- type: textarea
attributes:
label: Description
description: Clear and concise description of the problem or missing capability. Attach screenshots if needed, and explain your own use case.
validations:
required: true
- type: textarea
attributes:
label: Solution
description: Clear and concise description of what you think should happen.
- type: textarea
attributes:
label: Alternatives
description: Any considered alternative solutions or workarounds. If undesirable, why?

View File

@@ -32,11 +32,13 @@ jobs:
libxcb-render-util0 \
libxcb-xinerama0 \
libopengl0 \
libxcb-cursor0
libxcb-cursor0 \
libpulse0 \
ffmpeg
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -Ur requirements.txt
- name: Run TagStudio app and check exit code
run: |

View File

@@ -16,11 +16,13 @@ jobs:
with:
reviewdog_version: latest
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
# pyside 6.6.3 has some issue in their .pyi files
pip install PySide6==6.6.2
pip install -r requirements.txt
pip install mypy==1.10.0
mkdir tagstudio/.mypy_cache

22
.github/workflows/pytest.yaml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: pytest
on: [push, pull_request]
jobs:
pytest:
name: Run tests
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install -r requirements-dev.txt
- name: Run tests
run: |
pytest tagstudio/tests/

View File

@@ -23,6 +23,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install -Ur requirements.txt pyinstaller
- run: pyinstaller tagstudio.spec -- ${{ matrix.build-flag }}
- run: tar czfC dist/tagstudio_linux_x86_64${{ matrix.suffix }}.tar.gz dist tagstudio
@@ -34,20 +35,22 @@ jobs:
macos:
strategy:
matrix:
os-version: ['11', '14']
os-version: ['12', '14']
include:
- os-version: '11'
- os-version: '12'
arch: x86_64
- os-version: '14'
arch: aarch64
runs-on: macos-${{ matrix.os-version }}
env:
# even though we run on 12, target towards compatibility
MACOSX_DEPLOYMENT_TARGET: '11.0'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install -Ur requirements.txt pyinstaller
- run: pyinstaller tagstudio.spec
- run: tar czfC dist/tagstudio_macos_${{ matrix.arch }}.tar.gz dist TagStudio.app
@@ -75,6 +78,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install -Ur requirements.txt pyinstaller
- run: PyInstaller tagstudio.spec -- ${{ matrix.build-flag }}
- run: Compress-Archive -Path dist/TagStudio${{ matrix.file-end }} -DestinationPath dist/tagstudio_windows_x86_64${{ matrix.suffix }}.zip

5
.gitignore vendored
View File

@@ -55,6 +55,7 @@ coverage.xml
.hypothesis/
.pytest_cache/
cover/
tagstudio/tests/fixtures/library/*
# Translations
*.mo
@@ -252,3 +253,7 @@ compile_commands.json
.TagStudio
TagStudio.ini
# End of https://www.toptal.com/developers/gitignore/api/visualstudiocode,python,qt
.envrc
.direnv
.devenv

170
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,170 @@
# Contributing to TagStudio
_Last Updated: June 10th, 2024_
Thank you so much for showing interest in contributing to TagStudio! Here are a set of instructions and guidelines for contributing code or documentation to the project. This document will change over time, so make sure that your contributions still line up with the requirements here before submitting a pull request.
## Getting Started
- Check the [Planned Features](https://github.com/TagStudioDev/TagStudio/blob/main/doc/updates/planned_features.md) page, [FAQ](/README.md/#faq), as well as the open [Issues](https://github.com/TagStudioDev/TagStudio/issues) and [Pull Requests](https://github.com/TagStudioDev/TagStudio/pulls).
- If you'd like to add a feature that isn't on the roadmap or doesn't have an open issue, **PLEASE create a feature request** issue for it discussing your intentions so any feedback or important information can be given by the team first.
- We don't want you wasting time developing a feature or making a change that can't/won't be added for any reason ranging from pre-existing refactors to design philosophy differences.
### Contribution Checklist
- I've read the [Planned Features](https://github.com/TagStudioDev/TagStudio/blob/main/doc/updates/planned_features.md) page
- I've read the [FAQ](/README.md/#faq), including the "[Features I Likely Won't Add/Pull](/README.md/#features-i-likely-wont-addpull)" section
- I've checked the open [Issues](https://github.com/TagStudioDev/TagStudio/issues) and [Pull Requests](https://github.com/TagStudioDev/TagStudio/pulls)
- **I've created a new issue for my feature _before_ starting work on it**, or have at least notified others in the relevant existing issue(s) of my intention to work on it
- I've set up my development environment including Ruff and Mypy
- I've read the [Code Guidelines](#code-guidelines) and/or [Documentation Guidelines](#documentation-guidelines)
- **_I mean it, I've found or created a new issue for my feature!_**
## Creating a Development Environment
### Prerequisites
- [Python](https://www.python.org/downloads/) 3.12
- [Ruff](https://github.com/astral-sh/ruff) (Included in `requirements-dev.txt`)
- [Mypy](https://github.com/python/mypy) (Included in `requirements-dev.txt`)
- [PyTest](https://docs.pytest.org) (Included in `requirements-dev.txt`)
### Creating a Python Virtual Environment
If you wish to launch the source version of TagStudio outside of your IDE:
> [!IMPORTANT]
> Depending on your system, Python may be called `python`, `py`, `python3`, or `py3`. These instructions use the alias `python3` for consistency. You can check to see which alias your system uses and if it's for the correct Python version by typing `python3 --version` (or whichever alias) into your terminal.
> [!TIP]
> On Linux and macOS, you can launch the `tagstudio.sh` script to skip the following process, minus the `requirements-dev.txt` installation step. _Using the script is fine if you just want to launch the program from source._
1. In the root repository directory, create a python virtual environment:
`python3 -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`
3. Install the required packages:
- `pip install -r requirements.txt`
- If developing (includes Ruff and Mypy): `pip install -r requirements-dev.txt`
_Learn more about setting up a virtual environment [here](https://docs.python.org/3/tutorial/venv.html)._
### Manually Launching (Outside of an IDE)
- **Windows** (start_win.bat)
- To launch TagStudio, launch the `start_win.bat` file. You can modify this .bat file or create a shortcut and add one or more additional arguments if desired.
- **Linux/macOS** (TagStudio.sh)
- Run the "TagStudio.sh" script and the program should launch! (Make sure that the script is marked as executable if on Linux). Note that launching from the script from outside of a terminal will not launch a terminal window with any debug or crash information. If you wish to see this information, just launch the shell script directly from your terminal with `./TagStudio.sh`.
- **NixOS** (Nix Flake)
> [!WARNING]
> Support for NixOS is still a work in progress.
- Use the provided [Flake](https://nixos.wiki/wiki/Flakes) to create and enter a working environment by running `nix develop`. Then, run the program via `python3 tagstudio/tag_studio.py` from the root directory.
- **Any** (No Scripts)
- Alternatively, with the virtual environment loaded, run the python file at `tagstudio\tag_studio.py` from your terminal. If you're in the project's root directory, simply run `python3 tagstudio/tag_studio.py`.
## Workflow Checks
When pushing your code, several automated workflows will check it against predefined tests and style checks. It's _highly recommended_ that you run these checks locally beforehand to avoid having to fight back-and-forth with the workflow checks inside your pull requests.
> [!TIP]
> To format the code automatically before each commit, there's a configured action available for the `pre-commit` hook. Install it by running `pre-commit install`. The hook will be executed each time on running `git commit`.
### [Ruff](https://github.com/astral-sh/ruff)
A Python linter and code formatter. Ruff uses the `pyproject.toml` as its config file and runs whenever code is pushed or pulled into the project.
#### Running Locally
- Lint code with by moving into the `/tagstudio` directory with `cd tagstudio` and running `ruff --config ../pyproject.toml`.
- Format code with `ruff format` inside the repository directory
Ruff is also available as a VS Code [extension](https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff), PyCharm [plugin](https://plugins.jetbrains.com/plugin/20574-ruff), and [more](https://docs.astral.sh/ruff/integrations/).
### [Mypy](https://github.com/python/mypy)
Mypy is a static type checker for Python. It sure has a lot to say sometimes, but we recommend you take its advice when possible. Mypy also uses the `pyproject.toml` as its config file and runs whenever code is pushed or pulled into the project.
#### Running Locally
- **First time only:** Move into the `/tagstudio` directory with `cd tagstudio` and run the following:
- `mkdir -p .mypy_cache`
- `mypy --install-types --non-interactive`
- Check code by moving into the `/tagstudio` directory with `cd tagstudio` _(if you aren't already inside)_ and running `mypy --config-file ../pyproject.toml .`. _(Don't forget the `.` at the end!)_
> [!CAUTION]
> There's a known issue between PySide v6.6.3 and Mypy where Mypy will detect issues with the `.pyi` files inside of PySide and prematurely stop checking files. This issue is not present in PySide v6.6.2, which _should_ be compatible with everything else if you wish to try using that version in the meantime.
Mypy is also available as a VS Code [extension](https://marketplace.visualstudio.com/items?itemName=matangover.mypy), PyCharm [plugin](https://plugins.jetbrains.com/plugin/11086-mypy), and [more](https://plugins.jetbrains.com/plugin/11086-mypy).
### PyTest
- Run all tests by moving into the `/tagstudio` directory with `cd tagstudio` and running `pytest tests/`.
## Code Guidelines
### 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.
- Try to keep a maximum column with of no more than **100** characters.
- Code comments should be used to help describe sections of code that don'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 (in newly created python files).
- When writing text for window titles, form titles, or dropdown options, 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/)!
> [!WARNING]
> Column width limits, docstring formatting, and import sorting aren't currently checked in the Ruff workflow but likely will be in the near future.
### Implementations
- Avoid direct calls to `os`
- Use `Pathlib` library instead of `os.path`
- Use `sys.platform` instead of `os.name`
- Don't prepend local imports with `tagstudio`, stick to `src`
- Use `logging` instead of `print` statements
- Avoid nested `f-string`s
#### Runtime
- Code must function on supported versions of Windows, macOS, and Linux:
- Windows: 10, 11
- macOS: 12.0+
- Linux: TBD
- Avoid use of unnecessary logging statements in final submitted code.
- Code should not cause unreasonable slowdowns to the program outside of a progress-indicated task.
#### Git/GitHub Specifics
- Use clear and concise commit messages. If your commit does too much, either consider breaking it up into smaller commits or providing extra detail in the commit description.
- Use imperative-style present-tense commit messages. Examples:
- "Add feature foo"
- "Change method bar"
- "Fix function foobar"
- Pull Requests should have an adequate title and description which clearly outline your intentions and changes/additions. Feel free to provide screenshots, GIFs, or videos, especially for UI changes.
## Documentation Guidelines
Documentation contributions include anything inside of the `doc/` folder, as well as the `README.md` and `CONTRIBUTING.md` files.
- Use "[snake_case](https://developer.mozilla.org/en-US/docs/Glossary/Snake_case)" for file and folder names
- Follow the folder structure pattern
- Don't add images or other media with excessively large file sizes
- Provide alt text for all embedded media
- Use "[Title Case](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case)" for title capitalization
## Translation Guidelines
_TBA_

View File

@@ -10,15 +10,18 @@
TagStudio is a photo & file organization application with an underlying 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.
<p align="center">
<img width="80%" src="screenshot.jpg">
</p>
<figure align="center">
<img width="80%" src="screenshot.jpg" alt="TagStudio Screenshot" align="center">
<figcaption><i>TagStudio Alpha v9.1.0 running on Windows 10.</i></figcaption>
</figure>
## Contents
- [Goals](#goals)
- [Priorities](#priorities)
- [Current Features](#current-features)
- [Contributing](#contributing)
- [Installation](#installation)
- [Usage](#usage)
- [FAQ](#faq)
@@ -50,13 +53,19 @@ TagStudio is a photo & file organization application with an underlying system t
- Special search conditions for entries that are: `untagged`/`no tags` and `empty`/`no fields`.
> [!NOTE]
> For more information on the project itself, please see the [FAQ](#faq) section and other docs.
> For more information on the project itself, please see the [FAQ](#faq) section as well as the [documentation](/doc/index.md).
## Contributing
If you're interested in contributing to TagStudio, please take a look at the [contribution guidelines](/CONTRIBUTING.md) for how to get started!
## Installation
To download TagStudio, visit the [Releases](https://github.com/TagStudioDev/TagStudio/releases) section of the GitHub repository and download the latest release for your system. TagStudio is available for **Windows**, **macOS** _(Apple Silicon & Intel)_, and **Linux**. Windows and Linux builds are also available in portable versions if you want a more self-contained executable to move around.
To download TagStudio, visit the [Releases](https://github.com/TagStudioDev/TagStudio/releases) section of the GitHub repository and download the latest release for your system under the "Assets" section. TagStudio is available for **Windows**, **macOS** _(Apple Silicon & Intel)_, and **Linux**. Windows and Linux builds are also available in portable versions if you want a more self-contained executable to move around.
> [!NOTE]
For video thumbnails and playback, you'll also need [FFmpeg](https://ffmpeg.org/download.html) installed on your system.
> [!IMPORTANT]
> 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.
#### Optional Arguments
@@ -67,7 +76,7 @@ Optional arguments to pass to the program.
> Path to a TagStudio Library folder to open on start.
> `--config-file <path>` / `-c <path>`
> Path to a TagStudio Library folder to open on start.
> Path to the TagStudio config file to load.
## Usage
@@ -112,9 +121,6 @@ To create a new tag, click on Edit -> New Tag from the menu bar. From there, ent
To edit a tag, right-click the tag in the tag field of the preview pane and select “Edit Tag”
> [!WARNING]
> There is currently no method to view all tags that youve created in your library. This is a top priority for future releases.
### Relinking Renamed/Moved Files
Inevitably, some of the files inside your library will be renamed, moved, or deleted. If a file has been renamed or moved, TagStudio will display the thumbnail as a red tag with a cross through it _(this icon is also used for items with broken thumbnails)._ To relink moved files or delete these entries, go to Tools -> Manage Unlinked Entries. Click the “Refresh” button to scan your library for unlinked entries. Once complete, you can attempt to “Search & Relink” any unlinked entries to their respective files, or “Delete Unlinked Entries” in the event the original files have been deleted and you no longer wish to keep their metadata entries inside your library.
@@ -143,7 +149,7 @@ Load in a .dupeguru file generated by [dupeGuru](https://github.com/arsenetar/du
Create an image collage of your photos and videos.
> [!CAUTION]
> Collage sizes and options are hardcoded.
> Collage sizes and options are hardcoded, and there's no GUI indicating the process of the collage creation.
#### Macros
@@ -159,64 +165,21 @@ Import JSON sidecar data generated by [gallery-dl](https://github.com/mikf/galle
> [!CAUTION]
> This feature is not supported or documented in any official capacity whatsoever. It will likely be rolled-in to a larger and more generalized sidecar importing feature in the future.
## Creating a Development Environment
## Launching/Building From Source
If you're interested in contributing to TagStudio or just wish to poke around the live codebase, here are instructions for setting up the Python project.
### Prerequisites
- Python 3.12
### Creating a Python Virtual Environment
> [!NOTE]
> Depending on your system, Python may be called `python`, `py`, `python3`, or `py3`. These instructions use the alias `python3`. You can check to see which alias you system uses and if it's for the correct Python version by typing `python3 --version` (or whichever alias) into your terminal.
_Skip these steps if launching from the .sh script on Linux/macOS._
1. In the root repository directory, create a python virtual environment:
`python3 -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`
3. Install the required packages:
- required to run the app: `pip install -r requirements.txt`
- required to develop: `pip install -r requirements-dev.txt`
To run all the tests use `python -m pytest tests/` from the `tagstudio` folder.
_Learn more about setting up a virtual environment [here](https://docs.python.org/3/tutorial/venv.html)._
### Launching Development Environment
- **Windows** (start_win.bat)
- To launch TagStudio, launch the `start_win.bat` file. You can modify this .bat file or create a shortcut and add one or more additional arguments if desired.
- **Linux/macOS** (TagStudio.sh)
- Run the "TagStudio.sh" script, and the program should launch! (Make sure that the script is marked as executable if on Linux). Note that launching from the script from outside of a terminal will not launch a terminal window with any debug or crash information. If you wish to see this information, just launch the shell script directly from your terminal with `./TagStudio.sh`.
- **NixOS** (TagStudio.sh)
- Use the provided `flake.nix` file to create and enter a working environment by running `nix develop`. Then, run the `TagStudio.sh` script.
- **Any** (No Scripts)
- Alternatively, with the virtual environment loaded, run the python file at `tagstudio\tag_studio.py` from your terminal. If you're in the project's root directory, simply run `python3 tagstudio/tag_studio.py`.
See instructions in the "[Creating Development Environment](/CONTRIBUTING.md/#creating-a-development-environment)" section from the [contribution documentation](/CONTRIBUTING.md).
## FAQ
### What State Is the Project Currently In?
As of writing (Alpha v9.2.0) the project is in a useable state, however it lacks proper testing and quality of life features.
As of writing (Alpha v9.3.0) the project is in a useable state, however it lacks proper testing and quality of life features.
### What Features Are You Planning on Adding?
> [!IMPORTANT]
> See the [Planned Features](/doc/updates/planned_features.md) documentation for the latest feature lists. The lists here are currently being migrated over there with individual pages for larger features.
Of the several features I have planned for the project, these are broken up into “priority” features and “future” features. Priority features were originally intended for the first public release, however are currently absent from the Alpha v9.x.x builds.
#### Priority Features
@@ -281,18 +244,3 @@ Ive been developing this project over several years in private, and have gone
### Wait, Is There a CLI Version?
As of right now, **no**. However, I _did_ have a CLI version in the recent past before dedicating my efforts to the Qt GUI version. Ive left in the currently-inoperable CLI code just in case anyone was curious about it. Also yes, its just a bunch of glorified print statements (_the outlook for some form of curses on Windows didnt look great at the time, and I just needed a driver for the newly refactored code...)._
### Can I Contribute?
**Yes!!** I recommend taking a look at the [Priority Features](#priority-features), [Future Features](#future-features), and [Features I Won't Pull](#features-i-likely-wont-addpull) lists, as well as the project issues to see whats currently being worked on. Please do not submit pull requests with new feature additions without opening up an issue with a feature request first.
Code formatting is automatically checked via [Ruff](https://docs.astral.sh/ruff/).
To format the code manually, install ruff via `pip install -r requirements-dev.txt` and then run `ruff format`
To format the code automatically before each commit, there's a configured action available for `pre-commit` hook. Install it by running `pre-commit install`. The hook will be executed each time on running `git commit`.
More structured documentation on contribution requirements is on its way, but for now:
- Use `pathlib` in favor of `os.path`
- Try to make new UI additions match the existing style of the application

BIN
doc/assets/db_schema.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@@ -1,189 +0,0 @@
# TagStudio Documentation (Alpha v9.1.0)
## _A User-Focused Document Management System_
> [!WARNING]
> This documentation is still a work in progress, and is intended to aide with deconstructing and understanding of the core mechanics of TagStudio and how it operates.
## Contents
- [Library](#library)
- [Fields](#fields)
- [Entries](#entries)
- [Tags](#tags)
- [Retrieving Entries](#retrieving-entries-based-on-tag-cluster)
- [Missing File Resolution](#missing-file-resolution)
## Library
The Library is how TagStudio represents your chosen directory. In this Library or Vault system, all files within this directory are represented by Entries, which then contain metadata Fields. All TagStudio data for a Library is stored within a `.TagStudio` folder at the root of the Library's directory. Internal Library objects include:
- Fields (v9+)
- Text Line (Title, Author, Artist, URL)
- Text Box (Description, Notes)
- Tag Box (Tags, Content Tags, Meta Tags)
- Datetime (Date Created, Date Modified, Date Taken) [WIP]
- Collation (Collation) [WIP]
- `name: str`: Collation Name
- `page: int`: Page #
- Checkbox (Archive, Favorite) [WIP]
- Drop Down (Group of Tags to select one from) [WIP]
- Entries (v1+)
- Tags (v7+)
- Macros (v9/10+)
## Fields
Fields are the building blocks of metadata stored in Entires. Fields have several base types for representing different types of information, including:
- `text_line`
- A string of text, displayed as a single line.
- Useful for Titles, Authors, URLs, etc.
- `text_box`
- A long string of text displayed as a box of text.
- Useful for descriptions, notes, etc.
- `datetime` [WIP]
- A date and time value.
- `tag_box`
- A box of tags added by the user.
- Multiple tag boxes can be used to separate classifications of tags, ex. 'Content Tags' and 'Meta Tags'.
- `checkbox` [WIP]
- A two-state checkbox.
- Can be associated with a tag for quick organization.
- `collation` [WIP]
- A collation is a collection of files that are intended to be displayed and retrieved together. Examples may include pages of a book or document that are spread out across several individual files. If you're intention is to associate files across multiple 'collations', use Tags instead!
## Entries
Entries are the representations of your files within the Library. They consist of a reference to the file on your drive, as well as the metadata associated with it.
### Entry Object Structure (v9):
- `id`:
- ID for the Entry.
- Int, Unique, Required
- Used for internal processing
- `filename`:
- The filename with extension of the referenced media file.
- String, Required
- `path`:
- The folder path in which the media file is located in.
- String, Required, OS Agnostic
- `fields`:
- A list of Field ID/Value dicts.
- List of dicts, Optional
NOTE: _Entries currently have several unused optional fields intended for later features._
## Tags
**Tags** are small data objects that represent an attribute of something. A person, place, thing, concept, you name it! Tags in TagStudio allow for more sophisticated Entry organization and searching thanks to their ability to contain alternate names and spellings via `aliases`, relational organization thanks to inherent `subtags`, and more! Tags can be as simple or as powerful as you want to make them, and TagStudio aims to provide as much power to you as possible.
### Tag Object Structure (v9):
- `id`:
- ID for the Tag.
- Int, Unique, Required
- Used for internal processing
- `name`:
- The normal name of the Tag, with no shortening or specification.
- String, Required
- Doesn't have to be unique
- Each word analyzed individually
- Used for display, searching, and storing
- `shorthand`:
- The shorthand name for the Tag.
- String, Optional
- Doesn't have to be unique
- Entire string analyzed as-is
- Used for display and searching
- `aliases`:
- Alternate names for the Tag.
- List of Strings, Optional
- Recommended to be unique to this Tag
- Entire string analyzed as-is
- Used for searching
- `subtags`:
- Other Tags that make up properties of this Tag.
- List of Strings, Optional
- Used for display (first subtag only) and searching.
- `color`:
- A hex code value for customizing the Tag's display color
- String, Optional
- Used for display
### Tag Examples:
#### League of Legends
- `name`: "League of Legends"
- `shorthand`: "LoL"
- `aliases`: ["League"]
- `subtags`: ["Game", "Fantasy"]
#### Arcane
- `name`: "Arcane"
- `shorthand`: ""
- `aliases`: []
- `subtags`: ["League of Legends", "Cartoon"]
#### Jinx (LoL)
- `name`: "Jinx Piltover"
- `shorthand`: "Jinx"
- `aliases`: ["Jinxy", "Jinxy Poo"]
- `subtags`: ["League of Legends", "Arcane", "Character"]
#### Zander (Arcane)
- `name`: "Zander Zanderson"
- `shorthand`: "Zander"
- `aliases`: []
- `subtags`: ["Arcane", "Character"]
#### Mr. Legend (LoL)
- `name`: "Mr. Legend"
- `shorthand`: ""
- `aliases`: []
- `subtags`: ["League of Legends", "Character"]
### Query "League of Legends" returns results for:
- League of Legends [because of "League of Legend"'s name]
- Arcane [because of "Arcane"'s subtag]
- Jinx (LoL) [because of "Jinx Piltover"'s subtag]
- Mr. Legend (LoL) [because of "Mr. Legned (LoL)'s subtag"]
- Zander (Arcane) [because of "Zander Zanderson"'s subtag ("Arcane")'s subtag]
### Query "LoL" returns results for:
- League of Legends [because of "League of Legend"'s shorthand]
- LoL [because of "League of Legend"'s shorthand]
- Arcane [because of "Arcane"'s subtag]
- Jinx (LoL) [because of "Jinx Piltover"'s subtag]
- Mr. Legend (LoL) [because of "Mr. Legned (LoL)'s subtag"]
- Zander (Arcane) [because of "Zander Zanderson"'s subtag ("Arcane")'s subtag]
### Query "Arcane" returns results for:
- Arcane [because of "Arcane"'s name]
- Jinx (LoL) [because of "Jinx Piltover"'s subtag "Arcane"]
- Zander (Arcane) [because of "Zander Zanderson"'s subtag]
## Retrieving Entries based on Tag Cluster
By default when querying Entries, each Entry's `tags` list (stored in the form of Tag `id`s) is compared against the Tag `id`s in a given Tag cluster (list of Tag `id`s) or appended clusters in the case of multi-term queries. The type of comparison depends on the type of query and whether or not it is an inclusive or exclusive query, or a combination of both. This default searching behavior is done in _O(n)_ time, but can be sped up in the future by building indexes on certain search terms. These indexes can be stored on disk and loaded back into memory in future sessions. These indexes will also need to be updated as new Tags and Entries are added or edited.
## Missing File Resolution
1. Refresh missing file list (`refresh missing`) (Automatically run if library has few entries)
2. Fix missing files screen (`fix missing`)
### Fix Missing Files Screen
0. **Match Search** (Determines if entries can be fixed) Scans for filename in library directory
1. **Quick Fixes** (one match found, no existing entry)
2. **Match Selection** (multiple matches found)
3. **Merge Conflict Resolution** (match has existing entry)
Any remaining missing files can be listed, but they probably really are missing at this point. You can update the path and filename to point to new files if you know where they should actually be pointing to.

24
doc/index.md Normal file
View File

@@ -0,0 +1,24 @@
# Welcome to the TagStudio Documentation!
> [!WARNING]
> This documentation is still a work in progress, and is intended to aide with deconstructing and understanding of the core mechanics of TagStudio and how it operates.
<div align="center">
<img src="../github_header.png" alt="TagStudio Alpha" height="100">
<img src="https://i0.wp.com/www.bapl.org/wp-content/uploads/2019/02/old-under-construction-gif.gif" alt="Under Construction" height="100">
</div>
## Table of Contents
- [Library](/doc/library/library.md)
- [Entries](/doc/library/entry.md)
- [Fields](/doc/library/field.md)
- [Tags](/doc/library/tag.md)
- [Tools & Macros](/doc/utilities/macro.md)
- [Planned Features](/doc/updates/planned_features.md)
---
### [Database Migration](/doc/updates/db_migration.md)
The "Database Migration", "DB Migration", or "SQLite Migration" is an upcoming update to TagStudio which will replace the current JSON [library](/doc/library/library.md) with a SQL-based one, and will additionally include some fundamental changes to how some features such as [tags](/doc/library/tag.md) will work.

25
doc/library/entry.md Normal file
View File

@@ -0,0 +1,25 @@
# Entry
Entries are the units that fill a [library](/doc/library/library.md). Each one corresponds to a file, holding a reference to it along with the metadata associated with it.
### Entry Object Structure
1. `id`:
- Int, Unique, **Required**
- The ID for the Entry.
- Used for internal processing
2. `filename`:
- String, **Required**
- The filename with extension of the referenced media file.
3. `path`:
- String, **Required**, OS Agnostic
- The folder path in which the media file is located in.
4. [`fields`](/doc/library/field.md):
- List of dicts, Optional
- A list of Field ID/Value dicts.
NOTE: _Entries currently have several unused optional fields intended for later features._
## Retrieving Entries based on [Tag](/doc/library/tag.md) Cluster
By default when querying Entries, each Entry's `tags` list (stored in the form of Tag `id`s) is compared against the Tag `id`s in a given Tag cluster (list of Tag `id`s) or appended clusters in the case of multi-term queries. The type of comparison depends on the type of query and whether or not it is an inclusive or exclusive query, or a combination of both. This default searching behavior is done in _O(n)_ time, but can be sped up in the future by building indexes on certain search terms. These indexes can be stored on disk and loaded back into memory in future sessions. These indexes will also need to be updated as new Tags and Entries are added or edited.

View File

@@ -0,0 +1,3 @@
# Entry Groups (Upcoming Feature)
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.

34
doc/library/field.md Normal file
View File

@@ -0,0 +1,34 @@
# Field
Fields are the building blocks of metadata stored in [entries](/doc/library/entry.md). Fields have several base types for representing different kinds of information, including:
#### `text_line`
- A string of text, displayed as a single line.
- e.g: Title, Author, Artist, URL, etc.
#### `text_box`
- A long string of text displayed as a box of text.
- e.g: Description, Notes, etc.
#### `tag_box`
- A box of [tags](/doc/library/tag.md) defined and added by the user.
- Multiple tag boxes can be used to separate classifications of tags.
- e.g: Content Tags, Meta Tags, etc.
#### `datetime` [WIP]
- A date and time value.
- e.g: Date Created, Date Modified, Date Taken, etc.
#### `checkbox` [WIP]
- A simple two-state checkbox.
- Can be associated with a tag for quick organization.
- e.g: Archive, Favorite, etc.
#### `collation` [obsolete]
- Previously used for associating files to be used in a [collation](/doc/utilities/macro.md#create-collage), will be removed in favor of a more flexible feature in future updates.

11
doc/library/library.md Normal file
View File

@@ -0,0 +1,11 @@
# Library
The library is how TagStudio represents your chosen directory, with every file inside of it being displayed as an [entry](/doc/library/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.
Note that this means [tags](/doc/library/tag.md) you create only exist _per-library_.
### Library Contents
- [Entries](/doc/library/entry.md)
- [Fields](/doc/library/field.md)
- [Tags](/doc/library/tag.md)
- [Macros](/doc/utilities/macro.md)

85
doc/library/tag.md Normal file
View File

@@ -0,0 +1,85 @@
# Tag
Tags are user-defined attributes made up of one or more keywords, aliases, and relationships to other tags. A person, place, thing, concept, you name it! Tags allow for a more sophisticated way to organize and search [entries](/doc/library/entry.md) thanks to their aliases, parent tags, and more.
Tags can be as simple or complex as wanted, so that any user can tune TagStudio to fit their needs.
Among the things that make tags so useful, aliases give the ability to contain alternate names and spellings, making searches intuitive and expansive. Furthermore, parent-tags/subtags offer relational organization capabilities for the structuring and connection of the [library's](/doc/library/library.md) contents.
## Tag Object Structure
#### `id`
ID for the tag.
- Int, Unique, Required
- Used for internal processing
#### `name`
The normal name of the tag, with no shortening or specification.
- String, Required
- Doesn't have to be unique
- Used for display, searching, and storing
#### `shorthand`
The shorthand name for the tag. Works like an alias but is used for specific display purposes.
- String, Optional
- Doesn't have to be unique
- Used for display and searching
#### `aliases`
Alternate names for the tag.
- List of Strings, Optional
- Recommended to be unique to this tag
- Used for searching
#### `subtags`
Other Tags that make up properties of this tag. Also called "parent tags".
- List of Strings, Optional
- Used for display (first parent tag only) and searching.
#### `color`
A color name string for customizing the tag's display color
- String, Optional
- Used for display
## Tag Search Examples:
Using for example, a library of files including some tagged with the following tags:
| Tag | `name` | `shorthand` | `aliases` | `parent tags` |
| ------------------- | ------------------- | ----------- | ---------------------- | -------------------------------------------- |
| _League of Legends_ | "League of Legends" | "LoL" | ["League"] | ["Game", "Fantasy"] |
| _Arcane_ | "Arcane" | "" | [] | ["League of Legends", "Cartoon"] |
| _Jinx (LoL)_ | "Jinx Piltover" | "Jinx" | ["Jinxy", "Jinxy Poo"] | ["League of Legends", "Arcane", "Character"] |
| _Zander (Arcane)_ | "Zander Zanderson" | "Zander" | [] | ["Arcane", "Character"] |
| _Mr. Legend (LoL)_ | "Mr. Legend" | "" | [] | ["League of Legends", "Character"] |
**The query "Arcane" will display results tagged with:**
| Tag | Cause of Inclusion | Tag Tree Lineage |
| --------------- | -------------------------------- | -------------------------- |
| Arcane | Direct match of tag name | "Arcane" |
| Jinx (LoL) | Search term is set as parent tag | "Jinx (LoL) > Arcane" |
| Zander (Arcane) | Search term is set as parent tag | "Zander (Arcane) > Arcane" |
**The query "League of Legends" will display results tagged with:**
| Tag | Cause of Inclusion | Tag Tree Lineage |
| ----------------- | ------------------------------------------------------ | ---------------------------------------------- |
| League of Legends | Direct match of tag name | "League of Legends" |
| Arcane | Search term is set as parent tag | "Arcane > League of Legends" |
| Jinx (LoL) | Search term is set as parent tag | "Jinx (LoL) > League of Legends" |
| Mr. Legend (LoL) | Search term is set as parent tag | "Mr. Legend (LoL) > League of Legends" |
| Zander (Arcane) | Search term is a parent tag of a tag set as parent tag | "Zander (Arcane) > Arcane > League of Legends" |
Note: The query "LoL" will display the same results as the above example since "LoL" is the shorthand for "League of Legends".

View File

@@ -0,0 +1,3 @@
# Tag Categories (Upcoming Feature)
Replaces [Tag Fields](/doc/library/field.md#tag_box). Tags are able to be marked as a “category” which then displays as tag fields currently do, with any tags inheriting from that category being displayed underneath.

View File

@@ -0,0 +1,16 @@
# Tag Overrides (Upcoming Feature)
Tag overrides are the ability to add or remove [parent tags](/doc/library/tag.md#subtags) from a [tag](/doc/library/tag.md) on a per- [entry](/doc/library/entry.md) basis. Relies on the [Database Migration](/doc/updates/db_migration.md) update being complete.
## Examples
<figure>
<img src="../assets/tag_override_ex-1.png" alt="Example 1" height="300">
<figcaption>Ex. 1 - Comparing standard tag composition vs additive and subtractive inheritance overrides.</figcaption>
</figure>
<figure>
<img src="../assets/tag_override_ex-2.png" alt="Example 2" height="300">
<figcaption>Ex. 2 - Parent tag swap using tag overrides.</figcaption>
</figure>

View File

@@ -0,0 +1,43 @@
# Database Migration
The database migration is an upcoming refactor to TagStudio's library data storage system. The database will be migrated from a JSON-based one to a SQLite-based one. Part of this migration will include a reworked schema, which will allow for several new features and changes to how [tags](/doc/library/tag.md) and [fields](/doc/library/field.md) operate.
## Schema
<img src="../assets/db_schema.png" alt="Database Schema" width="500">
### `alias` Table
_Description TBA_
### `entry` Table
_Description TBA_
### `entry_attribute` Table
_Description TBA_
### `entry_page` Table
_Description TBA_
### `location` Table
_Description TBA_
### `tag` Table
_Description TBA_
### `tag_relation` Table
_Description TBA_
## Resulting New Features and Changes
- Multiple Directory Support
- [Tag Categories](/doc/library/tag_categories.md) (Replaces [Tag Fields](/doc/library/field.md#tag_box))
- [Tag Overrides](/doc/library/tag_overrides.md)
- User-Defined [Fields](/doc/library/field.md)
- Tag Icons

View File

@@ -0,0 +1,59 @@
# Planned Features
The following lists outline the planned major and minor features for TagStudio, in no particular order.
# Major Features
- [SQL Database Migration](/doc/updates/db_migration.md)
- Multiple Directory Support
- [Tags Categories](/doc/library/tag_categories.md)
- [Entry Groups](/doc/library/entry_groups.md)
- [Tag Overrides](/doc/library/tag_overrides.md)
- Tagging Panel
- Top Tags
- Recent Tags
- Tag Search
- Pinned Tags
- Configurable Default Fields (May be part of [Macros](/doc/utilities/macro.md))
- Deep File Extension Control
- Settings Menu
- Custom User Colors
- Search Engine Rework
- Boolean Search
- Tag Objects In Search
- Search For Fields
- Sortable Search Results
- Automatic Entry Relinking
- Detect Renames
- Detect Moves
- Thumbnail Caching
- User-Defined Fields
- Exportable Library/Tag Data
- Exportable Human-Readable Library
- Exportable/Importable Human-Readable “Tag Packs”
- Exportable/Importable Color Palettes
- Configurable Thumbnail Labels
- Toggle Extension Label
- Toggle File Size Label
- Configurable Thumbnail Tag Badges
- Customize tags that appear instead of just “Archive” and “Favorite”
- OCR Search
## Minor Features
- Deleting Tags
- Merging Tags
- Tag Icons
- Tag/Field Copy + Paste
- Collage UI
- Resizable Thumbnail Grid
- Draggable Files Outside The Program
- File Property Caching
- 3D Previews
- Audio Waveform Previews
- Toggle Between Waveform And Album Artwork
- PDF Previews
- SVG Previews
- Full Video Player
- Duration Properties For Video + Audio Files
- Optional Starter Tag Packs

43
doc/utilities/macro.md Normal file
View File

@@ -0,0 +1,43 @@
# Tools & Macros
Tools and macros are features that serve to create a more fluid [library](/doc/library/library.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.
## Tools
### Fix Unlinked Entries
This tool displays the number of unlinked [entries](/doc/library/entry.md), and some options for their resolution.
1. Refresh
- Scans through the library and updates the unlinked entry count.
2. Search & Relink
- Attempts to automatically find and reassign missing files.
3. Delete Unlinked Entries
- Displays a confirmation prompt containing the list of all missing files to be deleted before committing to or cancelling the operation.
### Fix Duplicate Files
This tool allows for management of duplicate files in the library using a [DupeGuru](https://dupeguru.voltaicideas.net/) file.
1. Load DupeGuru File
- load the "results" file created from a DupeGuru scan
2. Mirror Entries
- Duplicate entries will have their contents mirrored across all instances. This allows for duplicate files to then be deleted with DupeGuru as desired, without losing the [field](/doc/library/field.md) data that has been assigned to either. (Once deleted, the "Fix Unlinked Entries" tool can be used to clean up the duplicates)
### Create Collage
This tool is a preview of an upcoming feature. When selected, TagStudio will generate a collage of all the contents in a Library, which can be found in the Library folder ("/your-folder/.TagStudio/collages/"). Note that this feature is still in early development, and doesn't yet offer any customization options.
## Macros
### Auto-fill [WIP]
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](/doc/library/field.md).
### Folders to Tags
Creates tags from the existing folder structure in the library, which are previewed in a hierarchy view for the user to confirm. A tag will be created for each folder and applied to all entries, with each subfolder being linked to the parent folder as a [parent tag](/doc/library/tag.md#subtags). Tags will initially be named after the folders, but can be fully edited and customized afterwards.

544
flake.lock generated
View File

@@ -1,12 +1,429 @@
{
"nodes": {
"cachix": {
"inputs": {
"devenv": "devenv_2",
"flake-compat": [
"devenv",
"flake-compat"
],
"nixpkgs": [
"devenv",
"nixpkgs"
],
"pre-commit-hooks": [
"devenv",
"pre-commit-hooks"
]
},
"locked": {
"lastModified": 1712055811,
"narHash": "sha256-7FcfMm5A/f02yyzuavJe06zLa9hcMHsagE28ADcmQvk=",
"owner": "cachix",
"repo": "cachix",
"rev": "02e38da89851ec7fec3356a5c04bc8349cae0e30",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "cachix",
"type": "github"
}
},
"devenv": {
"inputs": {
"cachix": "cachix",
"flake-compat": "flake-compat_2",
"nix": "nix_2",
"nixpkgs": "nixpkgs_2",
"pre-commit-hooks": "pre-commit-hooks"
},
"locked": {
"lastModified": 1724763216,
"narHash": "sha256-oW2bwCrJpIzibCNK6zfIDaIQw765yMAuMSG2gyZfGv0=",
"owner": "cachix",
"repo": "devenv",
"rev": "1e4ef61205b9aa20fe04bf1c468b6a316281c4f1",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "devenv",
"type": "github"
}
},
"devenv-root": {
"flake": false,
"locked": {
"narHash": "sha256-d6xi4mKdjkX2JFicDIv5niSzpyI0m/Hnm8GGAIU04kY=",
"type": "file",
"url": "file:///dev/null"
},
"original": {
"type": "file",
"url": "file:///dev/null"
}
},
"devenv_2": {
"inputs": {
"flake-compat": [
"devenv",
"cachix",
"flake-compat"
],
"nix": "nix",
"nixpkgs": "nixpkgs",
"poetry2nix": "poetry2nix",
"pre-commit-hooks": [
"devenv",
"cachix",
"pre-commit-hooks"
]
},
"locked": {
"lastModified": 1708704632,
"narHash": "sha256-w+dOIW60FKMaHI1q5714CSibk99JfYxm0CzTinYWr+Q=",
"owner": "cachix",
"repo": "devenv",
"rev": "2ee4450b0f4b95a1b90f2eb5ffea98b90e48c196",
"type": "github"
},
"original": {
"owner": "cachix",
"ref": "python-rewrite",
"repo": "devenv",
"type": "github"
}
},
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1673956053,
"narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-compat_2": {
"flake": false,
"locked": {
"lastModified": 1696426674,
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-parts": {
"inputs": {
"nixpkgs-lib": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1725024810,
"narHash": "sha256-ODYRm8zHfLTH3soTFWE452ydPYz2iTvr9T8ftDMUQ3E=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "af510d4a62d071ea13925ce41c95e3dec816c01d",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1689068808,
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_3": {
"inputs": {
"systems": "systems_3"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"gitignore": {
"inputs": {
"nixpkgs": [
"devenv",
"pre-commit-hooks",
"nixpkgs"
]
},
"locked": {
"lastModified": 1709087332,
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "gitignore.nix",
"type": "github"
}
},
"nix": {
"inputs": {
"flake-compat": "flake-compat",
"nixpkgs": [
"devenv",
"cachix",
"devenv",
"nixpkgs"
],
"nixpkgs-regression": "nixpkgs-regression"
},
"locked": {
"lastModified": 1712911606,
"narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=",
"owner": "domenkozar",
"repo": "nix",
"rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12",
"type": "github"
},
"original": {
"owner": "domenkozar",
"ref": "devenv-2.21",
"repo": "nix",
"type": "github"
}
},
"nix-github-actions": {
"inputs": {
"nixpkgs": [
"devenv",
"cachix",
"devenv",
"poetry2nix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1688870561,
"narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=",
"owner": "nix-community",
"repo": "nix-github-actions",
"rev": "165b1650b753316aa7f1787f3005a8d2da0f5301",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nix-github-actions",
"type": "github"
}
},
"nix2container": {
"inputs": {
"flake-utils": "flake-utils_3",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1724996935,
"narHash": "sha256-njRK9vvZ1JJsP8oV2OgkBrpJhgQezI03S7gzskCcHos=",
"owner": "nlewo",
"repo": "nix2container",
"rev": "fa6bb0a1159f55d071ba99331355955ae30b3401",
"type": "github"
},
"original": {
"owner": "nlewo",
"repo": "nix2container",
"type": "github"
}
},
"nix_2": {
"inputs": {
"flake-compat": [
"devenv",
"flake-compat"
],
"nixpkgs": [
"devenv",
"nixpkgs"
],
"nixpkgs-regression": "nixpkgs-regression_2"
},
"locked": {
"lastModified": 1712911606,
"narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=",
"owner": "domenkozar",
"repo": "nix",
"rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12",
"type": "github"
},
"original": {
"owner": "domenkozar",
"ref": "devenv-2.21",
"repo": "nix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1712473363,
"narHash": "sha256-TIScFAVdI2yuybMxxNjC4YZ/j++c64wwuKbpnZnGiyU=",
"lastModified": 1692808169,
"narHash": "sha256-x9Opq06rIiwdwGeK2Ykj69dNc2IvUH1fY55Wm7atwrE=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9201b5ff357e781bf014d0330d18555695df7ba8",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-qt6": {
"locked": {
"lastModified": 1718428119,
"narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
}
},
"nixpkgs-regression": {
"locked": {
"lastModified": 1643052045,
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
}
},
"nixpkgs-regression_2": {
"locked": {
"lastModified": 1643052045,
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
}
},
"nixpkgs-stable": {
"locked": {
"lastModified": 1710695816,
"narHash": "sha256-3Eh7fhEID17pv9ZxrPwCLfqXnYP006RKzSs0JptsN84=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "614b4613980a522ba49f0d194531beddbb7220d3",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-23.11",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1713361204,
"narHash": "sha256-TA6EDunWTkc5FvDCqU3W2T3SFn0gRZqh6D/hJnM02MM=",
"owner": "cachix",
"repo": "devenv-nixpkgs",
"rev": "285676e87ad9f0ca23d8714a6ab61e7e027020c6",
"type": "github"
},
"original": {
"owner": "cachix",
"ref": "rolling",
"repo": "devenv-nixpkgs",
"type": "github"
}
},
"nixpkgs_3": {
"locked": {
"lastModified": 1724819573,
"narHash": "sha256-GnR7/ibgIH1vhoy8cYdmXE6iyZqKqFxQSVkFgosBh6w=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "e89cf1c932006531f454de7d652163a9a5c86668",
"rev": "71e91c409d1e654808b2621f28a327acfdad8dc2",
"type": "github"
},
"original": {
@@ -16,9 +433,128 @@
"type": "github"
}
},
"poetry2nix": {
"inputs": {
"flake-utils": "flake-utils",
"nix-github-actions": "nix-github-actions",
"nixpkgs": [
"devenv",
"cachix",
"devenv",
"nixpkgs"
]
},
"locked": {
"lastModified": 1692876271,
"narHash": "sha256-IXfZEkI0Mal5y1jr6IRWMqK8GW2/f28xJenZIPQqkY0=",
"owner": "nix-community",
"repo": "poetry2nix",
"rev": "d5006be9c2c2417dafb2e2e5034d83fabd207ee3",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "poetry2nix",
"type": "github"
}
},
"pre-commit-hooks": {
"inputs": {
"flake-compat": [
"devenv",
"flake-compat"
],
"flake-utils": "flake-utils_2",
"gitignore": "gitignore",
"nixpkgs": [
"devenv",
"nixpkgs"
],
"nixpkgs-stable": "nixpkgs-stable"
},
"locked": {
"lastModified": 1713775815,
"narHash": "sha256-Wu9cdYTnGQQwtT20QQMg7jzkANKQjwBD9iccfGKkfls=",
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"rev": "2ac4dcbf55ed43f3be0bae15e181f08a57af24a4",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
"devenv": "devenv",
"devenv-root": "devenv-root",
"flake-parts": "flake-parts",
"nix2container": "nix2container",
"nixpkgs": "nixpkgs_3",
"nixpkgs-qt6": "nixpkgs-qt6",
"systems": "systems_4"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_3": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_4": {
"locked": {
"lastModified": 1689347949,
"narHash": "sha256-12tWmuL2zgBgZkdoB6qXZsgJEH9LR3oUgpaQq2RbI80=",
"owner": "nix-systems",
"repo": "default-linux",
"rev": "31732fcf5e8fea42e59c2488ad31a0e651500f68",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default-linux",
"type": "github"
}
}
},

266
flake.nix
View File

@@ -1,70 +1,208 @@
{
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
description = "TagStudio";
outputs = { self, nixpkgs, }:
let
pkgs = nixpkgs.legacyPackages.x86_64-linux;
in {
devShells.x86_64-linux.default = pkgs.mkShell {
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [
pkgs.gcc-unwrapped
pkgs.zlib
pkgs.libglvnd
pkgs.glib
pkgs.stdenv.cc.cc
pkgs.fontconfig
pkgs.libxkbcommon
pkgs.xorg.libxcb
pkgs.freetype
pkgs.dbus
pkgs.qt6.qtwayland
pkgs.qt6.full
pkgs.qt6.qtbase
pkgs.zstd
];
buildInputs = with pkgs; [
cmake
gdb
zstd
qt6.qtbase
qt6.full
qt6.qtwayland
qtcreator
python312Packages.pip
python312Full
python312Packages.virtualenv # run virtualenv .
python312Packages.pyusb # fixes the pyusb 'No backend available' when installed directly via pip
inputs = {
devenv.url = "github:cachix/devenv";
libgcc
makeWrapper
bashInteractive
glib
libxkbcommon
freetype
binutils
dbus
coreutils
libGL
libGLU
fontconfig
xorg.libxcb
# this is for the shellhook portion
qt6.wrapQtAppsHook
makeWrapper
bashInteractive
];
# set the environment variables that Qt apps expect
shellHook = ''
export QT_QPA_PLATFORM=wayland
export LIBRARY_PATH=/usr/lib:/usr/lib64:$LIBRARY_PATH
# export LD_LIBRARY_PATH=${pkgs.stdenv.cc.cc.lib}/lib/:/run/opengl-driver/lib/
export QT_PLUGIN_PATH=${pkgs.qt6.qtbase}/${pkgs.qt6.qtbase.qtPluginPrefix}
bashdir=$(mktemp -d)
makeWrapper "$(type -p bash)" "$bashdir/bash" "''${qtWrapperArgs[@]}"
exec "$bashdir/bash"
'';
devenv-root = {
url = "file+file:///dev/null";
flake = false;
};
flake-parts = {
url = "github:hercules-ci/flake-parts";
inputs.nixpkgs-lib.follows = "nixpkgs";
};
nix2container = {
url = "github:nlewo/nix2container";
inputs.nixpkgs.follows = "nixpkgs";
};
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
# Pinned to Qt version 6.7.1
nixpkgs-qt6.url = "github:NixOS/nixpkgs/e6cea36f83499eb4e9cd184c8a8e823296b50ad5";
systems.url = "github:nix-systems/default-linux";
};
outputs =
{
flake-parts,
nixpkgs,
nixpkgs-qt6,
self,
systems,
...
}@inputs:
flake-parts.lib.mkFlake { inherit inputs; } {
imports = [ inputs.devenv.flakeModule ];
systems = import systems;
perSystem =
{
config,
pkgs,
system,
...
}:
let
inherit (nixpkgs) lib;
qt6Pkgs = import nixpkgs-qt6 { inherit system; };
in
{
formatter = pkgs.nixfmt-rfc-style;
devenv.shells = rec {
default = tagstudio;
tagstudio =
let
cfg = config.devenv.shells.tagstudio;
in
{
# NOTE: many things were simply transferred over from previous,
# there must be additional work in ensuring all relevant dependencies
# are in place (and no extraneous). I have already spent much
# work making this in the first place and just need to get it out
# there, especially after my promises. Would appreciate any help
# (possibly PRs!) on taking care of this. Otherwise, just expect
# this to get ironed out over time.
#
# Thank you! -Xarvex
devenv.root =
let
devenvRoot = builtins.readFile inputs.devenv-root.outPath;
in
# If not overriden (/dev/null), --impure is necessary.
pkgs.lib.mkIf (devenvRoot != "") devenvRoot;
name = "TagStudio";
# Derived from previous flake iteration.
packages =
(with pkgs; [
cmake
binutils
coreutils
dbus
fontconfig
freetype
gdb
glib
libGL
libGLU
libgcc
libxkbcommon
mypy
ruff
xorg.libxcb
zstd
])
++ (with qt6Pkgs; [
qt6.full
qt6.qtbase
qt6.qtwayland
qtcreator
]);
enterShell =
let
setQtEnv =
pkgs.runCommand "set-qt-env"
{
buildInputs = with qt6Pkgs.qt6; [
qtbase
];
nativeBuildInputs =
(with pkgs; [
makeShellWrapper
])
++ (with qt6Pkgs.qt6; [
wrapQtAppsHook
]);
}
''
makeShellWrapper "$(type -p sh)" "$out" "''${qtWrapperArgs[@]}"
sed "/^exec/d" -i "$out"
'';
in
''
source ${setQtEnv}
'';
scripts.tagstudio.exec = ''
python ${cfg.devenv.root}/tagstudio/tag_studio.py
'';
env = {
QT_QPA_PLATFORM = "wayland;xcb";
# Derived from previous flake iteration.
# Not desired given LD_LIBRARY_PATH pollution.
# See supposed alternative below, further research required.
LD_LIBRARY_PATH = lib.makeLibraryPath (
(with pkgs; [
dbus
fontconfig
freetype
gcc-unwrapped
glib
libglvnd
libkrb5
libpulseaudio
libva
libxkbcommon
openssl
stdenv.cc.cc.lib
wayland
xorg.libxcb
xorg.libXrandr
zlib
zstd
])
++ (with qt6Pkgs.qt6; [
qtbase
qtwayland
full
])
);
};
languages.python = {
enable = true;
venv = {
enable = true;
quiet = true;
requirements =
let
excludeDeps =
req: deps:
builtins.concatStringsSep "\n" (
builtins.filter (line: !(lib.any (elem: lib.hasPrefix elem line) deps)) (lib.splitString "\n" req)
);
in
''
${builtins.readFile ./requirements.txt}
${excludeDeps (builtins.readFile ./requirements-dev.txt) [
"mypy"
"ruff"
]}
'';
};
# Should be able to replace LD_LIBRARY_PATH?
# Was not quite able to get working,
# will be consulting cachix community. -Xarvex
# libraries = with pkgs; [ ];
};
};
};
};
};
}

View File

@@ -1,8 +1,9 @@
[tool.ruff]
exclude = ["main_window.py", "home_ui.py", "resources.py", "resources_rc.py"]
exclude = ["main_window.py", "home_ui.py", "resources.py", "resources_rc.py", "**/vendored/"]
[tool.mypy]
strict_optional = false
disable_error_code = ["union-attr", "annotation-unchecked", "import-untyped"]
explicit_package_bases = true
warn_unused_ignores = true
exclude = ['tests', 'src/qt/helpers/vendored']

View File

@@ -3,3 +3,4 @@ pre-commit==3.7.0
pytest==8.2.0
Pyinstaller==6.6.0
mypy==1.10.0
syrupy==4.6.1

View File

@@ -1,10 +1,18 @@
humanfriendly==10.0
opencv_python>=4.8.0.74,<=4.9.0.80
Pillow==10.3.0
PySide6>=6.5.1.1,<=6.6.3.1
PySide6_Addons>=6.5.1.1,<=6.6.3.1
PySide6_Essentials>=6.5.1.1,<=6.6.3.1
PySide6==6.7.1
PySide6_Addons==6.7.1
PySide6_Essentials==6.7.1
typing_extensions>=3.10.0.0,<=4.11.0
ujson>=5.8.0,<=5.9.0
numpy==1.26.4
rawpy==0.21.0
pillow-heif==0.16.0
chardet==5.2.0
pydub==0.25.1
mutagen==1.47.0
numpy==1.26.4
ffmpeg-python==0.2.0
Send2Trash==1.8.3
vtf2img==0.1.0

View File

@@ -26,7 +26,7 @@ a = Analysis(
['tagstudio/tag_studio.py'],
pathex=[],
binaries=[],
datas=[('tagstudio/resources', 'resources')],
datas=[('tagstudio/resources', 'resources'), ('tagstudio/src', 'src')],
hiddenimports=[],
hookspath=[],
hooksconfig={},

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 361 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="#ffffff"><path d="M560-200v-560h160v560H560Zm-320 0v-560h160v560H240Z"/></svg>

After

Width:  |  Height:  |  Size: 172 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="#ffffff"><path d="M320-200v-560l440 280-440 280Z"/></svg>

After

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

After

Width:  |  Height:  |  Size: 397 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="#ffffff"><path d="M560-131v-82q90-26 145-100t55-168q0-94-55-168T560-749v-82q124 28 202 125.5T840-481q0 127-78 224.5T560-131ZM120-360v-240h160l200-200v640L280-360H120Zm440 40v-322q47 22 73.5 66t26.5 96q0 51-26.5 94.5T560-320Z"/></svg>

After

Width:  |  Height:  |  Size: 327 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="#ffffff"><path d="M792-56 671-177q-25 16-53 27.5T560-131v-82q14-5 27.5-10t25.5-12L480-368v208L280-360H120v-240h128L56-792l56-56 736 736-56 56Zm-8-232-58-58q17-31 25.5-65t8.5-70q0-94-55-168T560-749v-82q124 28 202 125.5T840-481q0 53-14.5 102T784-288ZM650-422l-90-90v-130q47 22 73.5 66t26.5 96q0 15-2.5 29.5T650-422ZM480-592 376-696l104-104v208Z"/></svg>

After

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

View File

@@ -88,21 +88,19 @@ class CliDriver:
self.is_dupe_file_count_init: bool = False
self.external_preview_size: tuple[int, int] = (960, 960)
epd_path = os.path.normpath(
f"{Path(__file__).parents[2]}/resources/cli/images/external_preview.png"
epd_path = (
Path(__file__).parents[2] / "resources/cli/images/external_preview.png"
)
self.external_preview_default: Image = (
Image.open(epd_path)
if os.path.exists(epd_path)
if epd_path.exists()
else Image.new(mode="RGB", size=(self.external_preview_size))
)
self.external_preview_default.thumbnail(self.external_preview_size)
epb_path = os.path.normpath(
f"{Path(__file__).parents[2]}/resources/cli/images/no_preview.png"
)
epb_path = Path(__file__).parents[3] / "resources/cli/images/no_preview.png"
self.external_preview_broken: Image = (
Image.open(epb_path)
if os.path.exists(epb_path)
if epb_path.exists()
else Image.new(mode="RGB", size=(self.external_preview_size))
)
self.external_preview_broken.thumbnail(self.external_preview_size)
@@ -361,45 +359,44 @@ class CliDriver:
def init_external_preview(self) -> None:
"""Initialized the external preview image file."""
if self.lib and self.lib.library_dir:
external_preview_path: str = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/external_preview.jpg"
external_preview_path: Path = (
self.lib.library_dir / TS_FOLDER_NAME / "external_preview.jpg"
)
if not os.path.isfile(external_preview_path):
if not external_preview_path.is_file():
temp = self.external_preview_default
temp.save(external_preview_path)
open_file(external_preview_path)
def set_external_preview_default(self) -> None:
"""Sets the external preview to its default image."""
if self.lib and self.lib.library_dir:
external_preview_path: str = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/external_preview.jpg"
external_preview_path: Path = (
self.lib.library_dir / TS_FOLDER_NAME / "external_preview.jpg"
)
if os.path.isfile(external_preview_path):
if external_preview_path.is_file():
temp = self.external_preview_default
temp.save(external_preview_path)
def set_external_preview_broken(self) -> None:
"""Sets the external preview image file to the 'broken' placeholder."""
if self.lib and self.lib.library_dir:
external_preview_path: str = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/external_preview.jpg"
external_preview_path: Path = (
self.lib.library_dir / TS_FOLDER_NAME / "external_preview.jpg"
)
if os.path.isfile(external_preview_path):
if external_preview_path.is_file():
temp = self.external_preview_broken
temp.save(external_preview_path)
def close_external_preview(self) -> None:
"""Destroys and closes the external preview image file."""
if self.lib and self.lib.library_dir:
external_preview_path: str = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/external_preview.jpg"
external_preview_path: Path = (
self.lib.library_dir / TS_FOLDER_NAME / "external_preview.jpg"
)
if os.path.isfile(external_preview_path):
if external_preview_path.is_file():
os.remove(external_preview_path)
def scr_create_library(self, path=""):
def scr_create_library(self, path=None):
"""Screen for creating a new TagStudio library."""
subtitle = "Create Library"
@@ -412,7 +409,10 @@ class CliDriver:
if not path:
print("Enter Library Folder Path: \n> ", end="")
path = input()
if os.path.exists(path):
path = Path(path)
if path.exists():
print("")
print(
f'{INFO} Are you sure you want to create a new Library at "{path}"? (Y/N)\n> ',
@@ -488,9 +488,7 @@ class CliDriver:
"""Saves a backup copy of the Library file to disk. Returns True if successful."""
if self.lib and self.lib.library_dir:
filename = self.lib.save_library_backup_to_disk()
location = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/backups/{filename}"
)
location = self.lib.library_dir / TS_FOLDER_NAME / "backups" / filename
if display_message:
print(f'{INFO} Backup of Library saved at "{location}".')
return True
@@ -617,13 +615,11 @@ class CliDriver:
"""
entry = None if index < 0 else self.lib.entries[index]
if entry:
filepath = os.path.normpath(
f"{self.lib.library_dir}/{entry.path}/{entry.filename}"
)
external_preview_path: str = ""
filepath = self.lib.library_dir / entry.path / entry.filename
external_preview_path: Path = None
if self.args.external_preview:
external_preview_path = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/external_preview.jpg"
external_preview_path = (
self.lib.library_dir / TS_FOLDER_NAME / "external_preview.jpg"
)
# thumb_width = min(
# os.get_terminal_size()[0]//2,
@@ -674,14 +670,9 @@ class CliDriver:
final_frame = Image.fromarray(frame)
w, h = final_frame.size
final_frame.save(
os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/temp.jpg"
),
quality=50,
)
final_img_path = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/temp.jpg"
self.lib.library_dir / TS_FOLDER_NAME / "temp.jpg", quality=50
)
final_img_path = self.lib.library_dir / TS_FOLDER_NAME / "temp.jpg"
# NOTE: Temporary way to hack a non-terminal preview.
if self.args.external_preview and entry:
final_frame.thumbnail(self.external_preview_size)
@@ -744,7 +735,7 @@ class CliDriver:
print(image.replace("\n", ("\n" + " " * spacing)))
if file_type in VIDEO_TYPES:
os.remove(f"{self.lib.library_dir}/{TS_FOLDER_NAME}/temp.jpg")
os.remove(self.lib.library_dir / TS_FOLDER_NAME / "temp.jpg")
except:
if not self.args.external_preview or not entry:
print(
@@ -901,7 +892,7 @@ class CliDriver:
"""Runs a specific Macro on an Entry given a Macro name."""
# entry: Entry = self.lib.get_entry_from_index(entry_id)
entry = self.lib.get_entry(entry_id)
path = os.path.normpath(f"{self.lib.library_dir}/{entry.path}/{entry.filename}")
path = self.lib.library_dir / entry.path / entry.filename
source = path.split(os.sep)[1].lower()
if name == "sidecar":
self.lib.add_generic_data_to_entry(
@@ -1054,8 +1045,11 @@ class CliDriver:
time.sleep(5)
collage = Image.new("RGB", (img_size, img_size))
filename = os.path.normpath(
f'{self.lib.library_dir}/{TS_FOLDER_NAME}/{COLLAGE_FOLDER_NAME}/collage_{datetime.datetime.utcnow().strftime("%F_%T").replace(":", "")}.png'
filename = (
elf.lib.library_dir
/ TS_FOLDER_NAME
/ COLLAGE_FOLDER_NAME
/ f'collage_{datetime.datetime.utcnow().strftime("%F_%T").replace(":", "")}.png'
)
i = 0
@@ -1065,10 +1059,7 @@ class CliDriver:
if i < len(self.lib.entries) and run:
# entry: Entry = self.lib.get_entry_from_index(i)
entry = self.lib.entries[i]
filepath = os.path.normpath(
f"{self.lib.library_dir}/{entry.path}/{entry.filename}"
)
file_type = os.path.splitext(filepath)[1].lower()[1:]
filepath = self.lib.library_dir / entry.path / entry.filename
color: str = ""
if data_tint_mode or data_only_mode:
@@ -1113,16 +1104,17 @@ class CliDriver:
collage.paste(pic, (y * thumb_size, x * thumb_size))
if not data_only_mode:
print(
f"\r{INFO} Combining [{i+1}/{len(self.lib.entries)}]: {self.get_file_color(file_type)}{entry.path}{os.sep}{entry.filename}{RESET}"
f"\r{INFO} Combining [{i+1}/{len(self.lib.entries)}]: {self.get_file_color(filepath.suffix.lower())}{entry.path}{os.sep}{entry.filename}{RESET}"
)
# sys.stdout.write(f'\r{INFO} Combining [{i+1}/{len(self.lib.entries)}]: {self.get_file_color(file_type)}{entry.path}{os.sep}{entry.filename}{RESET}')
# sys.stdout.flush()
if file_type in IMAGE_TYPES:
if filepath.suffix.lower() in IMAGE_TYPES:
try:
with Image.open(
os.path.normpath(
f"{self.lib.library_dir}/{entry.path}/{entry.filename}"
)
self.lib.library_dir
/ entry.path
/ entry.filename
) as pic:
if keep_aspect:
pic.thumbnail((thumb_size, thumb_size))
@@ -1146,7 +1138,7 @@ class CliDriver:
f"[ERROR] One of the images was too big ({e})"
)
elif file_type in VIDEO_TYPES:
elif filepath.suffix.lower() in VIDEO_TYPES:
video = cv2.VideoCapture(filepath)
video.set(
cv2.CAP_PROP_POS_FRAMES,
@@ -1168,9 +1160,7 @@ class CliDriver:
)
collage.paste(pic, (y * thumb_size, x * thumb_size))
except UnidentifiedImageError:
print(
f"\n{ERROR} Couldn't read {entry.path}{os.sep}{entry.filename}"
)
print(f"\n{ERROR} Couldn't read {entry.path / entry.filename}")
except KeyboardInterrupt:
# self.quit(save=False, backup=True)
run = False
@@ -1178,7 +1168,7 @@ class CliDriver:
print(f"{INFO} Collage operation cancelled.")
clear_scr = False
except:
print(f"{ERROR} {entry.path}{os.sep}{entry.filename}")
print(f"{ERROR} {entry.path / entry.filename}")
traceback.print_exc()
print("Continuing...")
i = i + 1
@@ -1455,7 +1445,7 @@ class CliDriver:
f"{WHITE_FG}Enter the filename for your DupeGuru results file:\n> {RESET}",
end="",
)
dg_results_file = os.path.normpath(input())
dg_results_file = Path(input())
print(
f"{INFO} Checking for duplicate files in Library '{self.lib.library_dir}'..."
)
@@ -1477,7 +1467,7 @@ class CliDriver:
) > 1:
if com[1].lower() == "entries":
for i, e in enumerate(self.lib.entries, start=0):
title = f"[{i+1}/{len(self.lib.entries)}] {self.lib.entries[i].path}{os.path.sep}{self.lib.entries[i].filename}"
title = f"[{i+1}/{len(self.lib.entries)}] {self.lib.entries[i].path / os.path.sep / self.lib.entries[i].filename}"
print(
self.format_subtitle(
title,
@@ -1526,12 +1516,11 @@ class CliDriver:
for dupe in self.lib.dupe_entries:
print(
self.lib.entries[dupe[0]].path
+ os.path.sep
+ self.lib.entries[dupe[0]].filename
/ self.lib.entries[dupe[0]].filename
)
for d in dupe[1]:
print(
f"\t-> {(self.lib.entries[d].path + os.path.sep + self.lib.entries[d].filename)}"
f"\t-> {(self.lib.entries[d].path / self.lib.entries[d].filename)}"
)
time.sleep(0.1)
print("Press Enter to Continue...")
@@ -1871,20 +1860,18 @@ class CliDriver:
# entry = self.lib.get_entry_from_index(
# self.filtered_entries[index])
entry = self.lib.get_entry(self.filtered_entries[index][1])
filename = f'{os.path.normpath(self.lib.library_dir + "/" + entry.path + "/" + entry.filename)}'
filename = self.lib.library_dir / entry.path / entry.filename
# if self.lib.is_legacy_library:
# title += ' (Legacy Format)'
h1 = f"[{index + 1}/{len(self.filtered_entries)}] {filename}"
# print(self.format_subtitle(subtitle))
print(
self.format_h1(
h1, self.get_file_color(os.path.splitext(filename)[1])
)
self.format_h1(h1, self.get_file_color(filename.suffix.lower()))
)
print("")
if not os.path.isfile(filename):
if not filename.is_file():
print(
f"{RED_BG}{BRIGHT_WHITE_FG}[File Missing]{RESET}{BRIGHT_RED_FG} (Run 'fix missing' to resolve){RESET}"
)
@@ -2527,7 +2514,7 @@ class CliDriver:
while True:
entry = self.lib.get_entry_from_index(index)
filename = f'{os.path.normpath(self.lib.library_dir + "/" + entry.path + "/" + entry.filename)}'
filename = self.lib.library_dir / entry.path / entry.filename
if refresh:
if clear_scr:
@@ -2542,7 +2529,7 @@ class CliDriver:
for i, match in enumerate(self.lib.missing_matches[filename]):
print(self.format_h1(f"[{i+1}] {match}"), end="\n\n")
fn = f'{os.path.normpath(self.lib.library_dir + "/" + match + "/" + entry.filename)}'
fn = self.lib.library_dir / match / entry.filename
self.print_thumbnail(
index=-1,
filepath=fn,
@@ -2585,9 +2572,7 @@ class CliDriver:
# Open =============================================================
elif com[0].lower() == "open" or com[0].lower() == "o":
for match in self.lib.missing_matches[filename]:
fn = os.path.normpath(
self.lib.library_dir + "/" + match + "/" + entry.filename
)
fn = self.lib.library_dir / match / entry.filename
open_file(fn)
refresh = False
# clear()
@@ -2630,9 +2615,7 @@ class CliDriver:
while True:
dupe = self.lib.dupe_files[index]
if os.path.exists(os.path.normpath(f"{dupe[0]}")) and os.path.exists(
os.path.normpath(f"{dupe[1]}")
):
if dupe[0].exists() and dupe[1].exists():
# entry = self.lib.get_entry_from_index(index_1)
entry_1_index = self.lib.get_entry_id_from_filepath(dupe[0])
entry_2_index = self.lib.get_entry_id_from_filepath(dupe[1])
@@ -2779,7 +2762,7 @@ class CliDriver:
title = f"{self.base_title} - Library '{self.lib.library_dir}'"
entry = self.lib.entries[entry_index]
filename = f'{os.path.normpath(self.lib.library_dir + "/" + entry.path + "/" + entry.filename)}'
filename = self.lib.library_dir / entry.path / entry.filename
field_name = self.lib.get_field_attr(entry.fields[field_index], "name")
subtitle = f'Editing "{field_name}" Field'
h1 = f"{filename}"
@@ -2796,7 +2779,7 @@ class CliDriver:
)
print("")
if not os.path.isfile(filename):
if not filename.is_file():
print(
f"{RED_BG}{BRIGHT_WHITE_FG}[File Missing]{RESET}{BRIGHT_RED_FG} (Run 'fix missing' to resolve){RESET}"
)
@@ -3048,7 +3031,7 @@ class CliDriver:
title = f"{self.base_title} - Library '{self.lib.library_dir}'"
entry = self.lib.entries[entry_index]
filename = f'{os.path.normpath(self.lib.library_dir + "/" + entry.path + "/" + entry.filename)}'
filename = self.lib.library_dir / entry.path / entry.filename
field_name = self.lib.get_field_attr(entry.fields[field_index], "name")
subtitle = f'Editing "{field_name}" Field'
h1 = f"{filename}"
@@ -3061,7 +3044,7 @@ class CliDriver:
print(self.format_h1(h1, self.get_file_color(os.path.splitext(filename)[1])))
print("")
if not os.path.isfile(filename):
if not filename.is_file():
print(
f"{RED_BG}{BRIGHT_WHITE_FG}[File Missing]{RESET}{BRIGHT_RED_FG} (Run 'fix missing' to resolve){RESET}"
)

View File

@@ -1,5 +1,5 @@
VERSION: str = "9.2.1" # Major.Minor.Patch
VERSION_BRANCH: str = "Pre-Release" # 'Alpha', 'Beta', or '' for Full Release
VERSION: str = "9.4.2" # 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"
@@ -7,90 +7,10 @@ BACKUP_FOLDER_NAME: str = "backups"
COLLAGE_FOLDER_NAME: str = "collages"
LIBRARY_FILENAME: str = "ts_library.json"
# TODO: Turn this whitelist into a user-configurable blacklist.
IMAGE_TYPES: list[str] = [
"png",
"jpg",
"jpeg",
"jpg_large",
"jpeg_large",
"jfif",
"gif",
"tif",
"tiff",
"heic",
"heif",
"webp",
"bmp",
"svg",
"avif",
"apng",
"jp2",
"j2k",
"jpg2",
]
RAW_IMAGE_TYPES: list[str] = ["raw", "dng", "rw2", "nef", "arw", "crw", "cr3"]
VIDEO_TYPES: list[str] = [
"mp4",
"webm",
"mov",
"hevc",
"mkv",
"avi",
"wmv",
"flv",
"gifv",
"m4p",
"m4v",
"3gp",
]
AUDIO_TYPES: list[str] = [
"mp3",
"mp4",
"mpeg4",
"m4a",
"aac",
"wav",
"flac",
"alac",
"wma",
"ogg",
"aiff",
]
DOC_TYPES: list[str] = ["txt", "rtf", "md", "doc", "docx", "pdf", "tex", "odt", "pages"]
PLAINTEXT_TYPES: list[str] = [
"txt",
"md",
"css",
"html",
"xml",
"json",
"js",
"ts",
"ini",
"htm",
"csv",
"php",
"sh",
"bat",
]
SPREADSHEET_TYPES: list[str] = ["csv", "xls", "xlsx", "numbers", "ods"]
PRESENTATION_TYPES: list[str] = ["ppt", "pptx", "key", "odp"]
ARCHIVE_TYPES: list[str] = ["zip", "rar", "tar", "tar.gz", "tgz", "7z"]
PROGRAM_TYPES: list[str] = ["exe", "app"]
SHORTCUT_TYPES: list[str] = ["lnk", "desktop", "url"]
ALL_FILE_TYPES: list[str] = (
IMAGE_TYPES
+ VIDEO_TYPES
+ AUDIO_TYPES
+ DOC_TYPES
+ SPREADSHEET_TYPES
+ PRESENTATION_TYPES
+ ARCHIVE_TYPES
+ PROGRAM_TYPES
+ SHORTCUT_TYPES
FONT_SAMPLE_TEXT: str = (
"""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!?@$%(){}[]"""
)
FONT_SAMPLE_SIZES: list[int] = [10, 15, 20]
BOX_FIELDS = ["tag_box", "text_box"]
TEXT_FIELDS = ["text_line", "text_box"]
@@ -135,3 +55,5 @@ TAG_COLORS = [
"cool gray",
"olive",
]
TAG_FAVORITE = 1
TAG_ARCHIVED = 0

View File

@@ -8,9 +8,34 @@ class SettingItems(str, enum.Enum):
LAST_LIBRARY = "last_library"
LIBS_LIST = "libs_list"
WINDOW_SHOW_LIBS = "window_show_libs"
AUTOPLAY = "autoplay_videos"
class Theme(str, enum.Enum):
COLOR_BG = "#65000000"
COLOR_BG_DARK = "#65000000"
COLOR_BG_LIGHT = "#22000000"
COLOR_DARK_LABEL = "#DD000000"
COLOR_HOVER = "#65AAAAAA"
COLOR_PRESSED = "#65EEEEEE"
COLOR_DISABLED = "#65F39CAA"
COLOR_DISABLED_BG = "#65440D12"
class SearchMode(int, enum.Enum):
"""Operational modes for item searching."""
AND = 0
OR = 1
class FieldID(int, enum.Enum):
TITLE = 0
AUTHOR = 1
ARTIST = 2
DESCRIPTION = 4
NOTES = 5
TAGS = 6
CONTENT_TAGS = 7
META_TAGS = 8
DATE_PUBLISHED = 14
SOURCE = 21

View File

@@ -1,4 +1,5 @@
from typing import TypedDict
from typing_extensions import NotRequired
class JsonLibary(TypedDict("", {"ts-version": str})):
@@ -8,7 +9,9 @@ class JsonLibary(TypedDict("", {"ts-version": str})):
fields: list # TODO
macros: "list[JsonMacro]"
entries: "list[JsonEntry]"
ignored_extensions: list[str]
ext_list: list[str]
is_exclude_list: bool
ignored_extensions: NotRequired[list[str]] # deprecated
class JsonBase(TypedDict):

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,486 @@
# 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 enum import Enum
from pathlib import Path
logging.basicConfig(format="%(message)s", level=logging.INFO)
class MediaType(str, Enum):
"""Names of media types."""
ADOBE_PHOTOSHOP: str = "adobe_photoshop"
AFFINITY_PHOTO: str = "affinity_photo"
ARCHIVE: str = "archive"
AUDIO_MIDI: str = "audio_midi"
AUDIO: str = "audio"
BLENDER: str = "blender"
DATABASE: str = "database"
DISK_IMAGE: str = "disk_image"
DOCUMENT: str = "document"
FONT: str = "font"
IMAGE_ANIMATED: str = "image_animated"
IMAGE_RAW: str = "image_raw"
IMAGE_VECTOR: str = "image_vector"
IMAGE: str = "image"
INSTALLER: str = "installer"
MATERIAL: str = "material"
MODEL: str = "model"
PACKAGE: str = "package"
PDF: str = "pdf"
PLAINTEXT: str = "plaintext"
PRESENTATION: str = "presentation"
PROGRAM: str = "program"
SHORTCUT: str = "shortcut"
SOURCE_ENGINE: str = "source_engine"
SPREADSHEET: str = "spreadsheet"
TEXT: str = "text"
VIDEO: str = "video"
class MediaCategory:
"""An object representing a category of media. Includes a MediaType identifier,
extensions set, and IANA status flag.
Args:
media_type (MediaType): The MediaType Enum representing this category.
extensions (set[str]): The set of file extensions associated with this category.
Includes leading ".", all lowercase, and does not need to be unique to this category.
is_iana (bool): Represents whether or not this is an IANA registered category.
"""
def __init__(
self,
media_type: MediaType,
extensions: set[str],
is_iana: bool = False,
) -> None:
self.media_type: MediaType = media_type
self.extensions: set[str] = extensions
self.is_iana: bool = is_iana
class MediaCategories:
"""Contains pre-made MediaCategory objects as well as methods to interact with them."""
# These sets are used either individually or together to form the final sets
# for the MediaCategory(s).
# These sets may be combined and are NOT 1:1 with the final categories.
_ADOBE_PHOTOSHOP_SET: set[str] = {
".pdd",
".psb",
".psd",
}
_AFFINITY_PHOTO_SET: set[str] = {".afphoto"}
_ARCHIVE_SET: set[str] = {
".7z",
".gz",
".rar",
".s7z",
".tar",
".tgz",
".zip",
}
_AUDIO_MIDI_SET: set[str] = {
".mid",
".midi",
}
_AUDIO_SET: set[str] = {
".aac",
".aif",
".aiff",
".alac",
".flac",
".m4a",
".m4p",
".mp3",
".mpeg4",
".ogg",
".wav",
".wma",
}
_BLENDER_SET: set[str] = {
".blen_tc",
".blend",
".blend1",
".blend10",
".blend11",
".blend12",
".blend13",
".blend14",
".blend15",
".blend16",
".blend17",
".blend18",
".blend19",
".blend2",
".blend20",
".blend21",
".blend22",
".blend23",
".blend24",
".blend25",
".blend26",
".blend27",
".blend28",
".blend29",
".blend3",
".blend30",
".blend31",
".blend32",
".blend4",
".blend5",
".blend6",
".blend7",
".blend8",
".blend9",
}
_DATABASE_SET: set[str] = {
".accdb",
".mdb",
".sqlite",
}
_DISK_IMAGE_SET: set[str] = {".bios", ".dmg", ".iso"}
_DOCUMENT_SET: set[str] = {
".doc",
".docm",
".docx",
".dot",
".dotm",
".dotx",
".odt",
".pages",
".pdf",
".rtf",
".tex",
".wpd",
".wps",
}
_FONT_SET: set[str] = {
".fon",
".otf",
".ttc",
".ttf",
".woff",
".woff2",
}
_IMAGE_ANIMATED_SET: set[str] = {
".apng",
".gif",
".webp",
".jxl",
}
_IMAGE_RAW_SET: set[str] = {
".arw",
".cr2",
".cr3",
".crw",
".dng",
".nef",
".orf",
".raf",
".raw",
".rw2",
}
_IMAGE_VECTOR_SET: set[str] = {".svg"}
_IMAGE_SET: set[str] = {
".apng",
".avif",
".bmp",
".exr",
".gif",
".heic",
".heif",
".j2k",
".jfif",
".jp2",
".jpeg_large",
".jpeg",
".jpg_large",
".jpg",
".jpg2",
".jxl",
".png",
".psb",
".psd",
".tif",
".tiff",
".webp",
}
_INSTALLER_SET: set[str] = {".appx", ".msi", ".msix"}
_MATERIAL_SET: set[str] = {".mtl"}
_MODEL_SET: set[str] = {".3ds", ".fbx", ".obj", ".stl"}
_PACKAGE_SET: set[str] = {
".aab",
".akp",
".apk",
".apkm",
".apks",
".pkg",
".xapk",
}
_PDF_SET: set[str] = {
".pdf",
}
_PLAINTEXT_SET: set[str] = {
".bat",
".css",
".csv",
".htm",
".html",
".ini",
".js",
".json",
".jsonc",
".md",
".php",
".plist",
".prefs",
".sh",
".ts",
".txt",
".xml",
".vmt",
".fgd",
".nut",
".cfg",
".conf",
".vdf",
".vcfg",
".gi",
".inf",
".vqlayout",
".qss",
".vsc",
".kv3",
".vsnd_template",
}
_PRESENTATION_SET: set[str] = {
".key",
".odp",
".ppt",
".pptx",
}
_PROGRAM_SET: set[str] = {".app", ".exe"}
_SOURCE_ENGINE_SET: set[str] = {
".vtf",
}
_SHORTCUT_SET: set[str] = {".desktop", ".lnk", ".url"}
_SPREADSHEET_SET: set[str] = {
".csv",
".numbers",
".ods",
".xls",
".xlsx",
}
_VIDEO_SET: set[str] = {
".3gp",
".avi",
".flv",
".gifv",
".hevc",
".m4p",
".m4v",
".mkv",
".mov",
".mp4",
".webm",
".wmv",
}
ADOBE_PHOTOSHOP_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.ADOBE_PHOTOSHOP,
extensions=_ADOBE_PHOTOSHOP_SET,
is_iana=False,
)
AFFINITY_PHOTO_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.AFFINITY_PHOTO,
extensions=_AFFINITY_PHOTO_SET,
is_iana=False,
)
ARCHIVE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.ARCHIVE,
extensions=_ARCHIVE_SET,
is_iana=False,
)
AUDIO_MIDI_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.AUDIO_MIDI,
extensions=_AUDIO_MIDI_SET,
is_iana=False,
)
AUDIO_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.AUDIO,
extensions=_AUDIO_SET | _AUDIO_MIDI_SET,
is_iana=True,
)
BLENDER_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.BLENDER,
extensions=_BLENDER_SET,
is_iana=False,
)
DATABASE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.DATABASE,
extensions=_DATABASE_SET,
is_iana=False,
)
DISK_IMAGE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.DISK_IMAGE,
extensions=_DISK_IMAGE_SET,
is_iana=False,
)
DOCUMENT_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.DOCUMENT,
extensions=_DOCUMENT_SET,
is_iana=False,
)
FONT_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.FONT,
extensions=_FONT_SET,
is_iana=True,
)
IMAGE_ANIMATED_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.IMAGE_ANIMATED,
extensions=_IMAGE_ANIMATED_SET,
is_iana=False,
)
IMAGE_RAW_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.IMAGE_RAW,
extensions=_IMAGE_RAW_SET,
is_iana=False,
)
IMAGE_VECTOR_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.IMAGE_VECTOR,
extensions=_IMAGE_VECTOR_SET,
is_iana=False,
)
IMAGE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.IMAGE,
extensions=_IMAGE_SET | _IMAGE_RAW_SET | _IMAGE_VECTOR_SET,
is_iana=True,
)
INSTALLER_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.INSTALLER,
extensions=_INSTALLER_SET,
is_iana=False,
)
MATERIAL_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.MATERIAL,
extensions=_MATERIAL_SET,
is_iana=False,
)
MODEL_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.MODEL,
extensions=_MODEL_SET,
is_iana=True,
)
PACKAGE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.PACKAGE,
extensions=_PACKAGE_SET,
is_iana=False,
)
PDF_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.PDF,
extensions=_PDF_SET,
is_iana=False,
)
PLAINTEXT_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.PLAINTEXT,
extensions=_PLAINTEXT_SET,
is_iana=False,
)
PRESENTATION_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.PRESENTATION,
extensions=_PRESENTATION_SET,
is_iana=False,
)
PROGRAM_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.PROGRAM,
extensions=_PROGRAM_SET,
is_iana=False,
)
SHORTCUT_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.SHORTCUT,
extensions=_SHORTCUT_SET,
is_iana=False,
)
SOURCE_ENGINE_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.SOURCE_ENGINE,
extensions=_SOURCE_ENGINE_SET,
is_iana=False,
)
SPREADSHEET_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.SPREADSHEET,
extensions=_SPREADSHEET_SET,
is_iana=False,
)
TEXT_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.TEXT,
extensions=_DOCUMENT_SET | _PLAINTEXT_SET,
is_iana=True,
)
VIDEO_TYPES: MediaCategory = MediaCategory(
media_type=MediaType.VIDEO,
extensions=_VIDEO_SET,
is_iana=True,
)
ALL_CATEGORIES: list[MediaCategory] = [
ADOBE_PHOTOSHOP_TYPES,
AFFINITY_PHOTO_TYPES,
ARCHIVE_TYPES,
AUDIO_MIDI_TYPES,
AUDIO_TYPES,
BLENDER_TYPES,
DATABASE_TYPES,
DISK_IMAGE_TYPES,
DOCUMENT_TYPES,
FONT_TYPES,
IMAGE_ANIMATED_TYPES,
IMAGE_RAW_TYPES,
IMAGE_TYPES,
IMAGE_VECTOR_TYPES,
INSTALLER_TYPES,
MATERIAL_TYPES,
MODEL_TYPES,
PACKAGE_TYPES,
PDF_TYPES,
PLAINTEXT_TYPES,
PRESENTATION_TYPES,
PROGRAM_TYPES,
SHORTCUT_TYPES,
SOURCE_ENGINE_TYPES,
SPREADSHEET_TYPES,
TEXT_TYPES,
VIDEO_TYPES,
]
@staticmethod
def get_types(ext: str, mime_fallback: bool = False) -> set[MediaType]:
"""Returns a set of MediaTypes given a file extension.
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.
"""
types: set[MediaType] = set()
mime_guess: bool = False
for cat in MediaCategories.ALL_CATEGORIES:
if ext in cat.extensions:
types.add(cat.media_type)
elif mime_fallback and cat.is_iana:
type: str = mimetypes.guess_type(Path("x" + ext), strict=False)[0]
if type and type.startswith(cat.media_type.value):
types.add(cat.media_type)
mime_guess = True
# logging.info(
# f"({ext}) Media Categories Found: {[x.value for x in types]}{' (MIME)' if mime_guess else ''}"
# )
return types

View File

@@ -13,7 +13,7 @@ class ColorType(int, Enum):
DARK_ACCENT = 4
_TAG_COLORS = {
_TAG_COLORS: dict = {
"": {
ColorType.PRIMARY: "#1e1e1e",
ColorType.TEXT: ColorType.LIGHT_ACCENT,
@@ -277,13 +277,58 @@ _TAG_COLORS = {
},
}
_UI_COLORS: dict = {
"": {
ColorType.PRIMARY: "#333333",
ColorType.BORDER: "#555555",
ColorType.LIGHT_ACCENT: "#FFFFFF",
ColorType.DARK_ACCENT: "#1e1e1e",
},
"red": {
ColorType.PRIMARY: "#e22c3c",
ColorType.BORDER: "#e54252",
ColorType.LIGHT_ACCENT: "#f39caa",
ColorType.DARK_ACCENT: "#440d12",
},
"green": {
ColorType.PRIMARY: "#28bb48",
ColorType.BORDER: "#43c568",
ColorType.LIGHT_ACCENT: "#DDFFCC",
ColorType.DARK_ACCENT: "#0d3828",
},
"purple": {
ColorType.PRIMARY: "#C76FF3",
ColorType.BORDER: "#c364f2",
ColorType.LIGHT_ACCENT: "#EFD4FB",
ColorType.DARK_ACCENT: "#3E1555",
},
"theme_dark": {
ColorType.PRIMARY: "#333333",
ColorType.BORDER: "#555555",
ColorType.LIGHT_ACCENT: "#FFFFFF",
ColorType.DARK_ACCENT: "#1e1e1e",
},
"theme_light": {
ColorType.PRIMARY: "#FFFFFF",
ColorType.BORDER: "#333333",
ColorType.LIGHT_ACCENT: "#999999",
ColorType.DARK_ACCENT: "#888888",
},
}
def get_tag_color(type, color):
def get_tag_color(color_type, color):
color = color.lower()
try:
if type == ColorType.TEXT:
return get_tag_color(_TAG_COLORS[color][type], color)
if color_type == ColorType.TEXT:
return get_tag_color(_TAG_COLORS[color][color_type], color)
else:
return _TAG_COLORS[color][type]
return _TAG_COLORS[color][color_type]
except KeyError:
return "#FF00FF"
def get_ui_color(color_type: ColorType, color: str):
"""Returns a hex value given a color name and ColorType."""
color = color.lower()
return _UI_COLORS.get(color).get(color_type)

View File

@@ -6,6 +6,8 @@
import json
import os
from pathlib import Path
from enum import Enum
from src.core.library import Entry, Library
from src.core.constants import TS_FOLDER_NAME, TEXT_FIELDS
@@ -20,7 +22,7 @@ class TagStudioCore:
def __init__(self):
self.lib: Library = Library()
def get_gdl_sidecar(self, filepath: str, source: str = "") -> dict:
def get_gdl_sidecar(self, filepath: str | Path, source: str = "") -> dict:
"""
Attempts to open and dump a Gallery-DL Sidecar sidecar file for
the filepath.\n Returns a formatted object with notable values or an
@@ -28,16 +30,19 @@ class TagStudioCore:
"""
json_dump = {}
info = {}
_filepath: Path = Path(filepath)
_filepath = _filepath.parent / (_filepath.name + ".json")
# NOTE: This fixes an unknown (recent?) bug in Gallery-DL where Instagram sidecar
# files may be downloaded with indices starting at 1 rather than 0, unlike the posts.
# This may only occur with sidecar files that are downloaded separate from posts.
if source == "instagram":
if not os.path.isfile(os.path.normpath(filepath + ".json")):
filepath = filepath[:-16] + "1" + filepath[-15:]
if not _filepath.is_file():
newstem = _filepath.stem[:-16] + "1" + _filepath.stem[-15:]
_filepath = _filepath.parent / (newstem + ".json")
try:
with open(os.path.normpath(filepath + ".json"), "r", encoding="utf8") as f:
with open(_filepath, "r", encoding="utf8") as f:
json_dump = json.load(f)
if json_dump:
@@ -101,19 +106,17 @@ class TagStudioCore:
def match_conditions(self, entry_id: int) -> None:
"""Matches defined conditions against a file to add Entry data."""
cond_file = os.path.normpath(
f"{self.lib.library_dir}/{TS_FOLDER_NAME}/conditions.json"
)
cond_file = self.lib.library_dir / TS_FOLDER_NAME / "conditions.json"
# TODO: Make this stored somewhere better instead of temporarily in this JSON file.
entry: Entry = self.lib.get_entry(entry_id)
try:
if os.path.isfile(cond_file):
if cond_file.is_file():
with open(cond_file, "r", encoding="utf8") as f:
json_dump = json.load(f)
for c in json_dump["conditions"]:
match: bool = False
for path_c in c["path_conditions"]:
if os.path.normpath(path_c) in entry.path:
if str(Path(path_c).resolve()) in str(entry.path):
match = True
break
if match:
@@ -180,7 +183,7 @@ class TagStudioCore:
"""
try:
entry = self.lib.get_entry(entry_id)
stubs = entry.filename.rsplit("_", 3)
stubs = str(entry.filename).rsplit("_", 3)
# print(stubs)
# source, author = os.path.split(entry.path)
url = f"www.twitter.com/{stubs[0]}/status/{stubs[-3]}/photo/{stubs[-2]}"
@@ -195,7 +198,7 @@ class TagStudioCore:
"""
try:
entry = self.lib.get_entry(entry_id)
stubs = entry.filename.rsplit("_", 2)
stubs = str(entry.filename).rsplit("_", 2)
# stubs[0] = stubs[0].replace(f"{author}_", '', 1)
# print(stubs)
# NOTE: Both Instagram usernames AND their ID can have underscores in them,

View File

@@ -0,0 +1,27 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from chardet.universaldetector import UniversalDetector
from pathlib import Path
def detect_char_encoding(filepath: Path) -> str | None:
"""
Attempts to detect the character encoding of a text file.
Args:
filepath (Path): The path of the text file to analyze.
Returns:
str | None: The detected character encoding, if any.
"""
detector = UniversalDetector()
with open(filepath, "rb") as text_file:
for line in text_file.readlines():
detector.feed(line)
if detector.done:
break
detector.close()
return detector.result["encoding"]

View File

@@ -0,0 +1,109 @@
#!/usr/bin/env python3
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
## This file is a modified script that gets the thumbnail data stored in a blend file
import struct
from PIL import (
Image,
ImageOps,
)
import gzip
import os
def blend_extract_thumb(path):
REND = b"REND"
TEST = b"TEST"
blendfile = open(path, "rb")
head = blendfile.read(12)
if head[0:2] == b"\x1f\x8b": # gzip magic
blendfile.close()
blendfile = gzip.GzipFile("", "rb", 0, open(path, "rb"))
head = blendfile.read(12)
if not head.startswith(b"BLENDER"):
blendfile.close()
return None, 0, 0
is_64_bit = head[7] == b"-"[0]
# true for PPC, false for X86
is_big_endian = head[8] == b"V"[0]
# blender pre 2.5 had no thumbs
if head[9:11] <= b"24":
return None, 0, 0
sizeof_bhead = 24 if is_64_bit else 20
int_endian = ">i" if is_big_endian else "<i"
int_endian_pair = int_endian + "i"
while True:
bhead = blendfile.read(sizeof_bhead)
if len(bhead) < sizeof_bhead:
return None, 0, 0
code = bhead[:4]
length = struct.unpack(int_endian, bhead[4:8])[0] # 4 == sizeof(int)
if code == REND:
blendfile.seek(length, os.SEEK_CUR)
else:
break
if code != TEST:
return None, 0, 0
try:
x, y = struct.unpack(int_endian_pair, blendfile.read(8)) # 8 == sizeof(int) * 2
except struct.error:
return None, 0, 0
length -= 8 # sizeof(int) * 2
if length != x * y * 4:
return None, 0, 0
image_buffer = blendfile.read(length)
if len(image_buffer) != length:
return None, 0, 0
return image_buffer, x, y
def blend_thumb(file_in):
buf, width, height = blend_extract_thumb(file_in)
image = Image.frombuffer(
"RGBA",
(width, height),
buf,
)
image = ImageOps.flip(image)
return image

View File

@@ -0,0 +1,64 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PIL import Image
from PySide6.QtCore import Qt
from PySide6.QtGui import QGuiApplication
from src.qt.helpers.gradient import linear_gradient
# TODO: Consolidate the built-in QT theme values with the values
# here, in enums.py, and in palette.py.
_THEME_DARK_FG: str = "#FFFFFF77"
_THEME_LIGHT_FG: str = "#000000DD"
_THEME_DARK_BG: str = "#000000DD"
_THEME_LIGHT_BG: str = "#FFFFFF55"
def theme_fg_overlay(image: Image.Image, use_alpha: bool = True) -> Image.Image:
"""
Overlay the foreground theme color onto an image.
Args:
image (Image): The PIL Image object to apply an overlay to.
"""
dark_fg: str = _THEME_DARK_FG[:-2] if not use_alpha else _THEME_DARK_FG
light_fg: str = _THEME_LIGHT_FG[:-2] if not use_alpha else _THEME_LIGHT_FG
overlay_color = (
dark_fg
if QGuiApplication.styleHints().colorScheme() is Qt.ColorScheme.Dark
else light_fg
)
im = Image.new(mode="RGBA", size=image.size, color=overlay_color)
return _apply_overlay(image, im)
def gradient_overlay(image: Image.Image, gradient=list[str]) -> Image.Image:
"""
Overlay a color gradient onto an image.
Args:
image (Image): The PIL Image object to apply an overlay to.
gradient (list[str): A list of string hex color codes for use as
the colors of the gradient.
"""
im: Image.Image = _apply_overlay(image, linear_gradient(image.size, gradient))
return im
def _apply_overlay(image: Image.Image, overlay: Image.Image) -> Image.Image:
"""
Internal method to apply an overlay on top of an image, using
the image's alpha channel as a mask.
Args:
image (Image): The PIL Image object to apply an overlay to.
overlay (Image): The PIL Image object to act as the overlay contents.
"""
im: Image.Image = Image.new(mode="RGBA", size=image.size, color="#00000000")
im.paste(overlay, (0, 0), mask=image)
return im

View File

@@ -0,0 +1,30 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import logging
from pathlib import Path
from send2trash import send2trash
logging.basicConfig(format="%(message)s", level=logging.INFO)
def delete_file(path: str | Path) -> bool:
"""Sends a file to the system trash.
Args:
path (str | Path): The path of the file to delete.
"""
_path = Path(path)
try:
logging.info(f"[delete_file] Sending to Trash: {_path}")
send2trash(_path)
return True
except PermissionError as e:
logging.error(f"[delete_file][ERROR] PermissionError: {e}")
except FileNotFoundError:
logging.error(f"[delete_file][ERROR] File Not Found: {_path}")
except Exception as e:
logging.error(e)
return False

View File

@@ -8,6 +8,7 @@ import subprocess
import shutil
import sys
import traceback
from pathlib import Path
from PySide6.QtWidgets import QLabel
from PySide6.QtCore import Qt
@@ -19,7 +20,7 @@ INFO = f"[INFO]"
logging.basicConfig(format="%(message)s", level=logging.INFO)
def open_file(path: str, file_manager: bool = False):
def open_file(path: str | Path, file_manager: bool = False):
"""Open a file in the default application or file explorer.
Args:
@@ -27,13 +28,14 @@ def open_file(path: str, file_manager: bool = False):
file_manager (bool, optional): Whether to open the file in the file manager (e.g. Finder on macOS).
Defaults to False.
"""
logging.info(f"Opening file: {path}")
if not os.path.exists(path):
logging.error(f"File not found: {path}")
_path = str(path)
logging.info(f"Opening file: {_path}")
if not os.path.exists(_path):
logging.error(f"File not found: {_path}")
return
try:
if sys.platform == "win32":
normpath = os.path.normpath(path)
normpath = os.path.normpath(_path)
if file_manager:
command_name = "explorer"
command_args = '/select,"' + normpath + '"'
@@ -59,7 +61,7 @@ def open_file(path: str, file_manager: bool = False):
else:
if sys.platform == "darwin":
command_name = "open"
command_args = [path]
command_args = [_path]
if file_manager:
# will reveal in Finder
command_args.append("-R")
@@ -73,12 +75,12 @@ def open_file(path: str, file_manager: bool = False):
"--type=method_call",
"/org/freedesktop/FileManager1",
"org.freedesktop.FileManager1.ShowItems",
f"array:string:file://{path}",
f"array:string:file://{_path}",
"string:",
]
else:
command_name = "xdg-open"
command_args = [path]
command_args = [_path]
command = shutil.which(command_name)
if command is not None:
subprocess.Popen([command] + command_args, close_fds=True)
@@ -89,21 +91,21 @@ def open_file(path: str, file_manager: bool = False):
class FileOpenerHelper:
def __init__(self, filepath: str):
def __init__(self, filepath: str | Path):
"""Initialize the FileOpenerHelper.
Args:
filepath (str): The path to the file to open.
"""
self.filepath = filepath
self.filepath = str(filepath)
def set_filepath(self, filepath: str):
def set_filepath(self, filepath: str | Path):
"""Set the filepath to open.
Args:
filepath (str): The path to the file to open.
"""
self.filepath = filepath
self.filepath = str(filepath)
def open_file(self):
"""Open the file in the default application."""

View File

@@ -0,0 +1,31 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import ffmpeg
from pathlib import Path
from src.qt.helpers.vendored.ffmpeg import _probe
def is_readable_video(filepath: Path | str):
"""Test if a video is in a readable format. Examples of unreadable videos
include files with undetermined codecs and DRM-protected content.
Args:
filepath (Path | str):
"""
try:
probe = _probe(Path(filepath))
for stream in probe["streams"]:
# DRM check
if stream.get("codec_tag_string") in [
"drma",
"drms",
"drmi",
]:
return False
except ffmpeg.Error:
return False
return True

View File

@@ -2,22 +2,14 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PIL import Image, ImageEnhance, ImageChops
from PIL import Image
def four_corner_gradient_background(image: Image.Image, adj_size, mask, hl):
if image.size != (adj_size, adj_size):
# Old 1 color method.
# bg_col = image.copy().resize((1, 1)).getpixel((0,0))
# bg = Image.new(mode='RGB',size=(adj_size,adj_size),color=bg_col)
# bg.thumbnail((1, 1))
# bg = bg.resize((adj_size,adj_size), resample=Image.Resampling.NEAREST)
# Small gradient background. Looks decent, and is only a one-liner.
# bg = image.copy().resize((2, 2), resample=Image.Resampling.BILINEAR).resize((adj_size,adj_size),resample=Image.Resampling.BILINEAR)
def four_corner_gradient(
image: Image.Image, size: tuple[int, int], mask: Image.Image
) -> Image.Image:
if image.size != size:
# Four-Corner Gradient Background.
# Not exactly a one-liner, but it's (subjectively) really cool.
tl = image.getpixel((0, 0))
tr = image.getpixel(((image.size[0] - 1), 0))
bl = image.getpixel((0, (image.size[1] - 1)))
@@ -27,24 +19,36 @@ def four_corner_gradient_background(image: Image.Image, adj_size, mask, hl):
bg.paste(tr, (1, 0, 2, 2))
bg.paste(bl, (0, 1, 2, 2))
bg.paste(br, (1, 1, 2, 2))
bg = bg.resize((adj_size, adj_size), resample=Image.Resampling.BICUBIC)
bg = bg.resize(size, resample=Image.Resampling.BICUBIC)
bg.paste(
image,
box=(
(adj_size - image.size[0]) // 2,
(adj_size - image.size[1]) // 2,
(size[0] - image.size[0]) // 2,
(size[1] - image.size[1]) // 2,
),
)
bg.putalpha(mask)
final = bg
final = Image.new("RGBA", bg.size, (0, 0, 0, 0))
final.paste(bg, mask=mask.getchannel(0))
else:
image.putalpha(mask)
final = image
final = Image.new("RGBA", size, (0, 0, 0, 0))
final.paste(image, mask=mask.getchannel(0))
if final.mode != "RGBA":
final = final.convert("RGBA")
hl_soft = hl.copy()
hl_soft.putalpha(ImageEnhance.Brightness(hl.getchannel(3)).enhance(0.5))
final.paste(ImageChops.soft_light(final, hl_soft), mask=hl_soft.getchannel(3))
return final
def linear_gradient(
size=tuple[int, int],
colors=list[str],
interpolation: Image.Resampling = Image.Resampling.BICUBIC,
) -> Image.Image:
seed: Image.Image = Image.new(mode="RGBA", size=(len(colors), 1), color="#000000")
for i, color in enumerate(colors):
c_im: Image.Image = Image.new(mode="RGBA", size=(1, 1), color=color)
seed.paste(c_im, (i, 0))
gradient: Image.Image = seed.resize(size, resample=interpolation)
return gradient

View File

@@ -0,0 +1,16 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtWidgets import QPushButton
class QPushButtonWrapper(QPushButton):
"""
This is a customized implementation of the PySide6 QPushButton that allows to suppress the warning that is triggered
by disconnecting a signal that is not currently connected.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_connected = False

View File

@@ -0,0 +1,31 @@
# Based on the implementation by eyllanesc:
# https://stackoverflow.com/questions/54230005/qmovie-with-border-radius
# Licensed under the Creative Commons CC BY-SA 4.0 License:
# https://creativecommons.org/licenses/by-sa/4.0/
# Modified for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtGui import QBrush, QColor, QPainter, QPixmap
from PySide6.QtWidgets import (
QProxyStyle,
)
class RoundedPixmapStyle(QProxyStyle):
def __init__(self, radius=8):
super().__init__()
self._radius = radius
def drawItemPixmap(self, painter, rectangle, alignment, pixmap):
painter.save()
pix = QPixmap(pixmap.size())
pix.fill(QColor("transparent"))
p = QPainter(pix)
p.setBrush(QBrush(pixmap))
p.setPen(QColor("transparent"))
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.drawRoundedRect(pixmap.rect(), self._radius, self._radius)
p.end()
super(RoundedPixmapStyle, self).drawItemPixmap(
painter, rectangle, alignment, pix
)
painter.restore()

View File

@@ -0,0 +1,64 @@
import subprocess
import sys
def promptless_Popen(
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,
restore_signals=True,
start_new_session=False,
pass_fds=(),
*,
group=None,
extra_groups=None,
user=None,
umask=-1,
encoding=None,
errors=None,
text=None,
pipesize=-1,
process_group=None,
):
creation_flags = 0
if sys.platform == "win32":
creation_flags = subprocess.CREATE_NO_WINDOW
return subprocess.Popen(
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,
universal_newlines=universal_newlines,
startupinfo=startupinfo,
creationflags=creation_flags,
restore_signals=restore_signals,
start_new_session=start_new_session,
pass_fds=pass_fds,
group=group,
extra_groups=extra_groups,
user=user,
umask=umask,
encoding=encoding,
errors=errors,
text=text,
pipesize=pipesize,
process_group=process_group,
)

View File

@@ -0,0 +1,51 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PIL import Image, ImageDraw, ImageFont
def wrap_line( # type: ignore
text: str,
font: ImageFont.ImageFont,
width: int = 256,
draw: ImageDraw.ImageDraw = None,
) -> int:
"""
Takes in a single line and returns the index it should be broken up at but
it only splits one Time
"""
if draw is None:
bg = Image.new("RGB", (width, width), color="#1e1e1e")
draw = ImageDraw.Draw(bg)
if draw.textlength(text, font=font) > width:
for i in range(
int(len(text) / int(draw.textlength(text, font=font)) * width) - 2,
0,
-1,
):
if draw.textlength(text[:i], font=font) < width:
return i
else:
return -1
def wrap_full_text(
text: str,
font: ImageFont.ImageFont,
width: int = 256,
draw: ImageDraw.ImageDraw = None,
) -> str:
"""
Takes in a string and breaks it up to fit in the canvas given accounts for kerning and font size etc.
"""
lines = []
i = 0
last_i = 0
while wrap_line(text[i:], font=font, width=width, draw=draw) > 0:
i = wrap_line(text[i:], font=font, width=width, draw=draw) + last_i
lines.append(text[last_i:i])
last_i = i
lines.append(text[last_i:])
text_wrapped = "\n".join(lines)
return text_wrapped

View File

@@ -0,0 +1,34 @@
# Copyright (C) 2022 Karl Kroening (kkroening).
# Licensed under the GPL-3.0 License.
# Vendored from ffmpeg-python and ffmpeg-python PR#790 by amamic1803
import subprocess
import json
import sys
import ffmpeg
from src.qt.helpers.silent_popen import promptless_Popen
def _probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
``stderr`` property of the exception.
"""
args = [cmd, '-show_format', '-show_streams', '-of', 'json']
args += ffmpeg._utils.convert_kwargs_to_cmd_line_args(kwargs)
args += [filename]
# PATCHED
p = promptless_Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
communicate_kwargs = {}
if timeout is not None:
communicate_kwargs['timeout'] = timeout
out, err = p.communicate(**communicate_kwargs)
if p.returncode != 0:
raise ffmpeg.Error('ffprobe', out, err)
return json.loads(out.decode('utf-8'))

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
import json
import re
import subprocess
from pydub.utils import (
get_prober_name,
fsdecode,
_fd_or_path_or_tempfile,
get_extra_info,
)
from src.qt.helpers.silent_popen import promptless_Popen
def _mediainfo_json(filepath, read_ahead_limit=-1):
"""Return json dictionary with media info(codec, duration, size, bitrate...) from filepath
"""
prober = get_prober_name()
command_args = [
"-v", "info",
"-show_format",
"-show_streams",
]
try:
command_args += [fsdecode(filepath)]
stdin_parameter = None
stdin_data = None
except TypeError:
if prober == 'ffprobe':
command_args += ["-read_ahead_limit", str(read_ahead_limit),
"cache:pipe:0"]
else:
command_args += ["-"]
stdin_parameter = subprocess.PIPE
file, close_file = _fd_or_path_or_tempfile(filepath, 'rb', tempfile=False)
file.seek(0)
stdin_data = file.read()
if close_file:
file.close()
command = [prober, '-of', 'json'] + command_args
# PATCHED
res = promptless_Popen(command, stdin=stdin_parameter, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, stderr = res.communicate(input=stdin_data)
output = output.decode("utf-8", 'ignore')
stderr = stderr.decode("utf-8", 'ignore')
try:
info = json.loads(output)
except json.decoder.JSONDecodeError:
# If ffprobe didn't give any information, just return it
# (for example, because the file doesn't exist)
return None
if not info:
return info
extra_info = get_extra_info(stderr)
audio_streams = [x for x in info['streams'] if x['codec_type'] == 'audio']
if len(audio_streams) == 0:
return info
# We just operate on the first audio stream in case there are more
stream = audio_streams[0]
def set_property(stream, prop, value):
if prop not in stream or stream[prop] == 0:
stream[prop] = value
for token in extra_info[stream['index']]:
m = re.match(r'([su]([0-9]{1,2})p?) \(([0-9]{1,2}) bit\)$', token)
m2 = re.match(r'([su]([0-9]{1,2})p?)( \(default\))?$', token)
if m:
set_property(stream, 'sample_fmt', m.group(1))
set_property(stream, 'bits_per_sample', int(m.group(2)))
set_property(stream, 'bits_per_raw_sample', int(m.group(3)))
elif m2:
set_property(stream, 'sample_fmt', m2.group(1))
set_property(stream, 'bits_per_sample', int(m2.group(2)))
set_property(stream, 'bits_per_raw_sample', int(m2.group(2)))
elif re.match(r'(flt)p?( \(default\))?$', token):
set_property(stream, 'sample_fmt', token)
set_property(stream, 'bits_per_sample', 32)
set_property(stream, 'bits_per_raw_sample', 32)
elif re.match(r'(dbl)p?( \(default\))?$', token):
set_property(stream, 'sample_fmt', token)
set_property(stream, 'bits_per_sample', 64)
set_property(stream, 'bits_per_raw_sample', 64)
return info

View File

@@ -12,215 +12,227 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtCore import (QCoreApplication, QMetaObject, QRect,
QSize, Qt)
from PySide6.QtGui import (QFont, QAction)
import logging
import typing
from PySide6.QtCore import (QCoreApplication, QMetaObject, QRect,QSize, Qt)
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (QComboBox, QFrame, QGridLayout,
QHBoxLayout, QVBoxLayout, QLayout, QLineEdit, QMainWindow,
QPushButton, QScrollArea, QSizePolicy,
QStatusBar, QWidget, QSplitter)
QHBoxLayout, QVBoxLayout, QLayout, QLineEdit, QMainWindow,
QPushButton, QScrollArea, QSizePolicy,
QStatusBar, QWidget, QSplitter, QCheckBox,
QSpacerItem)
from src.qt.pagination import Pagination
from src.qt.widgets.landing import LandingWidget
# Only import for type checking/autocompletion, will not be imported at runtime.
if typing.TYPE_CHECKING:
from src.qt.ts_qt import QtDriver
logging.basicConfig(format="%(message)s", level=logging.INFO)
class Ui_MainWindow(QMainWindow):
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setupUi(self)
def __init__(self, driver: "QtDriver", parent=None) -> None:
super().__init__(parent)
self.driver: "QtDriver" = driver
self.setupUi(self)
# self.setWindowFlag(Qt.WindowType.NoDropShadowWindowHint, True)
# self.setWindowFlag(Qt.WindowType.WindowTransparentForInput, False)
# # self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
# self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
# NOTE: These are old attempts to allow for a translucent/acrylic
# window effect. This may be attempted again in the future.
# self.setWindowFlag(Qt.WindowType.NoDropShadowWindowHint, True)
# self.setWindowFlag(Qt.WindowType.WindowTransparentForInput, False)
# # self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
# self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
# self.windowFX = WindowEffect()
# self.windowFX.setAcrylicEffect(self.winId(), isEnableShadow=False)
# self.windowFX = WindowEffect()
# self.windowFX.setAcrylicEffect(self.winId(), isEnableShadow=False)
# # self.setStyleSheet(
# # 'background:#EE000000;'
# # )
# # self.setStyleSheet(
# # 'background:#EE000000;'
# # )
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")
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)
# Search type selector
self.comboBox_2 = QComboBox(self.centralwidget)
self.comboBox_2.setMinimumSize(QSize(165, 0))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.horizontalLayout_3.addWidget(self.comboBox_2)
# Thumbnail Size placeholder
self.thumb_size_combobox = QComboBox(self.centralwidget)
self.thumb_size_combobox.setObjectName(u"thumbSizeComboBox")
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.horizontalLayout_3.addWidget(self.thumb_size_combobox)
self.gridLayout.addLayout(self.horizontalLayout_3, 5, 0, 1, 1)
self.splitter = QSplitter()
self.splitter.setObjectName(u"splitter")
self.splitter.setHandleWidth(12)
self.splitter = QSplitter()
self.splitter.setObjectName(u"splitter")
self.splitter.setHandleWidth(12)
self.frame_container = QWidget()
self.frame_layout = QVBoxLayout(self.frame_container)
self.frame_layout.setSpacing(0)
self.frame_container = QWidget()
self.frame_layout = QVBoxLayout(self.frame_container)
self.frame_layout.setSpacing(0)
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.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.page_bar_controls = QWidget()
# self.page_bar_controls.setStyleSheet('background:blue;')
# self.page_bar_controls.setMinimumHeight(32)
self.pagination = Pagination()
self.frame_layout.addWidget(self.pagination)
self.pagination = Pagination()
self.frame_layout.addWidget(self.pagination)
self.horizontalLayout.addWidget(self.splitter)
self.splitter.addWidget(self.frame_container)
self.splitter.setStretchFactor(0, 1)
# self.frame_layout.addWidget(self.page_bar_controls)
# self.frame_layout.addWidget(self.page_bar_controls)
self.gridLayout.addLayout(self.horizontalLayout, 10, 0, 1, 1)
self.horizontalLayout.addWidget(self.splitter)
self.splitter.addWidget(self.frame_container)
self.splitter.setStretchFactor(0, 1)
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))
font = QFont()
font.setPointSize(14)
font.setBold(True)
self.backButton.setFont(font)
self.gridLayout.addLayout(self.horizontalLayout, 10, 0, 1, 1)
self.horizontalLayout_2.addWidget(self.backButton)
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))
font = QFont()
font.setPointSize(14)
font.setBold(True)
self.backButton.setFont(font)
self.forwardButton = QPushButton(self.centralwidget)
self.forwardButton.setObjectName(u"forwardButton")
self.forwardButton.setMinimumSize(QSize(0, 32))
self.forwardButton.setMaximumSize(QSize(32, 16777215))
font1 = QFont()
font1.setPointSize(14)
font1.setBold(True)
font1.setKerning(True)
self.forwardButton.setFont(font1)
self.horizontalLayout_2.addWidget(self.backButton)
self.horizontalLayout_2.addWidget(self.forwardButton)
self.forwardButton = QPushButton(self.centralwidget)
self.forwardButton.setObjectName(u"forwardButton")
self.forwardButton.setMinimumSize(QSize(0, 32))
self.forwardButton.setMaximumSize(QSize(32, 16777215))
font1 = QFont()
font1.setPointSize(14)
font1.setBold(True)
font1.setKerning(True)
self.forwardButton.setFont(font1)
self.searchField = QLineEdit(self.centralwidget)
self.searchField.setObjectName(u"searchField")
self.searchField.setMinimumSize(QSize(0, 32))
font2 = QFont()
font2.setPointSize(11)
font2.setBold(False)
self.searchField.setFont(font2)
self.horizontalLayout_2.addWidget(self.forwardButton)
self.horizontalLayout_2.addWidget(self.searchField)
self.searchField = QLineEdit(self.centralwidget)
self.searchField.setObjectName(u"searchField")
self.searchField.setMinimumSize(QSize(0, 32))
font2 = QFont()
font2.setPointSize(11)
font2.setBold(False)
self.searchField.setFont(font2)
self.searchButton = QPushButton(self.centralwidget)
self.searchButton.setObjectName(u"searchButton")
self.searchButton.setMinimumSize(QSize(0, 32))
self.searchButton.setFont(font2)
self.horizontalLayout_2.addWidget(self.searchField)
self.horizontalLayout_2.addWidget(self.searchButton)
self.gridLayout.addLayout(self.horizontalLayout_2, 3, 0, 1, 1)
self.gridLayout_2.setContentsMargins(6, 6, 6, 6)
self.searchButton = QPushButton(self.centralwidget)
self.searchButton.setObjectName(u"searchButton")
self.searchButton.setMinimumSize(QSize(0, 32))
self.searchButton.setFont(font2)
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)
MainWindow.setStatusBar(self.statusbar)
self.horizontalLayout_2.addWidget(self.searchButton)
self.gridLayout.addLayout(self.horizontalLayout_2, 3, 0, 1, 1)
self.retranslateUi(MainWindow)
self.comboBox = QComboBox(self.centralwidget)
self.comboBox.setObjectName(u"comboBox")
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.comboBox.sizePolicy().hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setMinimumWidth(128)
self.comboBox.setMaximumWidth(128)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
self.gridLayout.addWidget(self.comboBox, 4, 0, 1, 1, Qt.AlignRight)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate(
"MainWindow", u"MainWindow", None))
# Navigation buttons
self.backButton.setText(
QCoreApplication.translate("MainWindow", u"<", None))
self.forwardButton.setText(
QCoreApplication.translate("MainWindow", u">", None))
# Search field
self.searchField.setPlaceholderText(
QCoreApplication.translate("MainWindow", u"Search Entries", None))
self.searchButton.setText(
QCoreApplication.translate("MainWindow", u"Search", None))
# Search type selector
self.comboBox_2.setItemText(0, QCoreApplication.translate("MainWindow", "And (Includes All Tags)"))
self.comboBox_2.setItemText(1, QCoreApplication.translate("MainWindow", "Or (Includes Any Tag)"))
self.thumb_size_combobox.setCurrentText("")
# Thumbnail size selector
self.thumb_size_combobox.setPlaceholderText(
QCoreApplication.translate("MainWindow", u"Thumbnail Size", None))
# retranslateUi
self.gridLayout_2.setContentsMargins(6, 6, 6, 6)
def moveEvent(self, event) -> None:
# time.sleep(0.02) # sleep for 20ms
pass
MainWindow.setCentralWidget(self.centralwidget)
# self.menubar = QMenuBar(MainWindow)
# self.menubar.setObjectName(u"menubar")
# self.menubar.setGeometry(QRect(0, 0, 1280, 22))
# MainWindow.setMenuBar(self.menubar)
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)
MainWindow.setStatusBar(self.statusbar)
def resizeEvent(self, event) -> None:
# time.sleep(0.02) # sleep for 20ms
pass
# menu_bar = self.menuBar()
# self.setMenuBar(menu_bar)
# self.gridLayout.addWidget(menu_bar, 4, 0, 1, 1, Qt.AlignRight)
# self.frame_layout.addWidget(menu_bar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate(
"MainWindow", u"MainWindow", None))
self.backButton.setText(
QCoreApplication.translate("MainWindow", u"<", None))
self.forwardButton.setText(
QCoreApplication.translate("MainWindow", u">", None))
self.searchField.setPlaceholderText(
QCoreApplication.translate("MainWindow", u"Search Entries", None))
self.searchButton.setText(
QCoreApplication.translate("MainWindow", u"Search", None))
self.comboBox.setCurrentText("")
self.comboBox.setPlaceholderText(
QCoreApplication.translate("MainWindow", u"Thumbnail Size", None))
# retranslateUi
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 _createMenuBar(self, main_window):
# menu_bar = QMenuBar(main_window)
# file_menu = QMenu('&File', main_window)
# edit_menu = QMenu('&Edit', main_window)
# tools_menu = QMenu('&Tools', main_window)
# macros_menu = QMenu('&Macros', main_window)
# help_menu = QMenu('&Help', main_window)
# file_menu.addAction(QAction('&New Library', main_window))
# file_menu.addAction(QAction('&Open Library', main_window))
# file_menu.addAction(QAction('&Save Library', main_window))
# file_menu.addAction(QAction('&Close Library', main_window))
# file_menu.addAction(QAction('&Refresh Directories', main_window))
# file_menu.addAction(QAction('&Add New Files to Library', main_window))
# menu_bar.addMenu(file_menu)
# menu_bar.addMenu(edit_menu)
# menu_bar.addMenu(tools_menu)
# menu_bar.addMenu(macros_menu)
# menu_bar.addMenu(help_menu)
# main_window.setMenuBar(menu_bar)
def toggle_landing_page(self, enabled: bool):
if enabled:
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.scrollArea.setHidden(False)

View File

@@ -10,20 +10,21 @@ from PySide6.QtWidgets import (
QHBoxLayout,
QLabel,
QPushButton,
QComboBox,
QListWidget,
)
from src.core.library import Library
class AddFieldModal(QWidget):
done = Signal(int)
done = Signal(list)
def __init__(self, library: "Library"):
# [Done]
# - OR -
# [Cancel] [Save]
super().__init__()
self.is_connected = False
self.lib = library
self.setWindowTitle(f"Add Field")
self.setWindowModality(Qt.WindowModality.ApplicationModal)
@@ -37,31 +38,25 @@ class AddFieldModal(QWidget):
self.title_widget.setStyleSheet(
# 'background:blue;'
# 'text-align:center;'
"font-weight:bold;" "font-size:14px;" "padding-top: 6px" ""
"font-weight:bold;" "font-size:14px;" "padding-top: 6px"
)
self.title_widget.setText("Add Field")
self.title_widget.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.combo_box = QComboBox()
self.combo_box.setEditable(False)
# self.combo_box.setMaxVisibleItems(5)
self.combo_box.setStyleSheet("combobox-popup:0;")
self.combo_box.view().setVerticalScrollBarPolicy(
Qt.ScrollBarPolicy.ScrollBarAsNeeded
)
self.list_widget = QListWidget()
self.list_widget.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
items = []
for df in self.lib.default_fields:
self.combo_box.addItem(
f'{df["name"]} ({df["type"].replace("_", " ").title()})'
)
items.append(f'{df["name"]} ({df["type"].replace("_", " ").title()})')
self.list_widget.addItems(items)
self.button_container = QWidget()
self.button_layout = QHBoxLayout(self.button_container)
self.button_layout.setContentsMargins(6, 6, 6, 6)
self.button_layout.addStretch(1)
# self.cancel_button = QPushButton()
# self.cancel_button.setText('Cancel')
self.cancel_button = QPushButton()
self.cancel_button.setText("Cancel")
self.cancel_button.clicked.connect(self.hide)
@@ -74,17 +69,11 @@ class AddFieldModal(QWidget):
self.save_button.setDefault(True)
self.save_button.clicked.connect(self.hide)
self.save_button.clicked.connect(
lambda: self.done.emit(self.combo_box.currentIndex())
lambda: self.done.emit(self.list_widget.selectedIndexes())
)
# self.save_button.clicked.connect(lambda: save_callback(widget.get_content()))
self.button_layout.addWidget(self.save_button)
# self.returnPressed.connect(lambda: self.done.emit(self.combo_box.currentIndex()))
# self.done.connect(lambda x: callback(x))
self.root_layout.addWidget(self.title_widget)
self.root_layout.addWidget(self.combo_box)
# self.root_layout.setStretch(1,2)
self.root_layout.addStretch(1)
self.root_layout.addWidget(self.list_widget)
self.root_layout.addWidget(self.button_container)

View File

@@ -5,30 +5,28 @@
import logging
from PySide6.QtCore import Signal, Qt
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget,
QVBoxLayout,
QLabel,
QPushButton,
QLineEdit,
QScrollArea,
QFrame,
QTextEdit,
QComboBox,
QFrame,
QLabel,
QLineEdit,
QPushButton,
QScrollArea,
QTextEdit,
QVBoxLayout,
QWidget,
)
from src.core.constants import TAG_COLORS
from src.core.library import Library, Tag
from src.core.palette import ColorType, get_tag_color
from src.core.constants import TAG_COLORS
from src.qt.widgets.panel import PanelWidget, PanelModal
from src.qt.widgets.tag import TagWidget
from src.qt.modals.tag_search import TagSearchPanel
from src.qt.widgets.panel import PanelModal, PanelWidget
from src.qt.widgets.tag import TagWidget
ERROR = f"[ERROR]"
WARNING = f"[WARNING]"
INFO = f"[INFO]"
ERROR = "[ERROR]"
WARNING = "[WARNING]"
INFO = "[INFO]"
logging.basicConfig(format="%(message)s", level=logging.INFO)
@@ -36,7 +34,7 @@ logging.basicConfig(format="%(message)s", level=logging.INFO)
class BuildTagPanel(PanelWidget):
on_edit = Signal(Tag)
def __init__(self, library, tag_id: int = -1):
def __init__(self, library, tag_id: int = -1, tag_name: str = "New Tag"):
super().__init__()
self.lib: Library = library
# self.callback = callback
@@ -96,7 +94,7 @@ class BuildTagPanel(PanelWidget):
self.subtags_layout.setSpacing(0)
self.subtags_layout.setAlignment(Qt.AlignmentFlag.AlignLeft)
self.subtags_title = QLabel()
self.subtags_title.setText("Subtags")
self.subtags_title.setText("Parent Tags")
self.subtags_layout.addWidget(self.subtags_title)
self.scroll_contents = QWidget()
@@ -117,8 +115,8 @@ class BuildTagPanel(PanelWidget):
self.subtags_add_button = QPushButton()
self.subtags_add_button.setText("+")
tsp = TagSearchPanel(self.lib)
tsp.tag_chosen.connect(lambda x: self.add_subtag_callback(x))
self.add_tag_modal = PanelModal(tsp, "Add Subtags", "Add Subtags")
tsp.tag_created.connect(lambda x: self.add_subtag_callback(x))
self.add_tag_modal = PanelModal(tsp, "Add Parent Tags", "Add Parent Tags")
self.subtags_add_button.clicked.connect(self.add_tag_modal.show)
self.subtags_layout.addWidget(self.subtags_add_button)
@@ -163,7 +161,7 @@ class BuildTagPanel(PanelWidget):
if tag_id >= 0:
self.tag = self.lib.get_tag(tag_id)
else:
self.tag = Tag(-1, "New Tag", "", [], [], "")
self.tag = Tag(-1, tag_name, "", [], [], "")
self.set_tag(self.tag)
def add_subtag_callback(self, tag_id: int):

View File

@@ -32,7 +32,7 @@ class DeleteUnlinkedEntriesModal(QWidget):
super().__init__()
self.lib = library
self.driver = driver
self.setWindowTitle(f"Delete Unlinked Entries")
self.setWindowTitle("Delete Unlinked Entries")
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setMinimumSize(500, 400)
self.root_layout = QVBoxLayout(self)
@@ -78,23 +78,9 @@ class DeleteUnlinkedEntriesModal(QWidget):
self.model.clear()
for i in self.lib.missing_files:
self.model.appendRow(QStandardItem(i))
self.model.appendRow(QStandardItem(str(i)))
def delete_entries(self):
# pb = QProgressDialog('', None, 0, len(self.lib.missing_files))
# # pb.setMaximum(len(self.lib.missing_files))
# pb.setFixedSize(432, 112)
# pb.setWindowFlags(pb.windowFlags() & ~Qt.WindowType.WindowCloseButtonHint)
# pb.setWindowTitle('Deleting Entries')
# pb.setWindowModality(Qt.WindowModality.ApplicationModal)
# pb.show()
# r = CustomRunnable(lambda: self.lib.ref(pb))
# r.done.connect(lambda: self.done.emit())
# # r.done.connect(lambda: self.model.clear())
# QThreadPool.globalInstance().start(r)
# # r.run()
iterator = FunctionIterator(self.lib.remove_missing_files)
pw = ProgressWidget(
@@ -119,23 +105,3 @@ class DeleteUnlinkedEntriesModal(QWidget):
r = CustomRunnable(lambda: iterator.run())
QThreadPool.globalInstance().start(r)
r.done.connect(lambda: (pw.hide(), pw.deleteLater(), self.done.emit()))
# def delete_entries_runnable(self):
# deleted = []
# for i, missing in enumerate(self.lib.missing_files):
# # pb.setValue(i)
# # pb.setLabelText(f'Deleting {i}/{len(self.lib.missing_files)} Unlinked Entries')
# try:
# id = self.lib.get_entry_id_from_filepath(missing)
# logging.info(f'Removing Entry ID {id}:\n\t{missing}')
# self.lib.remove_entry(id)
# self.driver.purge_item_from_navigation(ItemType.ENTRY, id)
# deleted.append(missing)
# except KeyError:
# logging.info(
# f'{ERROR} \"{id}\" was reported as missing, but is not in the file_to_entry_id map.')
# yield i
# for d in deleted:
# self.lib.missing_files.remove(d)
# # self.driver.filter_items('')
# # self.done.emit()

View File

@@ -0,0 +1,245 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from pathlib import Path
import shutil
import typing
from PySide6.QtCore import QThreadPool
from PySide6.QtGui import QDropEvent, QDragEnterEvent, QDragMoveEvent
from PySide6.QtWidgets import QMessageBox
from src.qt.widgets.progress import ProgressWidget
from src.qt.helpers.custom_runnable import CustomRunnable
from src.qt.helpers.function_iterator import FunctionIterator
if typing.TYPE_CHECKING:
from src.qt.ts_qt import QtDriver
import logging
class DropImport:
def __init__(self, driver: "QtDriver"):
self.driver = driver
def dropEvent(self, event: QDropEvent):
if (
event.source() is self.driver
): # change that if you want to drop something originating from tagstudio, for moving or so
return
if not event.mimeData().hasUrls():
return
self.urls = event.mimeData().urls()
self.import_files()
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event: QDragMoveEvent):
if event.mimeData().hasUrls():
event.accept()
else:
logging.info(self.driver.selected)
event.ignore()
def import_files(self):
self.files: list[Path] = []
self.dirs_in_root: list[Path] = []
self.duplicate_files: list[Path] = []
def displayed_text(x):
text = f"Searching New Files...\n{x[0]+1} File{'s' if x[0]+1 != 1 else ''} Found."
if x[1] == 0:
return text
return text + f" {x[1]} Already exist in the library folders"
create_progress_bar(
self.collect_files_to_import,
"Searching Files",
"Searching New Files...\nPreparing...",
displayed_text,
self.ask_user,
)
def collect_files_to_import(self):
for url in self.urls:
if not url.isLocalFile():
continue
file = Path(url.toLocalFile())
if file.is_dir():
for f in self.get_files_in_folder(file):
if f.is_dir():
continue
self.files.append(f)
if (
self.driver.lib.library_dir / self.get_relative_path(file)
).exists():
self.duplicate_files.append(f)
yield [len(self.files), len(self.duplicate_files)]
self.dirs_in_root.append(file.parent)
else:
self.files.append(file)
if file.parent not in self.dirs_in_root:
self.dirs_in_root.append(
file.parent
) # to create relative path of files not in folder
if (Path(self.driver.lib.library_dir) / file.name).exists():
self.duplicate_files.append(file)
yield [len(self.files), len(self.duplicate_files)]
def copy_files(self):
fileCount = 0
duplicated_files_progress = 0
for file in self.files:
if file.is_dir():
continue
dest_file = self.get_relative_path(file)
full_dest_path: Path = self.driver.lib.library_dir / dest_file
if file in self.duplicate_files:
duplicated_files_progress += 1
if self.choice == 0: # skip duplicates
continue
if self.choice == 2: # rename
new_name = self.get_renamed_duplicate_filename_in_lib(dest_file)
dest_file = dest_file.with_name(new_name)
self.driver.lib.files_not_in_library.append(full_dest_path)
else: # override is simply copying but not adding a new entry
self.driver.lib.files_not_in_library.append(full_dest_path)
(full_dest_path).parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(file, full_dest_path)
fileCount += 1
yield [fileCount, duplicated_files_progress]
def ask_user(self):
self.choice = -1
if len(self.duplicate_files) > 0:
self.choice = self.duplicates_choice()
if self.choice == 3: # cancel
return
def displayed_text(x):
dupes_choice_text = (
"Skipped"
if self.choice == 0
else ("Overridden" if self.choice == 1 else "Renamed")
)
text = f"Importing New Files...\n{x[0]+1} File{'s' if x[0]+1 != 1 else ''} Imported."
if x[1] == 0:
return text
return text + f" {x[1]} {dupes_choice_text}"
create_progress_bar(
self.copy_files,
"Import Files",
"Importing New Files...\nPreparing...",
displayed_text,
self.driver.add_new_files_runnable,
len(self.files),
)
def duplicates_choice(self) -> int:
display_limit: int = 5
msgBox = QMessageBox()
msgBox.setWindowTitle(
f"File Conflict{'s' if len(self.duplicate_files) > 1 else ''}"
)
dupes_to_show = self.duplicate_files
if len(self.duplicate_files) > display_limit:
dupes_to_show = dupes_to_show[0:display_limit]
dupes_str = "\n ".join(map(lambda path: str(path), dupes_to_show))
dupes_more = (
f"\nand {len(self.duplicate_files)-display_limit} more "
if len(self.duplicate_files) > display_limit
else "\n"
)
msgBox.setText(
f"The following files:\n {dupes_str}{dupes_more}have filenames that already exist in the library folder."
)
msgBox.addButton("Skip", QMessageBox.ButtonRole.YesRole)
msgBox.addButton("Override", QMessageBox.ButtonRole.DestructiveRole)
msgBox.addButton("Rename", QMessageBox.ButtonRole.DestructiveRole)
msgBox.addButton("Cancel", QMessageBox.ButtonRole.NoRole)
return msgBox.exec()
def get_files_exists_in_library(self, path: Path) -> list[Path]:
exists: list[Path] = []
if not path.is_dir():
return exists
files = self.get_files_in_folder(path)
for file in files:
if file.is_dir():
exists += self.get_files_exists_in_library(file)
elif (self.driver.lib.library_dir / self.get_relative_path(file)).exists():
exists.append(file)
return exists
def get_relative_paths(self, paths: list[Path]) -> list[Path]:
relative_paths = []
for file in paths:
relative_paths.append(self.get_relative_path(file))
return relative_paths
def get_relative_path(self, path: Path) -> Path:
for dir in self.dirs_in_root:
if path.is_relative_to(dir):
return path.relative_to(dir)
return Path(path.name)
def get_files_in_folder(self, path: Path) -> list[Path]:
files = []
for file in path.glob("**/*"):
files.append(file)
return files
def get_renamed_duplicate_filename_in_lib(self, filePath: Path) -> str:
index = 2
o_filename = filePath.name
dot_idx = o_filename.index(".")
while (self.driver.lib.library_dir / filePath).exists():
filePath = filePath.with_name(
o_filename[:dot_idx] + f" ({index})" + o_filename[dot_idx:]
)
index += 1
return filePath.name
def create_progress_bar(
function, title: str, text: str, update_label_callback, done_callback, max=0
):
iterator = FunctionIterator(function)
pw = ProgressWidget(
window_title=title,
label_text=text,
cancel_button_text=None,
minimum=0,
maximum=max,
)
pw.show()
iterator.value.connect(lambda x: pw.update_progress(x[0] + 1))
iterator.value.connect(lambda x: pw.update_label(update_label_callback(x)))
r = CustomRunnable(lambda: iterator.run())
r.done.connect(lambda: (pw.hide(), done_callback())) # type: ignore
QThreadPool.globalInstance().start(r)

View File

@@ -0,0 +1,65 @@
import logging
import math
from pathlib import Path
from shutil import which
import subprocess
from PIL import Image, ImageQt
from PySide6.QtCore import Signal, Qt, QUrl
from PySide6.QtGui import QPixmap, QDesktopServices
from PySide6.QtWidgets import QMessageBox
class FfmpegChecker(QMessageBox):
"""A warning dialog for if FFmpeg is missing."""
HELP_URL = "https://docs.tagstud.io/help/ffmpeg/"
def __init__(self):
super().__init__()
self.setWindowTitle("Warning: Missing dependency")
self.setText("Warning: Could not find FFmpeg installation")
self.setIcon(QMessageBox.Warning)
# Blocks other application interactions until resolved
self.setWindowModality(Qt.ApplicationModal)
self.setStandardButtons(
QMessageBox.Help | QMessageBox.Ignore | QMessageBox.Cancel
)
self.setDefaultButton(QMessageBox.Ignore)
# Enables the cancel button but hides it to allow for click X to close dialog
self.button(QMessageBox.Cancel).hide()
self.ffmpeg = False
self.ffprobe = False
def installed(self):
"""Checks if both FFmpeg and FFprobe are installed and in the PATH."""
if which("ffmpeg"):
self.ffmpeg = True
if which("ffprobe"):
self.ffprobe = True
logging.info(
f"[FFmpegChecker] FFmpeg found: {self.ffmpeg}, FFprobe found: {self.ffprobe}"
)
return self.ffmpeg and self.ffprobe
def show_warning(self):
"""Displays the warning to the user and awaits respone."""
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) which can be ignored
if selection == QMessageBox.Help:
QDesktopServices.openUrl(QUrl(self.HELP_URL))

View File

@@ -4,51 +4,110 @@
from PySide6.QtCore import Signal, Qt
from PySide6.QtWidgets import QVBoxLayout, QPushButton, QTableWidget, QTableWidgetItem
from PySide6.QtWidgets import (
QVBoxLayout,
QHBoxLayout,
QWidget,
QPushButton,
QTableWidget,
QTableWidgetItem,
QStyledItemDelegate,
QLineEdit,
QComboBox,
QLabel,
)
from src.core.library import Library
from src.qt.widgets.panel import PanelWidget
class FileExtensionItemDelegate(QStyledItemDelegate):
def setModelData(self, editor, model, index):
if isinstance(editor, QLineEdit):
if 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(f"File Extensions")
self.setWindowTitle("File Extensions")
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setMinimumSize(200, 400)
self.setMinimumSize(240, 400)
self.root_layout = QVBoxLayout(self)
self.root_layout.setContentsMargins(6, 6, 6, 6)
self.table = QTableWidget(len(self.lib.ignored_extensions), 1)
# Create Table Widget --------------------------------------------------
self.table = QTableWidget(len(self.lib.ext_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()
self.add_button.setText("&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()
self.mode_label.setText("List Mode:")
self.mode_combobox = QComboBox()
self.mode_combobox.setEditable(False)
self.mode_combobox.addItem("Exclude")
self.mode_combobox.addItem("Include")
self.mode_combobox.setCurrentIndex(0 if self.lib.is_exclude_list else 1)
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. 0 for "Exclude", 1 for "Include".
"""
if mode == 0:
self.lib.is_exclude_list = True
elif mode == 1:
self.lib.is_exclude_list = False
def refresh_list(self):
for i, ext in enumerate(self.lib.ignored_extensions):
for i, ext in enumerate(self.lib.ext_list):
self.table.setItem(i, 0, QTableWidgetItem(ext))
def add_item(self):
self.table.insertRow(self.table.rowCount())
def save(self):
self.lib.ignored_extensions.clear()
self.lib.ext_list.clear()
for i in range(self.table.rowCount()):
ext = self.table.item(i, 0)
if ext and ext.text():
self.lib.ignored_extensions.append(ext.text())
self.lib.ext_list.append(ext.text().lower())

View File

@@ -137,9 +137,7 @@ class FixDupeFilesModal(QWidget):
self.set_dupe_count(self.count)
def select_file(self):
qfd = QFileDialog(
self, "Open DupeGuru Results File", os.path.normpath(self.lib.library_dir)
)
qfd = QFileDialog(self, "Open DupeGuru Results File", str(self.lib.library_dir))
qfd.setFileMode(QFileDialog.FileMode.ExistingFile)
qfd.setNameFilter("DupeGuru Files (*.dupeguru)")
if qfd.exec_():

View File

@@ -6,7 +6,7 @@
import logging
import typing
from PySide6.QtCore import QThread, Qt, QThreadPool
from PySide6.QtCore import Qt, QThreadPool
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from src.core.library import Library
@@ -14,6 +14,7 @@ from src.qt.helpers.function_iterator import FunctionIterator
from src.qt.helpers.custom_runnable import CustomRunnable
from src.qt.modals.delete_unlinked import DeleteUnlinkedEntriesModal
from src.qt.modals.relink_unlinked import RelinkUnlinkedEntries
from src.qt.modals.merge_dupe_entries import MergeDuplicateEntries
from src.qt.widgets.progress import ProgressWidget
# Only import for type checking/autocompletion, will not be imported at runtime.
@@ -21,65 +22,79 @@ if typing.TYPE_CHECKING:
from src.qt.ts_qt import QtDriver
ERROR = f"[ERROR]"
WARNING = f"[WARNING]"
INFO = f"[INFO]"
ERROR = "[ERROR]"
WARNING = "[WARNING]"
INFO = "[INFO]"
logging.basicConfig(format="%(message)s", level=logging.INFO)
class FixUnlinkedEntriesModal(QWidget):
# done = Signal(int)
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__()
self.lib = library
self.driver = driver
self.count = -1
self.setWindowTitle(f"Fix Unlinked Entries")
self.missing_count = -1
self.dupe_count = -1
self.setWindowTitle("Fix Unlinked Entries")
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setMinimumSize(400, 300)
self.root_layout = QVBoxLayout(self)
self.root_layout.setContentsMargins(6, 6, 6, 6)
self.desc_widget = QLabel()
self.desc_widget.setObjectName("descriptionLabel")
self.desc_widget.setWordWrap(True)
self.desc_widget.setStyleSheet(
# 'background:blue;'
"text-align:left;"
# 'font-weight:bold;'
# 'font-size:14px;'
# 'padding-top: 6px'
""
self.unlinked_desc_widget = QLabel()
self.unlinked_desc_widget.setObjectName("unlinkedDescriptionLabel")
self.unlinked_desc_widget.setWordWrap(True)
self.unlinked_desc_widget.setStyleSheet("text-align:left;")
self.unlinked_desc_widget.setText(
"""Each library entry is linked to a file in one of your directories. If a file linked to an entry is moved or deleted outside of TagStudio, it is then considered unlinked. Unlinked entries may be automatically relinked via searching your directories, manually relinked by the user, or deleted if desired."""
)
self.desc_widget.setText("""Each library entry is linked to a file in one of your directories. If a file linked to an entry is moved or deleted outside of TagStudio, it is then considered unlinked.
Unlinked entries may be automatically relinked via searching your directories, manually relinked by the user, or deleted if desired.""")
self.desc_widget.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.missing_count = QLabel()
self.missing_count.setObjectName("missingCountLabel")
self.missing_count.setStyleSheet(
# 'background:blue;'
# 'text-align:center;'
"font-weight:bold;"
"font-size:14px;"
# 'padding-top: 6px'
""
self.dupe_desc_widget = QLabel()
self.dupe_desc_widget.setObjectName("dupeDescriptionLabel")
self.dupe_desc_widget.setWordWrap(True)
self.dupe_desc_widget.setStyleSheet("text-align:left;")
self.dupe_desc_widget.setText(
"""Duplicate entries are defined as multiple entries which point to the same file on disk. Merging these will combine the tags and metadata from all duplicates into a single consolidated entry. These are not to be confused with "duplicate files", which are duplicates of your files themselves outside of TagStudio."""
)
self.missing_count.setAlignment(Qt.AlignmentFlag.AlignCenter)
# self.missing_count.setText('Missing Files: N/A')
self.refresh_button = QPushButton()
self.refresh_button.setText("&Refresh")
self.refresh_button.clicked.connect(lambda: self.refresh_missing_files())
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()
self.refresh_unlinked_button.setText("&Refresh All")
self.refresh_unlinked_button.clicked.connect(
lambda: self.refresh_missing_files()
)
self.merge_class = MergeDuplicateEntries(self.lib, self.driver)
self.relink_class = RelinkUnlinkedEntries(self.lib, self.driver)
self.search_button = QPushButton()
self.search_button.setText("&Search && Relink")
self.relink_class = RelinkUnlinkedEntries(self.lib, self.driver)
self.relink_class.done.connect(lambda: self.refresh_missing_files())
self.relink_class.done.connect(lambda: self.driver.update_thumbs())
self.relink_class.done.connect(
lambda: self.refresh_and_repair_dupe_entries(self.merge_class)
)
self.search_button.clicked.connect(lambda: self.relink_class.repair_entries())
self.refresh_dupe_button = QPushButton()
self.refresh_dupe_button.setText("Refresh Duplicate Entries")
self.refresh_dupe_button.clicked.connect(lambda: self.refresh_dupe_entries())
self.merge_dupe_button = QPushButton()
self.merge_dupe_button.setText("&Merge Duplicate Entries")
self.merge_class.done.connect(lambda: self.set_dupe_count(-1))
self.merge_class.done.connect(lambda: self.set_missing_count(-1))
self.merge_class.done.connect(lambda: self.driver.filter_items())
self.merge_dupe_button.clicked.connect(lambda: self.merge_class.merge_entries())
self.manual_button = QPushButton()
self.manual_button.setText("&Manual Relink")
@@ -92,14 +107,6 @@ class FixUnlinkedEntriesModal(QWidget):
self.delete_button.setText("De&lete Unlinked Entries")
self.delete_button.clicked.connect(lambda: self.delete_modal.show())
# self.combo_box = QComboBox()
# self.combo_box.setEditable(False)
# # self.combo_box.setMaxVisibleItems(5)
# self.combo_box.setStyleSheet('combobox-popup:0;')
# self.combo_box.view().setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
# for df in self.lib.default_fields:
# self.combo_box.addItem(f'{df["name"]} ({df["type"].replace("_", " ").title()})')
self.button_container = QWidget()
self.button_layout = QHBoxLayout(self.button_container)
self.button_layout.setContentsMargins(6, 6, 6, 6)
@@ -107,50 +114,39 @@ class FixUnlinkedEntriesModal(QWidget):
self.done_button = QPushButton()
self.done_button.setText("&Done")
# self.save_button.setAutoDefault(True)
self.done_button.setDefault(True)
self.done_button.clicked.connect(self.hide)
# self.done_button.clicked.connect(lambda: self.done.emit(self.combo_box.currentIndex()))
# self.save_button.clicked.connect(lambda: save_callback(widget.get_content()))
self.button_layout.addWidget(self.done_button)
# self.returnPressed.connect(lambda: self.done.emit(self.combo_box.currentIndex()))
# self.done.connect(lambda x: callback(x))
self.root_layout.addWidget(self.desc_widget)
self.root_layout.addWidget(self.missing_count)
self.root_layout.addWidget(self.refresh_button)
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.manual_button.setHidden(True)
self.root_layout.addWidget(self.manual_button)
self.root_layout.addWidget(self.delete_button)
# self.root_layout.setStretch(1,2)
self.root_layout.addStretch(1)
self.root_layout.addWidget(self.dupe_count_label)
self.root_layout.addWidget(self.dupe_desc_widget)
self.root_layout.addWidget(self.refresh_dupe_button)
self.root_layout.addWidget(self.merge_dupe_button)
self.root_layout.addStretch(2)
self.root_layout.addWidget(self.button_container)
self.set_missing_count(self.count)
self.set_missing_count(self.missing_count)
self.set_dupe_count(self.dupe_count)
def refresh_missing_files(self):
logging.info(f"Start RMF: {QThread.currentThread()}")
# pb = QProgressDialog(f'Scanning Library for Unlinked Entries...', None, 0,len(self.lib.entries))
# pb.setFixedSize(432, 112)
# pb.setWindowFlags(pb.windowFlags() & ~Qt.WindowType.WindowCloseButtonHint)
# pb.setWindowTitle('Scanning Library')
# pb.setWindowModality(Qt.WindowModality.ApplicationModal)
# pb.show()
iterator = FunctionIterator(self.lib.refresh_missing_files)
pw = ProgressWidget(
window_title="Scanning Library",
label_text=f"Scanning Library for Unlinked Entries...",
label_text="Scanning Library for Unlinked Entries...",
cancel_button_text=None,
minimum=0,
maximum=len(self.lib.entries),
)
pw.show()
iterator.value.connect(lambda v: pw.update_progress(v + 1))
# rmf.value.connect(lambda v: pw.update_label(f'Progress: {v}'))
r = CustomRunnable(lambda: iterator.run())
QThreadPool.globalInstance().start(r)
r.done.connect(
@@ -159,30 +155,76 @@ class FixUnlinkedEntriesModal(QWidget):
pw.deleteLater(),
self.set_missing_count(len(self.lib.missing_files)),
self.delete_modal.refresh_list(),
self.refresh_dupe_entries(),
)
)
# r = CustomRunnable(lambda: self.lib.refresh_missing_files(lambda v: self.update_scan_value(pb, v)))
# r.done.connect(lambda: (pb.hide(), pb.deleteLater(), self.set_missing_count(len(self.lib.missing_files)), self.delete_modal.refresh_list()))
# QThreadPool.globalInstance().start(r)
# # r.run()
# pass
def refresh_dupe_entries(self):
iterator = FunctionIterator(self.lib.refresh_dupe_entries)
pw = ProgressWidget(
window_title="Scanning Library",
label_text="Scanning Library for Duplicate Entries...",
cancel_button_text=None,
minimum=0,
maximum=len(self.lib.entries),
)
pw.show()
iterator.value.connect(lambda v: pw.update_progress(v + 1))
r = CustomRunnable(lambda: iterator.run())
QThreadPool.globalInstance().start(r)
r.done.connect(
lambda: (
pw.hide(),
pw.deleteLater(),
self.set_dupe_count(len(self.lib.dupe_entries)),
)
)
# def update_scan_value(self, pb:QProgressDialog, value=int):
# # pb.setLabelText(f'Scanning Library for Unlinked Entries ({value}/{len(self.lib.entries)})...')
# pb.setValue(value)
def refresh_and_repair_dupe_entries(self, merge_class: MergeDuplicateEntries):
iterator = FunctionIterator(self.lib.refresh_dupe_entries)
pw = ProgressWidget(
window_title="Scanning Library",
label_text="Scanning Library for Duplicate Entries...",
cancel_button_text=None,
minimum=0,
maximum=len(self.lib.entries),
)
pw.show()
iterator.value.connect(lambda v: pw.update_progress(v + 1))
r = CustomRunnable(lambda: iterator.run())
QThreadPool.globalInstance().start(r)
r.done.connect(
lambda: (
pw.hide(), # type: ignore
pw.deleteLater(), # type: ignore
self.set_dupe_count(len(self.lib.dupe_entries)),
merge_class.merge_entries(),
)
)
def set_missing_count(self, count: int):
self.count = count
if self.count < 0:
self.missing_count = count
if self.missing_count < 0:
self.search_button.setDisabled(True)
self.delete_button.setDisabled(True)
self.missing_count.setText(f"Unlinked Entries: N/A")
elif self.count == 0:
self.missing_count_label.setText("Unlinked Entries: N/A")
elif self.missing_count == 0:
self.search_button.setDisabled(True)
self.delete_button.setDisabled(True)
self.missing_count.setText(f"Unlinked Entries: {count}")
self.missing_count_label.setText(f"Unlinked Entries: {count}")
else:
self.search_button.setDisabled(False)
self.delete_button.setDisabled(False)
self.missing_count.setText(f"Unlinked Entries: {count}")
self.missing_count_label.setText(f"Unlinked Entries: {count}")
def set_dupe_count(self, count: int):
self.dupe_count = count
if self.dupe_count < 0:
self.dupe_count_label.setText("Duplicate Entries: N/A")
self.merge_dupe_button.setDisabled(True)
elif self.dupe_count == 0:
self.dupe_count_label.setText(f"Duplicate Entries: {count}")
self.merge_dupe_button.setDisabled(True)
else:
self.dupe_count_label.setText(f"Duplicate Entries: {count}")
self.merge_dupe_button.setDisabled(False)

View File

@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (
QFrame,
)
from src.core.enums import FieldID
from src.core.library import Library, Tag
from src.core.palette import ColorType, get_tag_color
from src.qt.flowlayout import FlowLayout
@@ -60,26 +61,26 @@ def folders_to_tags(library: Library):
library.add_tag_to_library(new_tag)
branch["dirs"][folder] = dict(dirs={}, tag=new_tag)
branch = branch["dirs"][folder]
return branch["tag"]
return branch.get("tag")
for tag in library.tags:
reversed_tag = reverse_tag(library, tag, None)
add_tag_to_tree(reversed_tag)
for entry in library.entries:
folders = entry.path.split("\\")
folders = list(entry.path.parts)
if len(folders) == 1 and folders[0] == "":
continue
tag = add_folders_to_tree(folders)
if tag:
if not entry.has_tag(library, tag.id):
entry.add_tag(library, tag.id, 6)
entry.add_tag(library, tag.id, FieldID.TAGS)
logging.info("Done")
def reverse_tag(library: Library, tag: Tag, list: list[Tag]) -> list[Tag]:
if list != None:
if list is not None:
list.append(tag)
else:
list = [tag]
@@ -120,7 +121,7 @@ def generate_preview_data(library: Library):
add_tag_to_tree(reversed_tag)
for entry in library.entries:
folders = entry.path.split("\\")
folders = list(entry.path.parts)
if len(folders) == 1 and folders[0] == "":
continue
branch = add_folders_to_tree(folders)
@@ -144,7 +145,7 @@ def generate_preview_data(library: Library):
if cut:
branch["dirs"].pop(folder)
if not "tag" in branch:
if "tag" not in branch:
return
if branch["tag"].id == -1 or len(branch["files"]) > 0: # Needs to be first
return False
@@ -289,7 +290,7 @@ class TreeItem(QWidget):
self.children_layout.addWidget(item)
for file in data["files"]:
label = QLabel()
label.setText(" -> " + file)
label.setText(" -> " + str(file))
self.children_layout.addWidget(label)
if len(data["files"]) == 0 and len(data["dirs"].values()) == 0:
@@ -321,7 +322,7 @@ class ModifiedTagWidget(
self.bg_button = QPushButton(self)
self.bg_button.setFlat(True)
if parentTag != None:
if parentTag is not None:
text = f"{tag.name} ({parentTag.name})".replace("&", "&&")
else:
text = tag.name.replace("&", "&&")
@@ -341,8 +342,8 @@ class ModifiedTagWidget(
f"font-weight: 600;"
f"border-color:{get_tag_color(ColorType.BORDER, tag.color)};"
f"border-radius: 6px;"
f"border-style:inset;"
f"border-width: {math.ceil(1*self.devicePixelRatio())}px;"
f"border-style:solid;"
f"border-width: {math.ceil(self.devicePixelRatio())}px;"
f"padding-right: 4px;"
f"padding-bottom: 1px;"
f"padding-left: 4px;"

View File

@@ -0,0 +1,46 @@
# Copyright (C) 2024 Travis Abendshien (CyanVoxel).
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
import typing
from PySide6.QtCore import QObject, Signal, QThreadPool
from src.core.library import Library
from src.qt.helpers.function_iterator import FunctionIterator
from src.qt.helpers.custom_runnable import CustomRunnable
from src.qt.widgets.progress import ProgressWidget
# Only import for type checking/autocompletion, will not be imported at runtime.
if typing.TYPE_CHECKING:
from src.qt.ts_qt import QtDriver
class MergeDuplicateEntries(QObject):
done = Signal()
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__()
self.lib = library
self.driver = driver
def merge_entries(self):
iterator = FunctionIterator(self.lib.merge_dupe_entries)
pw = ProgressWidget(
window_title="Merging Duplicate Entries",
label_text="",
cancel_button_text=None,
minimum=0,
maximum=len(self.lib.dupe_entries),
)
pw.show()
iterator.value.connect(lambda x: pw.update_progress(x))
iterator.value.connect(
lambda: (pw.update_label("Merging Duplicate Entries..."))
)
r = CustomRunnable(lambda: iterator.run())
r.done.connect(lambda: (pw.hide(), pw.deleteLater(), self.done.emit()))
QThreadPool.globalInstance().start(r)

View File

@@ -26,20 +26,6 @@ class RelinkUnlinkedEntries(QObject):
self.fixed = 0
def repair_entries(self):
# pb = QProgressDialog('', None, 0, len(self.lib.missing_files))
# # pb.setMaximum(len(self.lib.missing_files))
# pb.setFixedSize(432, 112)
# pb.setWindowFlags(pb.windowFlags() & ~Qt.WindowType.WindowCloseButtonHint)
# pb.setWindowTitle('Relinking Entries')
# pb.setWindowModality(Qt.WindowModality.ApplicationModal)
# pb.show()
# r = CustomRunnable(lambda: self.repair_entries_runnable(pb))
# r.done.connect(lambda: self.done.emit())
# # r.done.connect(lambda: self.model.clear())
# QThreadPool.globalInstance().start(r)
# # r.run()
iterator = FunctionIterator(self.lib.fix_missing_files)
pw = ProgressWidget(
@@ -49,6 +35,7 @@ class RelinkUnlinkedEntries(QObject):
minimum=0,
maximum=len(self.lib.missing_files),
)
pw.show()
iterator.value.connect(lambda x: pw.update_progress(x[0] + 1))
@@ -60,7 +47,6 @@ class RelinkUnlinkedEntries(QObject):
),
)
)
# iterator.value.connect(lambda x: self.driver.purge_item_from_navigation(ItemType.ENTRY, x[1]))
r = CustomRunnable(lambda: iterator.run())
r.done.connect(
@@ -73,27 +59,3 @@ class RelinkUnlinkedEntries(QObject):
def reset_fixed(self):
self.fixed = 0
# def repair_entries_runnable(self, pb: QProgressDialog):
# fixed = 0
# for i in self.lib.fix_missing_files():
# if i[1]:
# fixed += 1
# pb.setValue(i[0])
# pb.setLabelText(f'Attempting to Relink {i[0]+1}/{len(self.lib.missing_files)} Entries, {fixed} Successfully Relinked')
# for i, missing in enumerate(self.lib.missing_files):
# pb.setValue(i)
# pb.setLabelText(f'Relinking {i}/{len(self.lib.missing_files)} Unlinked Entries')
# self.lib.fix_missing_files()
# try:
# id = self.lib.get_entry_id_from_filepath(missing)
# logging.info(f'Removing Entry ID {id}:\n\t{missing}')
# self.lib.remove_entry(id)
# self.driver.purge_item_from_navigation(ItemType.ENTRY, id)
# deleted.append(missing)
# except KeyError:
# logging.info(
# f'{ERROR} \"{id}\" was reported as missing, but is not in the file_to_entry_id map.')
# for d in deleted:
# self.lib.missing_files.remove(d)

View File

@@ -2,32 +2,37 @@
# Licensed under the GPL-3.0 License.
# Created for TagStudio: https://github.com/CyanVoxel/TagStudio
from PySide6.QtCore import Signal, Qt, QSize
import typing
from PySide6.QtCore import QSize, Qt, Signal
from PySide6.QtWidgets import (
QWidget,
QVBoxLayout,
QFrame,
QHBoxLayout,
QLineEdit,
QScrollArea,
QFrame,
QVBoxLayout,
QWidget,
)
from src.core.library import Library
from src.qt.widgets.panel import PanelWidget, PanelModal
from src.qt.widgets.tag import TagWidget
from src.core.constants import TAG_COLORS
from src.qt.modals.build_tag import BuildTagPanel
from src.qt.widgets.panel import PanelModal, PanelWidget
from src.qt.widgets.tag import TagWidget
# Only import for type checking/autocompletion, will not be imported at runtime.
if typing.TYPE_CHECKING:
from src.core.library import Library, Tag
from src.qt.ts_qt import QtDriver
class TagDatabasePanel(PanelWidget):
tag_chosen = Signal(int)
def __init__(self, library):
def __init__(self, library: "Library", driver: "QtDriver"):
super().__init__()
self.lib: Library = library
# self.callback = callback
self.driver: QtDriver = driver
self.first_tag_id = -1
self.tag_limit = 30
# self.selected_tag: int = 0
self.setMinimumSize(300, 400)
self.root_layout = QVBoxLayout(self)
@@ -103,8 +108,28 @@ class TagDatabasePanel(PanelWidget):
# Get tag ids to keep this behaviorally identical
tags = [t.id for t in self.lib.tags]
if query:
# sort tags by whether the tag's name is the text that's matching the search, alphabetically, and then by color
sorted_tags = sorted(
tags,
key=lambda tag_id: (
not self.lib.get_tag(tag_id).name.lower().startswith(query.lower()),
self.lib.get_tag(tag_id).display_name(self.lib),
TAG_COLORS.index(self.lib.get_tag(tag_id).color.lower()),
),
)
else:
# sort tags by color and then alphabetically
sorted_tags = sorted(
tags,
key=lambda tag_id: (
TAG_COLORS.index(self.lib.get_tag(tag_id).color.lower()),
self.lib.get_tag(tag_id).display_name(self.lib),
),
)
first_id_set = False
for tag_id in tags:
for tag_id in sorted_tags:
if not first_id_set:
self.first_tag_id = tag_id
first_id_set = True
@@ -112,9 +137,14 @@ class TagDatabasePanel(PanelWidget):
row = QHBoxLayout(container)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(3)
tw = TagWidget(self.lib, self.lib.get_tag(tag_id), True, False)
tw.on_edit.connect(
lambda checked=False, t=self.lib.get_tag(tag_id): (self.edit_tag(t.id))
tag: Tag = self.lib.get_tag(tag_id)
tw = TagWidget(self.lib, tag, True, False)
tw.on_edit.connect(lambda checked=False, t=tag: (self.edit_tag(t.id)))
tw.on_click.connect(
lambda checked=False, q=f"tag_id: {tag_id}": (
self.driver.main_window.searchField.setText(q),
self.driver.filter_items(q),
)
)
row.addWidget(tw)
self.scroll_layout.addWidget(container)

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