Commit 54d02a42ad

54d02a42ad43b99868c5a5b1b29f17a7a9b43993

parent: 5eef4e4240

Unsigned

Azin Sharaf <azin.sharaf@icloud.com> · 2026-04-27 16:54 UTC

feat(windows): add cross-platform compatibility for Windows

Replace Unix-specific path assumptions and shell commands with
platform-aware alternatives using the \dirs\ crate. Introduce a
\paths\ module for canonical config/data/cache directories, swap
hardcoded single-quote delimiters for runtime-selected quote chars,
use \cmd /C\ and Windows file-deletion commands where appropriate,
and filter duplicate key events (Press-only) to fix double-input on
Windows terminals.

Layout: unified · split

.gitignore +1
@@ -1,2 +1,3 @@
11/target
22/docs/book
3/mpv-dev
Cargo.lock +136 −11
@@ -682,6 +682,27 @@ dependencies = [
682682 "crypto-common",
683683]
684684
685[[package]]
686name = "dirs"
687version = "5.0.1"
688source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
690dependencies = [
691 "dirs-sys",
692]
693
694[[package]]
695name = "dirs-sys"
696version = "0.4.1"
697source = "registry+https://github.com/rust-lang/crates.io-index"
698checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
699dependencies = [
700 "libc",
701 "option-ext",
702 "redox_users",
703 "windows-sys 0.48.0",
704]
705
685706[[package]]
686707name = "displaydoc"
687708version = "0.2.5"
@@ -1014,6 +1035,17 @@ dependencies = [
10141035 "version_check",
10151036]
10161037
1038[[package]]
1039name = "getrandom"
1040version = "0.2.17"
1041source = "registry+https://github.com/rust-lang/crates.io-index"
1042checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1043dependencies = [
1044 "cfg-if",
1045 "libc",
1046 "wasi",
1047]
1048
10171049[[package]]
10181050name = "getrandom"
10191051version = "0.3.4"
@@ -1578,6 +1610,15 @@ version = "2.0.0-fork.1"
15781610source = "registry+https://github.com/rust-lang/crates.io-index"
15791611checksum = "88adfe3a9f3ef1d69c87ce86930246cd80c86be098d5bfd2a7b05962ff1d3a50"
15801612
1613[[package]]
1614name = "libredox"
1615version = "0.1.16"
1616source = "registry+https://github.com/rust-lang/crates.io-index"
1617checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c"
1618dependencies = [
1619 "libc",
1620]
1621
15811622[[package]]
15821623name = "line-clipping"
15831624version = "0.3.5"
@@ -1958,6 +1999,12 @@ dependencies = [
19581999 "vcpkg",
19592000]
19602001
2002[[package]]
2003name = "option-ext"
2004version = "0.2.0"
2005source = "registry+https://github.com/rust-lang/crates.io-index"
2006checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
2007
19612008[[package]]
19622009name = "ordered-float"
19632010version = "4.6.0"
@@ -2467,6 +2514,17 @@ dependencies = [
24672514 "bitflags 2.11.0",
24682515]
24692516
2517[[package]]
2518name = "redox_users"
2519version = "0.4.6"
2520source = "registry+https://github.com/rust-lang/crates.io-index"
2521checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
2522dependencies = [
2523 "getrandom 0.2.17",
2524 "libredox",
2525 "thiserror 1.0.69",
2526]
2527
24702528[[package]]
24712529name = "regex"
24722530version = "1.12.3"
@@ -3787,7 +3845,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
37873845checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49"
37883846dependencies = [
37893847 "windows-core 0.54.0",
3790 "windows-targets",
3848 "windows-targets 0.52.6",
37913849]
37923850
37933851[[package]]
@@ -3797,7 +3855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
37973855checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65"
37983856dependencies = [
37993857 "windows-result 0.1.2",
3800 "windows-targets",
3858 "windows-targets 0.52.6",
38013859]
38023860
38033861[[package]]
@@ -3847,7 +3905,7 @@ version = "0.1.2"
38473905source = "registry+https://github.com/rust-lang/crates.io-index"
38483906checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
38493907dependencies = [
3850 "windows-targets",
3908 "windows-targets 0.52.6",
38513909]
38523910
38533911[[package]]
@@ -3868,13 +3926,22 @@ dependencies = [
38683926 "windows-link",
38693927]
38703928
3929[[package]]
3930name = "windows-sys"
3931version = "0.48.0"
3932source = "registry+https://github.com/rust-lang/crates.io-index"
3933checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
3934dependencies = [
3935 "windows-targets 0.48.5",
3936]
3937
38713938[[package]]
38723939name = "windows-sys"
38733940version = "0.59.0"
38743941source = "registry+https://github.com/rust-lang/crates.io-index"
38753942checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
38763943dependencies = [
3877 "windows-targets",
3944 "windows-targets 0.52.6",
38783945]
38793946
38803947[[package]]
@@ -3886,34 +3953,67 @@ dependencies = [
38863953 "windows-link",
38873954]
38883955
3956[[package]]
3957name = "windows-targets"
3958version = "0.48.5"
3959source = "registry+https://github.com/rust-lang/crates.io-index"
3960checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
3961dependencies = [
3962 "windows_aarch64_gnullvm 0.48.5",
3963 "windows_aarch64_msvc 0.48.5",
3964 "windows_i686_gnu 0.48.5",
3965 "windows_i686_msvc 0.48.5",
3966 "windows_x86_64_gnu 0.48.5",
3967 "windows_x86_64_gnullvm 0.48.5",
3968 "windows_x86_64_msvc 0.48.5",
3969]
3970
38893971[[package]]
38903972name = "windows-targets"
38913973version = "0.52.6"
38923974source = "registry+https://github.com/rust-lang/crates.io-index"
38933975checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
38943976dependencies = [
3895 "windows_aarch64_gnullvm",
3896 "windows_aarch64_msvc",
3897 "windows_i686_gnu",
3977 "windows_aarch64_gnullvm 0.52.6",
3978 "windows_aarch64_msvc 0.52.6",
3979 "windows_i686_gnu 0.52.6",
38983980 "windows_i686_gnullvm",
3899 "windows_i686_msvc",
3900 "windows_x86_64_gnu",
3901 "windows_x86_64_gnullvm",
3902 "windows_x86_64_msvc",
3981 "windows_i686_msvc 0.52.6",
3982 "windows_x86_64_gnu 0.52.6",
3983 "windows_x86_64_gnullvm 0.52.6",
3984 "windows_x86_64_msvc 0.52.6",
39033985]
39043986
3987[[package]]
3988name = "windows_aarch64_gnullvm"
3989version = "0.48.5"
3990source = "registry+https://github.com/rust-lang/crates.io-index"
3991checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
3992
39053993[[package]]
39063994name = "windows_aarch64_gnullvm"
39073995version = "0.52.6"
39083996source = "registry+https://github.com/rust-lang/crates.io-index"
39093997checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
39103998
3999[[package]]
4000name = "windows_aarch64_msvc"
4001version = "0.48.5"
4002source = "registry+https://github.com/rust-lang/crates.io-index"
4003checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
4004
39114005[[package]]
39124006name = "windows_aarch64_msvc"
39134007version = "0.52.6"
39144008source = "registry+https://github.com/rust-lang/crates.io-index"
39154009checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
39164010
4011[[package]]
4012name = "windows_i686_gnu"
4013version = "0.48.5"
4014source = "registry+https://github.com/rust-lang/crates.io-index"
4015checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
4016
39174017[[package]]
39184018name = "windows_i686_gnu"
39194019version = "0.52.6"
@@ -3926,24 +4026,48 @@ version = "0.52.6"
39264026source = "registry+https://github.com/rust-lang/crates.io-index"
39274027checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
39284028
4029[[package]]
4030name = "windows_i686_msvc"
4031version = "0.48.5"
4032source = "registry+https://github.com/rust-lang/crates.io-index"
4033checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
4034
39294035[[package]]
39304036name = "windows_i686_msvc"
39314037version = "0.52.6"
39324038source = "registry+https://github.com/rust-lang/crates.io-index"
39334039checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
39344040
4041[[package]]
4042name = "windows_x86_64_gnu"
4043version = "0.48.5"
4044source = "registry+https://github.com/rust-lang/crates.io-index"
4045checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
4046
39354047[[package]]
39364048name = "windows_x86_64_gnu"
39374049version = "0.52.6"
39384050source = "registry+https://github.com/rust-lang/crates.io-index"
39394051checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
39404052
4053[[package]]
4054name = "windows_x86_64_gnullvm"
4055version = "0.48.5"
4056source = "registry+https://github.com/rust-lang/crates.io-index"
4057checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
4058
39414059[[package]]
39424060name = "windows_x86_64_gnullvm"
39434061version = "0.52.6"
39444062source = "registry+https://github.com/rust-lang/crates.io-index"
39454063checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
39464064
4065[[package]]
4066name = "windows_x86_64_msvc"
4067version = "0.48.5"
4068source = "registry+https://github.com/rust-lang/crates.io-index"
4069checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
4070
39474071[[package]]
39484072name = "windows_x86_64_msvc"
39494073version = "0.52.6"
@@ -4099,6 +4223,7 @@ dependencies = [
40994223 "chrono",
41004224 "clipboard",
41014225 "crossterm 0.29.0",
4226 "dirs",
41024227 "dyn-clone",
41034228 "futures",
41044229 "home",
Cargo.toml +1
@@ -29,6 +29,7 @@ serde = {version = "1.0", default-features = false, features = ["derive"]}
2929crossterm = {version = "0.29", default-features = false, features = ["serde"]}
3030viuer = {version = "0.11", default-features = false, optional = true, features = ["print-file"]}
3131home = "0.5"
32dirs = "5"
3233chrono = {version = "0.4", default-features = false, features = ["clock"]}
3334typemap = {version = "0.3", default-features = false}
3435tui-additions = {version = "0.4.3", default-features = false, features = ["framework", "widgets"]}
README.md +2 −2
@@ -11,7 +11,7 @@
1111
1212# Overview
1313
14Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal. Works out of the box and easily configurable.
14Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal. Works out of the box and easily configurable. Supports Linux and Windows.
1515
1616![](./docs/src/images/readme1.png)
1717
@@ -23,7 +23,7 @@ It is like an _app launcher_, it launches other programs to do the heavy lifting
2323
2424## Customisable
2525
26The YouTube TUI can be customised through config files, they are located in `~/.config/youtube-tui` and are in the YAML format.
26The YouTube TUI can be customised through config files, located in `~/.config/youtube-tui` on Linux or `%APPDATA%\youtube-tui` on Windows, in the YAML format.
2727
2828Here's an example of the config file:
2929
build.rs added +20
@@ -0,0 +1,20 @@
1fn main() {
2 // On Windows, help the linker find mpv.lib when building with the mpv feature.
3 // Check MPV_LIB_DIR env var, then fall back to a local mpv-dev directory.
4 #[cfg(all(target_os = "windows", feature = "mpv"))]
5 {
6 if let Ok(dir) = std::env::var("MPV_LIB_DIR") {
7 println!("cargo:rustc-link-search=native={}", dir);
8 } else {
9 // Check for a local mpv-dev directory (created by setup-mpv-dev.ps1)
10 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
11 let local_mpv = std::path::Path::new(&manifest_dir).join("mpv-dev");
12 if local_mpv.exists() {
13 println!(
14 "cargo:rustc-link-search=native={}",
15 local_mpv.display()
16 );
17 }
18 }
19 }
20}
docs/src/installation.md +32 −7
@@ -1,6 +1,6 @@
11# Installation
22
3The YouTube TUI is *not* intended for Windows, pull requests to make it work are welcome.
3The YouTube TUI supports both Linux and Windows.
44
55## Install from Crates.io (recommended)
66
@@ -66,6 +66,33 @@ youtube-tui
6666
6767If installed correctly, a TUI should be launched. Press `q` to close the TUI.
6868
69## Installation on Windows
70
71Install using `cargo`:
72
73```sh
74cargo install youtube-tui
75```
76
77All default features work on Windows. The `sixel` feature uses a pure Rust encoder on Windows (no native dependencies). The `clipboard` feature uses native Windows clipboard APIs.
78
79If you do not have `mpv` installed, you can disable the `mpv` feature:
80
81```sh
82cargo install youtube-tui --no-default-features -F sixel -F halfblock -F clipboard -F rustypipe
83```
84
85### Windows configuration
86
87The default config directory on Windows is `%APPDATA%\youtube-tui\`. Data files (history, thumbnails, etc.) are stored in `%LOCALAPPDATA%\youtube-tui\`.
88
89Default tools on Windows:
90- **Browser**: `explorer` (opens URLs in default browser)
91- **Terminal emulator**: `cmd /c start cmd /k`
92- **Shell**: `cmd`
93
94These can be changed in `main.yml`.
95
6996## Features
7097
7198The TUI has features that can be enabled/disabled when compiling.
@@ -82,23 +109,21 @@ Display images through HalfBlocks, work best in terminals with TrueColour suppor
82109
83110### `sixel` (default)
84111
85Display images with Sixels, allows the display of images at full definition. Not present on windows.
86
87Enabling this will also enable `halfblock`.
112Display images with Sixels, allows the display of images at full definition.
88113
89Requires <a href="https://github.com/saitoha/libsixel" target=_blank>`libsixel`</a>.
114On Linux, this uses the C `libsixel` library for best performance (requires <a href="https://github.com/saitoha/libsixel" target=_blank>`libsixel`</a>). On Windows, a pure Rust encoder is used automatically (no native dependencies).
90115
91116### `clipboard` (default)
92117
93118Allows clipboard pasting in commands and search bar.
94119
95Requires <a href="https://xcb.freedesktop.org/" target=_blank>`libxcb`</a>.
120On Linux, requires <a href="https://xcb.freedesktop.org/" target=_blank>`libxcb`</a>. On Windows, uses native clipboard APIs (no extra dependencies).
96121
97122### `mpv` (default)
98123
99124Embedded audio player
100125
101Requires <a href="https://mpv.io/" target=_blank>`mpv`</a> (libmpv) to be installed in your system.
126Requires <a href="https://mpv.io/" target=_blank>`mpv`</a> (libmpv) to be installed in your system. On Windows, `mpv.dll` must be available in your PATH or next to the executable.
102127
103128### rustypipe (default)
104129
setup-mpv-dev.ps1 added +139
@@ -0,0 +1,139 @@
1# Downloads mpv dev library for Windows (required to build with the `mpv` feature)
2# Usage: .\setup-mpv-dev.ps1
3# This downloads ~30MB and extracts mpv.lib + libmpv-2.dll into a local 'mpv-dev' folder.
4# Then sets MPV_LIB_DIR for the current session.
5
6$ErrorActionPreference = "Stop"
7
8$mpvDevDir = Join-Path $PSScriptRoot "mpv-dev"
9$mpvLib = Join-Path $mpvDevDir "mpv.lib"
10
11if (Test-Path $mpvLib) {
12 Write-Host "mpv.lib already exists at $mpvDevDir, skipping download."
13 $env:MPV_LIB_DIR = $mpvDevDir
14 Write-Host "MPV_LIB_DIR set to $mpvDevDir"
15 return
16}
17
18# Detect architecture
19$arch = if ([Environment]::Is64BitOperatingSystem) { "x86_64" } else { "i686" }
20$url = "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/20260412/mpv-dev-${arch}-20260412-git-062f4bf.7z"
21
22Write-Host "Downloading mpv-dev for $arch..."
23$tempFile = Join-Path $env:TEMP "mpv-dev.7z"
24Invoke-WebRequest -Uri $url -OutFile $tempFile -UserAgent "Mozilla/5.0"
25
26# Create output directory
27New-Item -ItemType Directory -Force -Path $mpvDevDir | Out-Null
28
29# Extract using 7z (ships with scoop, git, or can be installed via scoop install 7zip)
30$7zPaths = @(
31 "7z",
32 "$env:ProgramFiles\7-Zip\7z.exe",
33 "$env:LOCALAPPDATA\Programs\7-Zip\7z.exe",
34 "$env:USERPROFILE\scoop\apps\7zip\current\7z.exe"
35)
36
37$7zExe = $null
38foreach ($p in $7zPaths) {
39 if (Get-Command $p -ErrorAction SilentlyContinue) {
40 $7zExe = $p
41 break
42 }
43 if (Test-Path $p) {
44 $7zExe = $p
45 break
46 }
47}
48
49if (-not $7zExe) {
50 Write-Host "7z not found. Attempting to install via scoop..."
51 scoop install 7zip
52 $7zExe = "$env:USERPROFILE\scoop\apps\7zip\current\7z.exe"
53}
54
55Write-Host "Extracting mpv-dev..."
56$tempExtract = Join-Path $env:TEMP "mpv-dev-extract"
57if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract }
58& $7zExe x $tempFile -o"$tempExtract" -y | Out-Null
59
60# Copy the files we need
61$libFile = Get-ChildItem -Path $tempExtract -Filter "mpv.lib" -Recurse | Select-Object -First 1
62$dllFile = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Select-Object -First 1
63
64if (-not $libFile) {
65 # The shinchiro builds ship libmpv.dll.a (GCC format), not mpv.lib (MSVC format).
66 # Generate mpv.lib from the DLL using dumpbin + lib (MSVC tools).
67 Write-Host "mpv.lib not found in archive. Generating from libmpv-2.dll..."
68
69 $dllForLib = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Select-Object -First 1
70 if (-not $dllForLib) {
71 Write-Error "Could not find libmpv-2.dll in the archive!"
72 }
73
74 # Find MSVC tools (dumpbin, lib) - they're installed but not in PATH
75 $vsBase = "${env:ProgramFiles(x86)}\Microsoft Visual Studio"
76 if (-not (Test-Path $vsBase)) { $vsBase = "$env:ProgramFiles\Microsoft Visual Studio" }
77 $dumpbin = Get-ChildItem -Path $vsBase -Recurse -Filter "dumpbin.exe" -ErrorAction SilentlyContinue |
78 Where-Object { $_.FullName -like "*Hostx64\x64*" -or $_.FullName -like "*HostX64\x64*" } |
79 Select-Object -First 1 -ExpandProperty FullName
80 $libExe = Get-ChildItem -Path $vsBase -Recurse -Filter "lib.exe" -ErrorAction SilentlyContinue |
81 Where-Object { $_.FullName -like "*Hostx64\x64*" -or $_.FullName -like "*HostX64\x64*" } |
82 Select-Object -First 1 -ExpandProperty FullName
83
84 if (-not $dumpbin -or -not $libExe) {
85 Write-Error "Could not find MSVC build tools (dumpbin.exe, lib.exe). Install 'Desktop development with C++' workload."
86 }
87
88 # Export function names from DLL
89 $defPath = Join-Path $mpvDevDir "mpv.def"
90 $exports = & $dumpbin /exports "$($dllForLib.FullName)" 2>&1 |
91 Select-String "^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)" |
92 ForEach-Object { $_.Matches[0].Groups[1].Value }
93
94 # Write .def file
95 $defContent = "LIBRARY libmpv-2`nEXPORTS`n"
96 $defContent += ($exports | ForEach-Object { " $_" }) -join "`n"
97 Set-Content -Path $defPath -Value $defContent -Encoding ASCII
98
99 # Generate .lib from .def
100 $machine = if ($arch -eq "x86_64") { "x64" } else { "x86" }
101 & $libExe /def:"$defPath" /machine:$machine /out:"$mpvDevDir\mpv.lib" 2>&1 | Out-Null
102
103 if (-not (Test-Path "$mpvDevDir\mpv.lib")) {
104 Write-Error "Failed to generate mpv.lib!"
105 } else {
106 Write-Host "Generated mpv.lib successfully."
107 }
108} else {
109 Copy-Item $libFile.FullName $mpvDevDir
110}
111
112if ($dllFile) {
113 Copy-Item $dllFile.FullName $mpvDevDir
114 # Also copy DLL next to the built binary location
115 $targetRelease = Join-Path $PSScriptRoot "target\release"
116 if (Test-Path $targetRelease) {
117 Copy-Item $dllFile.FullName $targetRelease
118 }
119}
120
121# Also grab any other DLLs we might need
122Get-ChildItem -Path $tempExtract -Filter "*.dll" -Recurse | ForEach-Object {
123 Copy-Item $_.FullName $mpvDevDir -Force
124}
125
126# Cleanup
127Remove-Item -Force $tempFile -ErrorAction SilentlyContinue
128Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue
129
130$env:MPV_LIB_DIR = $mpvDevDir
131Write-Host ""
132Write-Host "Done! mpv dev files extracted to: $mpvDevDir"
133Write-Host "MPV_LIB_DIR set to: $mpvDevDir"
134Write-Host ""
135Write-Host "You can now build with:"
136Write-Host " cargo build --release"
137Write-Host ""
138Write-Host "To make this permanent, add to your PowerShell profile:"
139Write-Host " `$env:MPV_LIB_DIR = '$mpvDevDir'"
src/config/appearance.rs +3 −4
@@ -1,5 +1,4 @@
1use crate::{config::serde::*, global::traits::*};
2use home::home_dir;
1use crate::{config::serde::*, global::functions::paths, global::traits::*};
32use ratatui::{style::Color, widgets::BorderType};
43use serde::{Deserialize, Serialize};
54use std::{
@@ -38,8 +37,8 @@ impl AppearanceConfig {
3837 return Ok(appearance);
3938 }
4039
41 let config_path = home_dir().unwrap().join(format!(
42 ".config/youtube-tui/{}.{}",
40 let config_path = paths::config_dir().join(format!(
41 "{}.{}",
4342 AppearanceConfigSerde::LABEL,
4443 EXTENSION
4544 ));
src/config/commandbindings.rs +35 −29
@@ -161,11 +161,17 @@ fn get_command<'a>(
161161
162162// default functions
163163
164/// Returns the appropriate quote character for shell commands on the current platform.
165#[cfg(target_os = "windows")]
166const Q: &str = "\"";
167#[cfg(not(target_os = "windows"))]
168const Q: &str = "'";
169
164170fn global_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
165171 HashMap::from([
166172 (
167173 KeyCodeSerde::Char('f'),
168 HashMap::from([(2, String::from("run ${browser} '${url}'"))]),
174 HashMap::from([(2, format!("run ${{browser}} {Q}${{url}}{Q}"))]),
169175 ),
170176 (
171177 KeyCodeSerde::Char('c'),
@@ -204,9 +210,9 @@ fn global_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
204210
205211fn search_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
206212 HashMap::from([
207 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
208 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
209 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
213 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
214 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
215 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
210216 ])
211217}
212218
@@ -216,41 +222,41 @@ fn channel_main_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
216222
217223fn channel_playlists_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
218224 HashMap::from([
219 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
220 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
221 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
225 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
226 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
227 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
222228 ])
223229}
224230
225231fn channel_videos_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
226232 HashMap::from([
227 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
228 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
229 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
233 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
234 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
235 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
230236 ])
231237}
232238
233239fn playlist_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
234240 HashMap::from([
235 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
236 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
237 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
241 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
242 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
243 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
238244 ])
239245}
240246
241247fn popular_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
242248 HashMap::from([
243 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
244 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
245 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
249 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
250 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
251 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
246252 ])
247253}
248254
249255fn trending_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
250256 HashMap::from([
251 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
252 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
253 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
257 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
258 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
259 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
254260 ])
255261}
256262
@@ -260,9 +266,9 @@ fn video_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
260266
261267fn watchhistory_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
262268 HashMap::from([
263 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
264 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
265 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
269 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
270 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
271 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
266272 ])
267273}
268274
@@ -272,22 +278,22 @@ fn feed_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
272278 KeyCodeSerde::Char('a'),
273279 HashMap::from([(
274280 2,
275 String::from("parrun ${terminal-emulator} mpv '${hover-video-url}' --no-video"),
281 format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-video-url}}{Q} --no-video"),
276282 )]),
277283 ),
278 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-channel-url}/videos' --no-video --loop-playlist=inf --shuffle"))])),
279 (KeyCodeSerde::Char('P'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-channel-url}/videos' --no-video --loop-playlist=inf --shuffle"))])),
284 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-channel-url}}/videos{Q} --no-video --loop-playlist=inf --shuffle"))])),
285 (KeyCodeSerde::Char('P'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-channel-url}}/videos{Q} --no-video --loop-playlist=inf --shuffle"))])),
280286 (
281287 KeyCodeSerde::Char('p'),
282 HashMap::from([(2, String::from("parrun mpv '${hover-video-url}'"))]),
288 HashMap::from([(2, format!("parrun mpv {Q}${{hover-video-url}}{Q}"))]),
283289 ),
284290 ])
285291}
286292
287293fn library_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
288294 HashMap::from([
289 (KeyCodeSerde::Char('a'), HashMap::from([(2, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video"))])),
290 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-url}' --no-video --loop-playlist=inf --shuffle"))])),
291 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("parrun mpv '${hover-url}'"))])),
295 (KeyCodeSerde::Char('a'), HashMap::from([(2, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video"))])),
296 (KeyCodeSerde::Char('A'), HashMap::from([(1, format!("parrun ${{terminal-emulator}} mpv {Q}${{hover-url}}{Q} --no-video --loop-playlist=inf --shuffle"))])),
297 (KeyCodeSerde::Char('p'), HashMap::from([(2, format!("parrun mpv {Q}${{hover-url}}{Q}"))])),
292298 ])
293299}
src/config/commands.rs +75 −36
@@ -98,6 +98,16 @@ fn launch_command_default() -> String {
9898}
9999
100100fn video_default() -> Vec<HashMap<String, String>> {
101 #[cfg(target_os = "windows")]
102 let q = "\"";
103 #[cfg(not(target_os = "windows"))]
104 let q = "'";
105
106 #[cfg(target_os = "windows")]
107 let rm_cmd = |pattern: &str| format!("run cmd /c del /q /s \"{pattern}\"");
108 #[cfg(not(target_os = "windows"))]
109 let rm_cmd = |pattern: &str| format!("run rm -rf '{pattern}'");
110
101111 vec![
102112 HashMap::from([(
103113 String::from("Reload updated video"),
@@ -105,20 +115,16 @@ fn video_default() -> Vec<HashMap<String, String>> {
105115 )]),
106116 HashMap::from([(
107117 String::from("Play video"),
108 String::from("parrun ${video-player} '${embed-url}'"),
118 format!("parrun ${{video-player}} {q}${{embed-url}}{q}"),
109119 )]),
110120 HashMap::from([(
111121 String::from("Play audio"),
112 String::from("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile '${embed-url}' ;; echo mpv Player started"),
122 format!("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile {q}${{embed-url}}{q} ;; echo mpv Player started"),
113123 )]),
114124 HashMap::from([(
115125 String::from("Play audio (loop)"),
116 String::from("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile '${embed-url}' ;; echo mpv Player started"),
126 format!("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile {q}${{embed-url}}{q} ;; echo mpv Player started"),
117127 )]),
118 // HashMap::from([(
119 // String::from("Add to queue"),
120 // String::from("mpv loadfile '${embed-url}' appendplay;; echo mpv Added to queue"),
121 // )]),
122128 HashMap::from([(
123129 String::from("View channel"),
124130 String::from("channel ${channel-id}"),
@@ -129,7 +135,7 @@ fn video_default() -> Vec<HashMap<String, String>> {
129135 )]),
130136 HashMap::from([(
131137 String::from("Open in browser"),
132 String::from("parrun ${browser} '${url}'"),
138 format!("parrun ${{browser}} {q}${{url}}{q}"),
133139 )]),
134140 HashMap::from([(
135141 String::from("Toggle bookmark"),
@@ -137,11 +143,11 @@ fn video_default() -> Vec<HashMap<String, String>> {
137143 )]),
138144 HashMap::from([(
139145 String::from("Save video to library"),
140 String::from("bookmark ${id} ;; run rm -rf '${save-path}${id}.*' ;; parrun ${terminal-emulator} ${youtube-downloader} '${embed-url}' -o '${save-path}%(title)s[%(id)s].%(ext)s'")
146 format!("bookmark ${{id}} ;; {} ;; parrun ${{terminal-emulator}} ${{youtube-downloader}} {q}${{embed-url}}{q} -o {q}${{save-path}}%(title)s[${{id}}].%(ext)s{q}", rm_cmd("${save-path}${id}.*"))
141147 )]),
142148 HashMap::from([(
143149 String::from("Save audio to library"),
144 String::from("bookmark ${id} ;; parrun rm -rf '${save-path}${id}.*' ;; parrun ${terminal-emulator} ${youtube-downloader} '${embed-url}' -x -o '${save-path}%(title)s[%(id)s].%(ext)s'")
150 format!("bookmark ${{id}} ;; {} ;; parrun ${{terminal-emulator}} ${{youtube-downloader}} {q}${{embed-url}}{q} -x -o {q}${{save-path}}%(title)s[${{id}}].%(ext)s{q}", rm_cmd("${save-path}${id}.*"))
145151 )]),
146152 HashMap::from([(
147153 String::from("Mode: ${provider}"),
@@ -151,6 +157,16 @@ fn video_default() -> Vec<HashMap<String, String>> {
151157}
152158
153159fn saved_video_default() -> Vec<HashMap<String, String>> {
160 #[cfg(target_os = "windows")]
161 let q = "\"";
162 #[cfg(not(target_os = "windows"))]
163 let q = "'";
164
165 #[cfg(target_os = "windows")]
166 let rm_cmd = |pattern: &str| format!("run cmd /c del /q /s \"{pattern}\"");
167 #[cfg(not(target_os = "windows"))]
168 let rm_cmd = |pattern: &str| format!("run rm {pattern}");
169
154170 vec![
155171 HashMap::from([(
156172 String::from("Reload updated video"),
@@ -158,20 +174,16 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
158174 )]),
159175 HashMap::from([(
160176 String::from("[Offline] Play saved file"),
161 String::from("parrun ${video-player} '${offline-path}' --force-window"),
177 format!("parrun ${{video-player}} {q}${{offline-path}}{q} --force-window"),
162178 )]),
163179 HashMap::from([(
164180 String::from("[Offline] Play saved file (audio)"),
165 String::from("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile '${offline-path}' ;; echo mpv Player started"),
181 format!("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile {q}${{offline-path}}{q} ;; echo mpv Player started"),
166182 )]),
167183 HashMap::from([(
168184 String::from("[Offline] Play saved file (audio loop)"),
169 String::from("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile '${offline-path}' ;; echo mpv Player started"),
185 format!("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile {q}${{offline-path}}{q} ;; echo mpv Player started"),
170186 )]),
171 // HashMap::from([(
172 // String::from("[Offline] Add to queue"),
173 // String::from("mpv loadfile '${offline-path}' appendplay ;; echo mpv Added to queue"),
174 // )]),
175187 HashMap::from([(
176188 String::from("View channel"),
177189 String::from("channel ${channel-id}"),
@@ -182,7 +194,7 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
182194 )]),
183195 HashMap::from([(
184196 String::from("Open in browser"),
185 String::from("parrun ${browser} '${url}'"),
197 format!("parrun ${{browser}} {q}${{url}}{q}"),
186198 )]),
187199 HashMap::from([(
188200 String::from("Toggle bookmark"),
@@ -190,20 +202,25 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
190202 )]),
191203 HashMap::from([(
192204 String::from("Redownload video to library"),
193 String::from("bookmark ${id} ;; run rm ${save-path}*${id}*.* ;; parrun ${terminal-emulator} ${youtube-downloader} ${embed-url} -o '${save-path}%(title)s[%(id)s].%(ext)s'"),
205 format!("bookmark ${{id}} ;; {} ;; parrun ${{terminal-emulator}} ${{youtube-downloader}} ${{embed-url}} -o {q}${{save-path}}%(title)s[${{id}}].%(ext)s{q}", rm_cmd("${save-path}*${id}*.*")),
194206 )]),
195207 HashMap::from([(
196208 String::from("Redownload audio to library"),
197 String::from("bookmark ${id} ;; run rm ${save-path}*${id}*.* ;; parrun ${terminal-emulator} ${youtube-downloader} ${embed-url} -x -o '${save-path}%(title)s[%(id)s].%(ext)s'")
209 format!("bookmark ${{id}} ;; {} ;; parrun ${{terminal-emulator}} ${{youtube-downloader}} ${{embed-url}} -x -o {q}${{save-path}}%(title)s[${{id}}].%(ext)s{q}", rm_cmd("${save-path}*${id}*.*"))
198210 )]),
199211 HashMap::from([(
200212 String::from("Delete saved file"),
201 String::from("run rm ${save-path}*${id}*.*")
213 rm_cmd("${save-path}*${id}*.*")
202214 )]),
203215 ]
204216}
205217
206218fn playlist_default() -> Vec<HashMap<String, String>> {
219 #[cfg(target_os = "windows")]
220 let q = "\"";
221 #[cfg(not(target_os = "windows"))]
222 let q = "'";
223
207224 vec![
208225 HashMap::from([(String::from("Switch view"), String::from("%switch-view%"))]),
209226 HashMap::from([(
@@ -222,10 +239,6 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
222239 String::from("Shuffle play all (audio loop)"),
223240 String::from("mpv stop ;; resume ;; ${mpv-queuelist} ;; mpv sprop loop-playlist yes ;; mpv playlist-shuffle ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
224241 )]),
225 // HashMap::from([(
226 // String::from("Add all to queue"),
227 // String::from("${mpv-queuelist} ;; echo mpv Queued playlist"),
228 // )]),
229242 HashMap::from([(
230243 String::from("View channel"),
231244 String::from("channel ${channel-id}"),
@@ -236,7 +249,7 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
236249 )]),
237250 HashMap::from([(
238251 String::from("Open in browser"),
239 String::from("parrun ${browser} '${url}'"),
252 format!("parrun ${{browser}} {q}${{url}}{q}"),
240253 )]),
241254 HashMap::from([(
242255 String::from("Toggle bookmark"),
@@ -244,11 +257,21 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
244257 )]),
245258 HashMap::from([(
246259 String::from("Save playlist videos to library"),
247 String::from("bookmark ${id} ;; run rm -rf '${save-path}*${id}*' ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"")
260 {
261 #[cfg(target_os = "windows")]
262 { String::from("bookmark ${id} ;; run cmd /c rd /s /q \"${save-path}*${id}*\" ;; parrun ${terminal-emulator} ${youtube-downloader} ${all-videos} -o \"${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s\"") }
263 #[cfg(not(target_os = "windows"))]
264 { String::from("bookmark ${id} ;; run rm -rf '${save-path}*${id}*' ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"") }
265 }
248266 )]),
249267 HashMap::from([(
250268 String::from("Save playlist audio to library"),
251 String::from("bookmark ${id} ;; run rm -rf '${save-path}*${id}*' ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -x -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"")
269 {
270 #[cfg(target_os = "windows")]
271 { String::from("bookmark ${id} ;; run cmd /c rd /s /q \"${save-path}*${id}*\" ;; parrun ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o \"${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s\"") }
272 #[cfg(not(target_os = "windows"))]
273 { String::from("bookmark ${id} ;; run rm -rf '${save-path}*${id}*' ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -x -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"") }
274 }
252275 )]),
253276 HashMap::from([(
254277 String::from("Mode: ${provider}"),
@@ -258,6 +281,11 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
258281}
259282
260283fn saved_playlist_default() -> Vec<HashMap<String, String>> {
284 #[cfg(target_os = "windows")]
285 let q = "\"";
286 #[cfg(not(target_os = "windows"))]
287 let q = "'";
288
261289 vec![
262290 HashMap::from([(String::from("Switch view"), String::from("%switch-view%"))]),
263291 HashMap::from([(
@@ -276,10 +304,6 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
276304 String::from("[Offline] Shuffle play all (audio loop)"),
277305 String::from("mpv stop ;; resume ;; ${offline-queuelist} ;; mpv sprop loop-playlist yes ;; mpv playlist-shuffle ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
278306 )]),
279 // HashMap::from([(
280 // String::from("[Offline] Add all to queue"),
281 // String::from("${offline-queuelist} ;; echo mpv Queued playlist"),
282 // )]),
283307 HashMap::from([(
284308 String::from("View channel"),
285309 String::from("channel ${channel-id}"),
@@ -290,7 +314,7 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
290314 )]),
291315 HashMap::from([(
292316 String::from("Open in browser"),
293 String::from("parrun ${browser} '${url}'"),
317 format!("parrun ${{browser}} {q}${{url}}{q}"),
294318 )]),
295319 HashMap::from([(
296320 String::from("Toggle bookmark"),
@@ -298,15 +322,30 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
298322 )]),
299323 HashMap::from([(
300324 String::from("Redownload playlist videos to library"),
301 String::from("bookmark ${id} ;; run rm -rf ${save-path}*${id}* ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"")
325 {
326 #[cfg(target_os = "windows")]
327 { String::from("bookmark ${id} ;; run cmd /c rd /s /q \"${save-path}*${id}*\" ;; parrun ${terminal-emulator} ${youtube-downloader} ${all-videos} -o \"${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s\"") }
328 #[cfg(not(target_os = "windows"))]
329 { String::from("bookmark ${id} ;; run rm -rf ${save-path}*${id}* ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"") }
330 }
302331 )]),
303332 HashMap::from([(
304333 String::from("Redownload playlist audio to library"),
305 String::from("bookmark ${id} ;; run rm -rf ${save-path}*${id}* ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -x -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"")
334 {
335 #[cfg(target_os = "windows")]
336 { String::from("bookmark ${id} ;; run cmd /c rd /s /q \"${save-path}*${id}*\" ;; parrun ${terminal-emulator} ${youtube-downloader} ${all-videos} -x -o \"${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s\"") }
337 #[cfg(not(target_os = "windows"))]
338 { String::from("bookmark ${id} ;; run rm -rf ${save-path}*${id}* ;; parrun ${terminal-emulator} bash -c \"${youtube-downloader} ${all-videos} -x -o '\"'${save-path}${title}[${id}]/%(title)s[%(id)s].%(ext)s'\"'\"") }
339 }
306340 )]),
307341 HashMap::from([(
308342 String::from("Delete saved files"),
309 String::from("run rm -rf ${save-path}*${id}*")
343 {
344 #[cfg(target_os = "windows")]
345 { String::from("run cmd /c rd /s /q \"${save-path}*${id}*\"") }
346 #[cfg(not(target_os = "windows"))]
347 { String::from("run rm -rf ${save-path}*${id}*") }
348 }
310349 )]),
311350 ]
312351}
src/config/keybindings.rs +3 −3
@@ -3,11 +3,11 @@ use super::{
33 WriteConfig,
44};
55use crate::global::{
6 functions::paths,
67 structs::KeyAction,
78 traits::{ConfigTrait, EXTENSION},
89};
910use crossterm::event::{KeyCode, KeyEvent};
10use home::home_dir;
1111use serde::{Deserialize, Serialize};
1212use std::{
1313 collections::HashMap,
@@ -174,8 +174,8 @@ impl KeyBindingsConfig {
174174 return Ok(keybindings);
175175 }
176176
177 let config_path = home_dir().unwrap().join(format!(
178 ".config/youtube-tui/{}.{}",
177 let config_path = paths::config_dir().join(format!(
178 "{}.{}",
179179 KeyBindingsConfigSerde::LABEL,
180180 EXTENSION
181181 ));
src/config/main.rs +50 −18
@@ -287,27 +287,59 @@ const fn write_to_config_default() -> WriteConfig {
287287}
288288
289289fn default_env() -> HashMap<String, String> {
290 HashMap::from([
291 (String::from("video-player"), String::from("mpv")),
292 (String::from("browser"), String::from("xdg-open")),
293 (
294 String::from("terminal-emulator"),
295 String::from("konsole -e"),
296 ),
297 (String::from("youtube-downloader"), String::from("yt-dlp")),
298 (
299 String::from("download-path"),
300 String::from("~/Downloads/%(title)s-%(id)s.%(ext)s"),
301 ),
302 (
303 String::from("save-path"),
304 String::from("~/.local/share/youtube-tui/saved/"),
305 ),
306 ])
290 use crate::global::functions::paths;
291
292 #[cfg(target_os = "windows")]
293 {
294 HashMap::from([
295 (String::from("video-player"), String::from("mpv")),
296 (String::from("browser"), String::from("explorer")),
297 (
298 String::from("terminal-emulator"),
299 String::from("cmd /c start cmd /k"),
300 ),
301 (String::from("youtube-downloader"), String::from("yt-dlp")),
302 (
303 String::from("download-path"),
304 paths::default_download_path(),
305 ),
306 (
307 String::from("save-path"),
308 paths::default_save_path(),
309 ),
310 ])
311 }
312 #[cfg(not(target_os = "windows"))]
313 {
314 HashMap::from([
315 (String::from("video-player"), String::from("mpv")),
316 (String::from("browser"), String::from("xdg-open")),
317 (
318 String::from("terminal-emulator"),
319 String::from("konsole -e"),
320 ),
321 (String::from("youtube-downloader"), String::from("yt-dlp")),
322 (
323 String::from("download-path"),
324 String::from("~/Downloads/%(title)s-%(id)s.%(ext)s"),
325 ),
326 (
327 String::from("save-path"),
328 String::from("~/.local/share/youtube-tui/saved/"),
329 ),
330 ])
331 }
307332}
308333
309334fn shell_default() -> String {
310 String::from("sh")
335 #[cfg(target_os = "windows")]
336 {
337 String::from("cmd")
338 }
339 #[cfg(not(target_os = "windows"))]
340 {
341 String::from("sh")
342 }
311343}
312344
313345fn api_key_default() -> String {
src/config/remap.rs +6 −4
@@ -6,11 +6,13 @@ use std::{
66};
77
88use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
9use home::home_dir;
109use serde::{Deserialize, Serialize};
1110use typemap::Key;
1211
13use crate::global::traits::{ConfigTrait, EXTENSION};
12use crate::global::{
13 functions::paths,
14 traits::{ConfigTrait, EXTENSION},
15};
1416
1517use super::{serde::KeyCodeSerde, WriteConfig};
1618
@@ -86,8 +88,8 @@ impl RemapConfig {
8688 return Ok(keybindings);
8789 }
8890
89 let config_path = home_dir().unwrap().join(format!(
90 ".config/youtube-tui/{}.{}",
91 let config_path = paths::config_dir().join(format!(
92 "{}.{}",
9193 RemapConfigSerde::LABEL,
9294 EXTENSION
9395 ));
src/exit.rs +4 −5
@@ -1,10 +1,10 @@
1use home::home_dir;
21use std::{collections::HashSet, error::Error, fs};
32use tui_additions::framework::Framework;
43
54use crate::{
65 config::MainConfig,
76 global::{
7 functions::paths,
88 structs::*,
99 traits::{Collection, CollectionNoId},
1010 },
@@ -51,10 +51,9 @@ pub fn exit(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
5151
5252 let cached_before = CACHED_BEFORE.get().unwrap();
5353
54 let info_path = home_dir().unwrap().join(".local/share/youtube-tui/info/");
55 let thumbnail_path = home_dir()
56 .unwrap()
57 .join(".local/share/youtube-tui/thumbnails/");
54 let data = paths::data_dir();
55 let info_path = data.join("info");
56 let thumbnail_path = data.join("thumbnails");
5857
5958 // remove cache that no longer exists
6059 for deleted in cached_before
src/global/functions/download_all_images.rs +1 −3
@@ -46,9 +46,7 @@ pub fn download_all_images(downloads: Vec<Option<DownloadRequest>>) {
4646 return;
4747 }
4848
49 let path = home::home_dir()
50 .expect("Cannot get your home directory")
51 .join(".local/share/youtube-tui/thumbnails/");
49 let path = super::paths::data_dir().join("thumbnails");
5250
5351 downloads.into_iter().flatten().for_each(|req| {
5452 LocalStore::add_image(req.id.clone());
src/global/functions/find_library.rs +23 −9
@@ -1,16 +1,30 @@
11use std::{fs, path::PathBuf};
22
3use home::home_dir;
4
53use crate::config::MainConfig;
64
5use super::paths;
6
77pub fn find_library_item(id: &str, mainconfig: &MainConfig) -> Option<PathBuf> {
8 fs::read_dir(
9 home_dir()
8 let save_path_str = mainconfig.env.get("save-path")?;
9
10 // Resolve save-path: handle tilde expansion for backward compatibility
11 let save_path = if save_path_str.starts_with("~/") || save_path_str.starts_with("~\\") {
12 home::home_dir()
1013 .unwrap()
11 .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
12 )
13 .ok()?
14 .filter_map(|entry| Some(entry.ok()?.path()))
15 .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))
14 .join(&save_path_str[2..])
15 } else {
16 // If it's an absolute path (e.g., from paths::default_save_path()), use directly
17 let p = PathBuf::from(save_path_str);
18 if p.is_absolute() {
19 p
20 } else {
21 // Relative path: treat as relative to data_dir for safety
22 paths::data_dir().join(save_path_str)
23 }
24 };
25
26 fs::read_dir(save_path)
27 .ok()?
28 .filter_map(|entry| Some(entry.ok()?.path()))
29 .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))
1630}
src/global/functions/init_move.rs +3 −4
@@ -1,11 +1,10 @@
11use std::fs;
22
3use home::home_dir;
3use super::paths;
44
55pub fn init_move() {
6 let home_dir = home_dir().unwrap();
7 let store_dir = home_dir.join(".local/share/youtube-tui/");
8 let cache_dir = home_dir.join(".cache/youtube-tui");
6 let store_dir = paths::data_dir();
7 let cache_dir = paths::cache_dir();
98
109 let store_info_dir = store_dir.join("info/");
1110 let cache_info_dir = cache_dir.join("info/");
src/global/functions/mod.rs +1
@@ -35,3 +35,4 @@ mod key_input;
3535pub use key_input::*;
3636mod find_library;
3737pub use find_library::*;
38pub mod paths;
src/global/functions/paths.rs added +68
@@ -0,0 +1,68 @@
1use std::path::PathBuf;
2
3/// Returns the configuration directory for youtube-tui.
4///
5/// - Linux: `~/.config/youtube-tui/`
6/// - Windows: `%APPDATA%\youtube-tui\`
7/// - macOS: `~/Library/Application Support/youtube-tui/`
8pub fn config_dir() -> PathBuf {
9 dirs::config_dir()
10 .unwrap_or_else(|| home::home_dir().unwrap().join(".config"))
11 .join("youtube-tui")
12}
13
14/// Returns the data directory for youtube-tui.
15///
16/// - Linux: `~/.local/share/youtube-tui/`
17/// - Windows: `%LOCALAPPDATA%\youtube-tui\`
18/// - macOS: `~/Library/Application Support/youtube-tui/`
19pub fn data_dir() -> PathBuf {
20 dirs::data_local_dir()
21 .unwrap_or_else(|| home::home_dir().unwrap().join(".local").join("share"))
22 .join("youtube-tui")
23}
24
25/// Returns the cache directory for youtube-tui.
26///
27/// - Linux: `~/.cache/youtube-tui/`
28/// - Windows: `%LOCALAPPDATA%\youtube-tui\cache\`
29/// - macOS: `~/Library/Caches/youtube-tui/`
30pub fn cache_dir() -> PathBuf {
31 dirs::cache_dir()
32 .unwrap_or_else(|| home::home_dir().unwrap().join(".cache"))
33 .join("youtube-tui")
34}
35
36/// Returns the storage directory for rustypipe.
37///
38/// - Linux: `~/.local/share/rustypipe/`
39/// - Windows: `%LOCALAPPDATA%\rustypipe\`
40/// - macOS: `~/Library/Application Support/rustypipe/`
41pub fn rustypipe_dir() -> PathBuf {
42 dirs::data_local_dir()
43 .unwrap_or_else(|| home::home_dir().unwrap().join(".local").join("share"))
44 .join("rustypipe")
45}
46
47/// Returns the default save path string for the `save-path` env variable.
48/// This is used in command strings, so it returns a String with trailing separator.
49pub fn default_save_path() -> String {
50 let p = data_dir().join("saved");
51 let mut s = p.to_string_lossy().to_string();
52 // Ensure trailing path separator for command substitution
53 if !s.ends_with(std::path::MAIN_SEPARATOR) {
54 s.push(std::path::MAIN_SEPARATOR);
55 }
56 s
57}
58
59/// Returns the default download path string for the `download-path` env variable.
60pub fn default_download_path() -> String {
61 let downloads = dirs::download_dir()
62 .unwrap_or_else(|| home::home_dir().unwrap().join("Downloads"));
63 let mut s = downloads.to_string_lossy().to_string();
64 if !s.ends_with(std::path::MAIN_SEPARATOR) {
65 s.push(std::path::MAIN_SEPARATOR);
66 }
67 format!("{s}%(title)s-%(id)s.%(ext)s")
68}
src/global/functions/run_command.rs +35 −11
@@ -4,7 +4,6 @@ use crate::{
44 load_configs,
55};
66use crossterm::event::{KeyEvent, KeyModifiers};
7use home::home_dir;
87use ratatui::{backend::CrosstermBackend, Terminal};
98use std::{
109 env,
@@ -156,17 +155,14 @@ pub fn run_single_command(
156155 }
157156 ["rmcache", id] => {
158157 let res = LocalStore::rm_cache(id);
158 let data = paths::data_dir();
159159 let _ = fs::remove_file(
160 home_dir()
161 .unwrap()
162 .join(".local/share/youtube-tui/info/")
160 data.join("info")
163161 .join(id)
164162 .with_extension("json"),
165163 );
166164 let _ = fs::remove_file(
167 home_dir()
168 .unwrap()
169 .join(".local/share/youtube-tui/thumbnails/")
165 data.join("thumbnails")
170166 .join(id),
171167 );
172168 if res {
@@ -351,9 +347,11 @@ pub fn run_single_command(
351347 let command = command[1..].join(" ");
352348 *framework.data.global.get_mut::<Message>().unwrap() =
353349 Message::Success(command.clone());
350 let shell = &framework.data.global.get::<MainConfig>().unwrap().shell;
351 let shell_flag = shell_flag(shell);
354352 if let Ok(mut child) =
355 Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
356 .args(["-c", &command])
353 Command::new(shell)
354 .args([shell_flag, &command])
357355 .stdout(Stdio::null())
358356 .stderr(Stdio::null())
359357 .spawn()
@@ -365,8 +363,10 @@ pub fn run_single_command(
365363 let command = command[1..].join(" ");
366364 *framework.data.global.get_mut::<Message>().unwrap() =
367365 Message::Success(command.clone());
368 let _ = Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
369 .args(["-c", &command])
366 let shell = &framework.data.global.get::<MainConfig>().unwrap().shell;
367 let shell_flag = shell_flag(shell);
368 let _ = Command::new(shell)
369 .args([shell_flag, &command])
370370 .stdout(Stdio::null())
371371 .stderr(Stdio::null())
372372 .spawn();
@@ -655,6 +655,30 @@ pub fn run_single_command(
655655 }
656656}
657657
658/// Returns the appropriate shell flag for the given shell command.
659///
660/// On Windows, `cmd` and `cmd.exe` use `/C`, `powershell`/`pwsh` use `-Command`,
661/// and everything else (e.g., bash from Git for Windows) uses `-c`.
662/// On non-Windows platforms, always uses `-c`.
663fn shell_flag(shell: &str) -> &'static str {
664 #[cfg(target_os = "windows")]
665 {
666 let shell_lower = shell.to_lowercase();
667 if shell_lower == "cmd" || shell_lower == "cmd.exe" {
668 "/C"
669 } else if shell_lower.contains("powershell") || shell_lower.contains("pwsh") {
670 "-Command"
671 } else {
672 "-c"
673 }
674 }
675 #[cfg(not(target_os = "windows"))]
676 {
677 let _ = shell;
678 "-c"
679 }
680}
681
658682const HELLO_WORLDS: &[&str] = &[
659683 "printf(\"Hello World\")",
660684 "std::cout << \"Hello World\"",
src/global/structs/history.rs +4 −4
@@ -13,7 +13,7 @@ impl Key for WatchHistory {
1313}
1414
1515impl Collection<Item> for WatchHistory {
16 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
16 const INDEX_PATH: &'static str = "watch_history.json";
1717
1818 fn items(&self) -> &Vec<Item> {
1919 &self.0
@@ -36,7 +36,7 @@ impl Key for SearchHistory {
3636}
3737
3838impl CollectionNoId<String> for SearchHistory {
39 const INDEX_PATH: &'static str = ".local/share/youtube-tui/search_history.json";
39 const INDEX_PATH: &'static str = "search_history.json";
4040
4141 fn items(&self) -> &Vec<String> {
4242 &self.0
@@ -59,7 +59,7 @@ impl Key for CommandHistory {
5959}
6060
6161impl CollectionNoId<String> for CommandHistory {
62 const INDEX_PATH: &'static str = ".local/share/youtube-tui/command_history.json";
62 const INDEX_PATH: &'static str = "command_history.json";
6363
6464 fn items(&self) -> &Vec<String> {
6565 &self.0
@@ -83,7 +83,7 @@ impl Key for ChannelHistory {
8383}
8484
8585impl CollectionNoId<String> for ChannelHistory {
86 const INDEX_PATH: &'static str = ".local/share/youtube-tui/channel_history.json";
86 const INDEX_PATH: &'static str = "channel_history.json";
8787
8888 fn items(&self) -> &Vec<String> {
8989 &self.0
src/global/structs/library.rs +1 −1
@@ -12,7 +12,7 @@ impl Key for Library {
1212}
1313
1414impl Collection<Item> for Library {
15 const INDEX_PATH: &'static str = ".local/share/youtube-tui/library.json";
15 const INDEX_PATH: &'static str = "library.json";
1616
1717 fn items(&self) -> &Vec<Item> {
1818 &self.0
src/global/structs/localstore.rs +7 −10
@@ -6,13 +6,12 @@
66// this needs to change
77use std::{
88 collections::{HashMap, HashSet},
9 env::home_dir,
109 fs::{self, OpenOptions},
1110 io::Write,
1211 sync::OnceLock,
1312};
1413
15use crate::global::structs::Item;
14use crate::global::{functions::paths, structs::Item};
1615
1716static mut LOCALSTORE: OnceLock<LocalStore> = OnceLock::new();
1817
@@ -48,10 +47,9 @@ impl LocalStore {
4847 .unwrap()
4948 .downloaded_images
5049 .remove(id);
51 let info_path = home_dir().unwrap().join(".local/share/youtube-tui/info/");
52 let thumbnail_path = home_dir()
53 .unwrap()
54 .join(".local/share/youtube-tui/thumbnails/");
50 let data = paths::data_dir();
51 let info_path = data.join("info");
52 let thumbnail_path = data.join("thumbnails");
5553 let _ = fs::remove_file(info_path.join(id).with_extension("json"));
5654 let _ = fs::remove_file(thumbnail_path.join(id));
5755
@@ -64,9 +62,8 @@ impl LocalStore {
6462 match localstore.info.get(id) {
6563 Some(LocalRecord { item, .. }) => Some(item.clone()),
6664 None => {
67 let path = home_dir()
68 .unwrap()
69 .join(format!(".local/share/youtube-tui/info/{id}.json"));
65 let path = paths::data_dir()
66 .join(format!("info/{id}.json"));
7067
7168 if path.exists() {
7269 serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?
@@ -83,7 +80,7 @@ impl LocalStore {
8380 }
8481
8582 pub fn save_only(ids: &HashSet<String>) {
86 let info_path = home_dir().unwrap().join(".local/share/youtube-tui/info/");
83 let info_path = paths::data_dir().join("info");
8784
8885 for (id, LocalRecord { item, is_new }) in unsafe { LOCALSTORE.get() }.unwrap().info.iter() {
8986 let info = info_path.join(id).with_extension("json");
src/global/structs/providers/rustypipe.rs +1 −1
@@ -24,7 +24,7 @@ impl Default for RustyPipeWrapper {
2424 fn default() -> Self {
2525 Self(
2626 RustyPipe::builder()
27 .storage_dir(home::home_dir().unwrap().join(".local/share/rustypipe"))
27 .storage_dir(crate::global::functions::paths::rustypipe_dir())
2828 .build()
2929 .unwrap(),
3030 )
src/global/structs/subscriptions.rs +5 −7
@@ -7,7 +7,6 @@ use crate::{
77 },
88};
99use chrono::Utc;
10use home::home_dir;
1110use serde::*;
1211use std::{
1312 error::Error,
@@ -247,9 +246,8 @@ fn update_channel_cache(
247246 channel: &FullChannelItem,
248247 image_index: usize,
249248) -> Result<(), Box<dyn Error>> {
250 let home_dir = home_dir().unwrap();
251 let cache_path = home_dir.join(format!(
252 ".local/share/youtube-tui/channels/{}.json",
249 let cache_path = crate::global::functions::paths::data_dir().join(format!(
250 "channels/{}.json",
253251 channel.id
254252 ));
255253
@@ -318,7 +316,7 @@ impl CollectionItem for SubItem {
318316}
319317
320318impl Collection<SubItem> for Subscriptions {
321 const INDEX_PATH: &'static str = ".local/share/youtube-tui/subscriptions.json";
319 const INDEX_PATH: &'static str = "subscriptions.json";
322320
323321 fn items(&self) -> &Vec<SubItem> {
324322 &self.0
@@ -337,7 +335,7 @@ impl Collection<SubItem> for Subscriptions {
337335 .truncate(true)
338336 .write(true)
339337 .create(true)
340 .open(home_dir().unwrap().join(Self::INDEX_PATH))?;
338 .open(crate::global::functions::paths::data_dir().join(Self::INDEX_PATH))?;
341339
342340 let save_string = serde_json::to_string_pretty(self)?;
343341 file.write_all(save_string.as_bytes())?;
@@ -349,7 +347,7 @@ impl Collection<SubItem> for Subscriptions {
349347 }
350348
351349 fn load() -> Self {
352 let path = home_dir().unwrap().join(Self::INDEX_PATH);
350 let path = crate::global::functions::paths::data_dir().join(Self::INDEX_PATH);
353351 let res = (|| -> Result<Self, Box<dyn Error>> {
354352 let file_string = fs::read_to_string(&path)?;
355353 let deserialized = serde_json::from_str(&file_string)?;
src/global/traits/collection.rs +13 −11
@@ -1,4 +1,3 @@
1use home::home_dir;
21use serde::{de::DeserializeOwned, Serialize};
32use std::{
43 error::Error,
@@ -6,6 +5,8 @@ use std::{
65 io::Write,
76};
87
8use crate::global::functions::paths;
9
910pub trait CollectionItem {
1011 fn id(&self) -> Option<&str>;
1112 fn children_ids(&self) -> Vec<&str>;
@@ -40,7 +41,7 @@ where
4041 .filter(|id| !id.is_empty())
4142 .collect::<Vec<&str>>(),
4243 )?;
43 let path = home_dir().unwrap().join(Self::INDEX_PATH);
44 let path = paths::data_dir().join(Self::INDEX_PATH);
4445
4546 let mut file = OpenOptions::new()
4647 .write(true)
@@ -88,7 +89,7 @@ where
8889
8990 /// loads watch history from file
9091 fn load() -> Self {
91 let path = home_dir().unwrap().join(Self::INDEX_PATH);
92 let path = paths::data_dir().join(Self::INDEX_PATH);
9293 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
9394 let file_string = fs::read_to_string(&path)?;
9495 let deserialized = serde_json::from_str(&file_string)?;
@@ -98,7 +99,7 @@ where
9899 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
99100 // which case returns Self::default()
100101 let items = if let Ok(deserialized) = res {
101 let info = home_dir().unwrap().join(".local/share/youtube-tui/info/");
102 let info = paths::data_dir().join("info");
102103 deserialized
103104 .into_iter()
104105 .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
@@ -124,11 +125,12 @@ where
124125
125126 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
126127 fn exit_move(&self) {
127 let home_dir = home_dir().unwrap();
128 let store_thumbnails_path = home_dir.join(".local/share/youtube-tui/thumbnails/");
129 let store_info_path = home_dir.join(".local/share/youtube-tui/info/");
130 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
131 let cache_info_path = home_dir.join(".cache/youtube-tui/info");
128 let data = paths::data_dir();
129 let cache = paths::cache_dir();
130 let store_thumbnails_path = data.join("thumbnails");
131 let store_info_path = data.join("info");
132 let cache_thumbnails_path = cache.join("thumbnails");
133 let cache_info_path = cache.join("info");
132134
133135 self.items().iter().for_each(|item| {
134136 let id = item.id().unwrap_or("invalid-dump");
@@ -189,7 +191,7 @@ where
189191 /// saves the current state of watch history into a file
190192 fn save(&self) -> Result<(), Box<dyn Error>> {
191193 let save_string = serde_json::to_string_pretty(&self)?;
192 let path = home_dir().unwrap().join(Self::INDEX_PATH);
194 let path = paths::data_dir().join(Self::INDEX_PATH);
193195
194196 let mut file = OpenOptions::new()
195197 .write(true)
@@ -218,7 +220,7 @@ where
218220
219221 /// loads watch history from file
220222 fn load() -> Self {
221 let path = home_dir().unwrap().join(Self::INDEX_PATH);
223 let path = paths::data_dir().join(Self::INDEX_PATH);
222224 let res = (|| -> Result<Vec<T>, Box<dyn Error>> {
223225 let file_string = fs::read_to_string(&path)?;
224226 let deserialized = serde_json::from_str(&file_string)?;
src/global/traits/configtrait.rs +2 −4
@@ -1,4 +1,3 @@
1use home::home_dir;
21use serde::{de::DeserializeOwned, Serialize};
32use std::{
43 error::Error,
@@ -6,7 +5,7 @@ use std::{
65 io::Write,
76};
87
9use crate::config::WriteConfig;
8use crate::{config::WriteConfig, global::functions::paths};
109
1110pub const EXTENSION: &str = "yml";
1211
@@ -18,9 +17,8 @@ pub trait ConfigTrait {
1817 where
1918 Self: Serialize + DeserializeOwned + Default + Clone,
2019 {
21 let home_dir = home_dir().unwrap();
2220 let config_path =
23 home_dir.join(format!(".config/youtube-tui/{}.{}", Self::LABEL, EXTENSION));
21 paths::config_dir().join(format!("{}.{}", Self::LABEL, EXTENSION));
2422
2523 // The config struct
2624 let config: Self = {
src/init.rs +6 −12
@@ -2,7 +2,6 @@ use crate::{
22 config::*,
33 global::{functions::*, structs::*, traits::*},
44};
5use home::home_dir;
65use ratatui::{backend::CrosstermBackend, Terminal};
76use std::{
87 collections::HashSet,
@@ -29,23 +28,19 @@ pub fn init(
2928 command: Option<&str>,
3029) -> Result<(), Box<dyn Error>> {
3130 LocalStore::init();
32 let home_dir = home_dir().unwrap();
3331 RUNTIME
3432 .set(Builder::new_current_thread().enable_all().build().unwrap())
3533 .unwrap();
3634
3735 // creating files
36 let data = paths::data_dir();
3837 [
39 // ".cache/youtube-tui/thumbnails/",
40 // ".cache/youtube-tui/info/",
41 // ".cache/youtube-tui/channels/",
42 ".local/share/youtube-tui/thumbnails/",
43 ".local/share/youtube-tui/info/",
44 ".local/share/youtube-tui/saved/",
38 data.join("thumbnails"),
39 data.join("info"),
40 data.join("saved"),
4541 ]
4642 .into_iter()
47 .for_each(|s| {
48 let dir = home_dir.join(s);
43 .for_each(|dir| {
4944 if !dir.exists() {
5045 fs::create_dir_all(dir).unwrap();
5146 }
@@ -136,8 +131,7 @@ pub fn init(
136131
137132/// reload all config files
138133pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>> {
139 let home_dir = home_dir().unwrap();
140 let config_path = home_dir.join(".config/youtube-tui/");
134 let config_path = paths::config_dir();
141135
142136 if !&config_path.exists() {
143137 fs::create_dir_all(&config_path).unwrap();
src/items/iteminfo.rs +2 −3
@@ -53,9 +53,8 @@ impl FrameworkItem for ItemInfo {
5353
5454 #[cfg(any(feature = "sixel", feature = "halfblock"))]
5555 {
56 let thumbnail_path = home::home_dir()
57 .unwrap()
58 .join(".local/share/youtube-tui/thumbnails/")
56 let thumbnail_path = crate::global::functions::paths::data_dir()
57 .join("thumbnails")
5958 .join(item.thumbnail_id());
6059 if thumbnail_path.exists() {
6160 #[cfg(any(feature = "sixel", feature = "halfblock"))]
src/run.rs +6 −2
@@ -1,4 +1,4 @@
1use crossterm::event::{self, Event, MouseButton, MouseEventKind};
1use crossterm::event::{self, Event, KeyEventKind, MouseButton, MouseEventKind};
22use ratatui::{backend::CrosstermBackend, Terminal};
33#[cfg(feature = "mpv")]
44use std::time::{Duration, Instant};
@@ -272,7 +272,11 @@ pub fn run(
272272 .push(Task::RenderAll);
273273 }
274274 }
275 Event::Key(key) => key_input(key, framework, terminal),
275 // Only handle Press events; ignore Release/Repeat to avoid
276 // duplicate key actions on Windows terminals that send enhanced key events.
277 Event::Key(key) if key.kind == KeyEventKind::Press => {
278 key_input(key, framework, terminal)
279 }
276280 // always render if there is a screen resize event
277281 Event::Resize(_, _) => {
278282 framework