From 314d760de1922128124f2a9be0494fd4f6f7effb Mon Sep 17 00:00:00 2001 From: subh Date: Fri, 3 Apr 2026 14:47:03 +0530 Subject: new music bar, auto usb mounting and more --- README.md | 10 - ghostty/config | 55 --- ghostty/themes/catppuccin-mocha.conf | 23 - ghostty/themes/void.conf | 32 -- hyprland/hyprland.conf | 26 +- hyprland/keybinds.conf | 8 +- kitty/kitty.conf | 39 ++ mpd/mpd.conf | 412 ++++++++++++++++++ quickshell/mpd/shell.qml | 564 ++++++++++++++++++++++++ quickshell/shell.qml | 88 ++-- rmpc/config.ron | 281 ++++++++++++ scripts/mount-usb.sh | 109 +++++ scripts/umount-usb.sh | 22 + scripts/weather.py | 36 +- yazi/init.lua | 128 ++++++ yazi/keymap.toml | 68 +++ yazi/package.toml | 47 ++ yazi/plugins/chmod.yazi/LICENSE | 21 + yazi/plugins/chmod.yazi/README.md | 28 ++ yazi/plugins/chmod.yazi/main.lua | 47 ++ yazi/plugins/clipboard.yazi/LICENSE | 661 ++++++++++++++++++++++++++++ yazi/plugins/clipboard.yazi/README.md | 64 +++ yazi/plugins/clipboard.yazi/main.lua | 450 +++++++++++++++++++ yazi/plugins/compress.yazi/LICENSE | 21 + yazi/plugins/compress.yazi/README.md | 152 +++++++ yazi/plugins/compress.yazi/main.lua | 577 ++++++++++++++++++++++++ yazi/plugins/fs-usage.yazi/LICENSE | 21 + yazi/plugins/fs-usage.yazi/README.md | 93 ++++ yazi/plugins/fs-usage.yazi/main.lua | 292 +++++++++++++ yazi/plugins/full-border.yazi/LICENSE | 21 + yazi/plugins/full-border.yazi/README.md | 32 ++ yazi/plugins/full-border.yazi/main.lua | 44 ++ yazi/plugins/glow.yazi/LICENSE | 7 + yazi/plugins/glow.yazi/README.md | 33 ++ yazi/plugins/glow.yazi/main.lua | 64 +++ yazi/plugins/lin-decompress.yazi/LICENSE | 10 + yazi/plugins/lin-decompress.yazi/README.md | 102 +++++ yazi/plugins/lin-decompress.yazi/main.lua | 419 ++++++++++++++++++ yazi/plugins/preview-audio.yazi/LICENSE | 674 +++++++++++++++++++++++++++++ yazi/plugins/preview-audio.yazi/README.md | 27 ++ yazi/plugins/preview-audio.yazi/main.lua | 149 +++++++ yazi/plugins/rsync.yazi/LICENSE | 21 + yazi/plugins/rsync.yazi/README.md | 66 +++ yazi/plugins/rsync.yazi/assets/demo.gif | Bin 0 -> 9593417 bytes yazi/plugins/rsync.yazi/assets/demo.webm | Bin 0 -> 1121014 bytes yazi/plugins/rsync.yazi/main.lua | 137 ++++++ yazi/yazi.toml | 27 ++ 47 files changed, 6020 insertions(+), 188 deletions(-) delete mode 100644 README.md delete mode 100644 ghostty/config delete mode 100644 ghostty/themes/catppuccin-mocha.conf delete mode 100644 ghostty/themes/void.conf create mode 100644 kitty/kitty.conf create mode 100644 mpd/mpd.conf create mode 100644 quickshell/mpd/shell.qml create mode 100644 rmpc/config.ron create mode 100755 scripts/mount-usb.sh create mode 100755 scripts/umount-usb.sh create mode 100644 yazi/init.lua create mode 100644 yazi/keymap.toml create mode 100644 yazi/package.toml create mode 100644 yazi/plugins/chmod.yazi/LICENSE create mode 100644 yazi/plugins/chmod.yazi/README.md create mode 100644 yazi/plugins/chmod.yazi/main.lua create mode 100644 yazi/plugins/clipboard.yazi/LICENSE create mode 100644 yazi/plugins/clipboard.yazi/README.md create mode 100644 yazi/plugins/clipboard.yazi/main.lua create mode 100644 yazi/plugins/compress.yazi/LICENSE create mode 100644 yazi/plugins/compress.yazi/README.md create mode 100644 yazi/plugins/compress.yazi/main.lua create mode 100644 yazi/plugins/fs-usage.yazi/LICENSE create mode 100644 yazi/plugins/fs-usage.yazi/README.md create mode 100644 yazi/plugins/fs-usage.yazi/main.lua create mode 100644 yazi/plugins/full-border.yazi/LICENSE create mode 100644 yazi/plugins/full-border.yazi/README.md create mode 100644 yazi/plugins/full-border.yazi/main.lua create mode 100644 yazi/plugins/glow.yazi/LICENSE create mode 100644 yazi/plugins/glow.yazi/README.md create mode 100644 yazi/plugins/glow.yazi/main.lua create mode 100644 yazi/plugins/lin-decompress.yazi/LICENSE create mode 100644 yazi/plugins/lin-decompress.yazi/README.md create mode 100644 yazi/plugins/lin-decompress.yazi/main.lua create mode 100644 yazi/plugins/preview-audio.yazi/LICENSE create mode 100644 yazi/plugins/preview-audio.yazi/README.md create mode 100644 yazi/plugins/preview-audio.yazi/main.lua create mode 100644 yazi/plugins/rsync.yazi/LICENSE create mode 100644 yazi/plugins/rsync.yazi/README.md create mode 100644 yazi/plugins/rsync.yazi/assets/demo.gif create mode 100644 yazi/plugins/rsync.yazi/assets/demo.webm create mode 100644 yazi/plugins/rsync.yazi/main.lua create mode 100644 yazi/yazi.toml diff --git a/README.md b/README.md deleted file mode 100644 index 0c31f74..0000000 --- a/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## DOTFILES FOR HYPRLAND - -### Installation - -``` -git clone https://github.com/5epi0l/Hyprland-Dotfiles.git -cd Hyprland-Dotfiles -chmod +x install.sh -./install.sh -``` diff --git a/ghostty/config b/ghostty/config deleted file mode 100644 index e1f0dc6..0000000 --- a/ghostty/config +++ /dev/null @@ -1,55 +0,0 @@ -#This is the configuration file for Ghostty. -# -# This template file has been automatically created at the following -# path since Ghostty couldn't find any existing config files on your system: -# -# /home/subh/.config/ghostty/config -theme = ~/.config/ghostty/themes/void.conf - -font-family = "Iosevka Nerd Font Propo" -#font-family = "JetBrainsMono Nerd Font" -font-size = 13 -cursor-style = block -shell-integration-features = no-cursor -# The template does not set any default options, since Ghostty ships -# with sensible defaults for all options. Users should only need to set -# options that they want to change from the default. -# -# Run `ghostty +show-config --default --docs` to view a list of -# all available config options and their default values. -# -# Additionally, each config option is also explained in detail -# on Ghostty's website, at https://ghostty.org/docs/config. -# -# Ghostty can reload the configuration while running by using the menu -# options or the bound key (default: Command + Shift + comma on macOS and -# Control + Shift + comma on other platforms). Not all config options can be -# reloaded while running; some only apply to new windows and others may require -# a full restart to take effect. - -# Config syntax crash course -# ========================== -# # The config file consists of simple key-value pairs, -# # separated by equals signs. -# font-family = Iosevka -# window-padding-x = 2 -# -# # Spacing around the equals sign does not matter. -# # All of these are identical: -# key=value -# key= value -# key =value -# key = value -# -# # Any line beginning with a # is a comment. It's not possible to put -# # a comment after a config option, since it would be interpreted as a -# # part of the value. For example, this will have a value of "#123abc": -# background = #123abc -# -# # Empty values are used to reset config keys to default. -# key = -# -# # Some config options have unique syntaxes for their value, -# # which is explained in the docs for that config option. -# # Just for example: -# resize-overlay-duration = 4s 200ms diff --git a/ghostty/themes/catppuccin-mocha.conf b/ghostty/themes/catppuccin-mocha.conf deleted file mode 100644 index e03e26d..0000000 --- a/ghostty/themes/catppuccin-mocha.conf +++ /dev/null @@ -1,23 +0,0 @@ -palette = 0=#45475a -palette = 1=#f38ba8 -palette = 2=#a6e3a1 -palette = 3=#f9e2af -palette = 4=#89b4fa -palette = 5=#f5c2e7 -palette = 6=#94e2d5 -palette = 7=#a6adc8 -palette = 8=#585b70 -palette = 9=#f38ba8 -palette = 10=#a6e3a1 -palette = 11=#f9e2af -palette = 12=#89b4fa -palette = 13=#f5c2e7 -palette = 14=#94e2d5 -palette = 15=#bac2de -background = 1e1e2e -foreground = cdd6f4 -cursor-color = f5e0dc -cursor-text = 11111b -selection-background = 353749 -selection-foreground = cdd6f4 -split-divider-color = 313244 diff --git a/ghostty/themes/void.conf b/ghostty/themes/void.conf deleted file mode 100644 index 7ef0766..0000000 --- a/ghostty/themes/void.conf +++ /dev/null @@ -1,32 +0,0 @@ -# --- Blackened Catppuccin Theme --- - -# Syntax Palette (Maintained for readability) -palette = 0=#45475a -palette = 1=#f38ba8 -palette = 2=#a6e3a1 -palette = 3=#f9e2af -palette = 4=#89b4fa -palette = 5=#f5c2e7 -palette = 6=#94e2d5 -palette = 7=#a6adc8 -palette = 8=#585b70 -palette = 9=#f38ba8 -palette = 10=#a6e3a1 -palette = 11=#f9e2af -palette = 12=#89b4fa -palette = 13=#f5c2e7 -palette = 14=#94e2d5 -palette = 15=#bac2de - -# True Black Background -background = #000000 -foreground = #cdd6f4 - -# Cursor & Selection (Adjusted for contrast) -cursor-color = #f5e0dc -cursor-text = #000000 -selection-background = #313244 -selection-foreground = #cdd6f4 - -# UI Elements -split-divider-color = #181825 diff --git a/hyprland/hyprland.conf b/hyprland/hyprland.conf index 0a692fc..7193445 100644 --- a/hyprland/hyprland.conf +++ b/hyprland/hyprland.conf @@ -9,13 +9,13 @@ monitor=HDMI-A-3,1920x1080@180,auto,1.0 # See https://wiki.hyprland.org/Configuring/Keywords/ # Set programs that you use -$terminal = ghostty +$terminal = kitty $fileManager = pcmanfm $menu = rofi -show drun -drun-reload-desktop-cache $reload_qs = pkill qs 2>&1; qs & $snip = hyprshot -m region --raw | satty --filename - $reload_hypr = hyprctl reload -$browser = firefox +$browser = librewolf $discord = discord @@ -195,6 +195,26 @@ windowrule { center = on } +windowrule { + name = rmpc-float + match:class = (?i).*rmpc-term.* + + float = on + size = 1400 900 + center = on +} + +windowrule { + name = yazi-float + match:class = (?i).*yazi-term.* + + float = on + size = 1400 900 + center = on +} + + + # Example windowrule v1 # windowrule = float, ^(kitty)$ @@ -202,5 +222,5 @@ windowrule { # windowrulev2 = float,class:^(kitty)$,title:^(kitty)$ #windowrulev2 = suppressevent maximize, class:^(firefox|code|jetbrains-.*|electron)$ -windowrule = border_color rgb(f38ba8) rgb(313244), match:class (firefox|librewolf|discord|sublime_text|com.mitchellh.ghostty|org.keepassxc.KeePassXC|burp-StartBurp) +windowrule = border_color rgb(f38ba8) rgb(313244), match:class (librewolf|discord|sublime_text|org.keepassxc.KeePassXC|burp-StartBurp|kitty) windowrule = suppress_event maximize, match:class .* # You'll probably like this. diff --git a/hyprland/keybinds.conf b/hyprland/keybinds.conf index 62c3582..3d455df 100644 --- a/hyprland/keybinds.conf +++ b/hyprland/keybinds.conf @@ -23,17 +23,23 @@ bind = $mainMod|Ctrl, L, exec, /opt/scripts/power.sh bind = $mainMod|Shift, W, exec, /opt/scripts/wallpaper-picker.sh bind = $mainMod, N, exec, /opt/scripts/wifi-connect.sh bind = $mainMod|Shift, N, exec, /opt/scripts/wifi-disconnect.sh -bind = $mainMod|Shift, M, exec, kill -9 `pidof spotify` +#bind = $mainMod|Shift, M, exec, kill -9 `pidof spotify` bind = $mainMod|Ctrl, K, exec, keepassxc bind = $mainMod, S, exec, subl bind = $mainMod, V, exec, /opt/scripts/vpn_connect.sh bind = $mainMod|Shift, V, exec, /opt/scripts/vpn_disconnect.sh bind = $mainMod, X, exec, /opt/scripts/screen-record.sh bind = $mainMod|Shift, X, exec, /opt/scripts/screen-record-stop.sh +bind = $mainMod, M, exec, /opt/scripts/mount-usb.sh +bind = $mainMod|Shift, M, exec, /opt/scripts/umount-usb.sh bind = $mainMod, Y, exec, hyprctl workspaces -j | jq '.[].lastwindowtitle' | rofi -show window bind = $mainMod, P, exec, hyprctl getoption general:layout | grep -q 'dwindle' && hyprctl keyword general:layout master || hyprctl keyword general:layout dwindle bind = $mainMod, equal, exec, pactl set-sink-volume @DEFAULT_SINK@ +5% && notify-send "Volume Status" "Current Volume: $(pactl --format json get-sink-volume @DEFAULT_SINK@ | jq -r '.volume."front-left"."value_percent"')" bind = $mainMod, minus, exec, pactl set-sink-volume @DEFAULT_SINK@ -5% && notify-send "Volume Status" "Current Volume: $(pactl --format json get-sink-volume @DEFAULT_SINK@ | jq -r '.volume."front-left"."value_percent"')" +bind = $mainMod SHIFT, equal, exec, mpc volume +5 && notify-send -i "audio-volume-high" -a "MPD" "MPD Volume" "$(mpc volume)" +bind = $mainMod SHIFT, minus, exec, mpc volume -5 && notify-send -i "audio-volume-low" -a "MPD" "MPD Volume" "$(mpc volume)" +bind = Ctrl, M, exec, kitty --class rmpc-term rmpc +bind = Ctrl|Shift, F, exec, kitty --class yazi-term yazi # Move focus with mainMod + arrow keys bind = $mainMod, h, movefocus, l diff --git a/kitty/kitty.conf b/kitty/kitty.conf new file mode 100644 index 0000000..9158d80 --- /dev/null +++ b/kitty/kitty.conf @@ -0,0 +1,39 @@ +confirm_os_window_close 0 +font_family IosevkaNerdFontPropo-Regular +bold_font IosevkaNerdFontPropo-Bold +italic_font IosevkaNerdFontPropo-Italic +bold_italic_font IosevkaNerdFontPropo-BoldItalic +font_size 13.0 + +# --- Blackened Catppuccin Theme --- +# Syntax Palette +color0 #45475a +color1 #f38ba8 +color2 #a6e3a1 +color3 #f9e2af +color4 #89b4fa +color5 #f5c2e7 +color6 #94e2d5 +color7 #a6adc8 +color8 #585b70 +color9 #f38ba8 +color10 #a6e3a1 +color11 #f9e2af +color12 #89b4fa +color13 #f5c2e7 +color14 #94e2d5 +color15 #bac2de + +# True Black Background +background #000000 +foreground #cdd6f4 + +# Cursor & Selection +cursor #f5e0dc +cursor_text_color #000000 +selection_background #313244 +selection_foreground #cdd6f4 + +# Splits +active_border_color #f38ba8 +inactive_border_color #313244 diff --git a/mpd/mpd.conf b/mpd/mpd.conf new file mode 100644 index 0000000..6e6dead --- /dev/null +++ b/mpd/mpd.conf @@ -0,0 +1,412 @@ +# An example configuration file for MPD. +# Read the user manual for documentation: http://www.musicpd.org/doc/user/ + +music_directory "/mnt" +playlist_directory "/mnt/playlists" +db_file "~/.local/share/mpd/database" +log_file "~/.local/share/mpd/log" +pid_file "~/.local/share/mpd/pid" +state_file "~/.local/share/mpd/state" +sticker_file "~/.local/share/mpd/sticker.sql" + +bind_to_address "127.0.0.1" +port "6600" +auto_update "yes" + +audio_output { + type "pipewire" + name "Pipewire" +} + + +# Files and directories ####################################################### +# +# This setting controls the top directory which MPD will search to discover the +# available audio files and add them to the daemon's online database. This +# setting defaults to the XDG directory, otherwise the music directory will be +# be disabled and audio files will only be accepted over ipc socket (using +# file:// protocol) or streaming files over an accepted protocol. +# +#music_directory "$XDG_MUSIC_DIR" +#music_directory "~/music" +# +# This setting sets the MPD internal playlist directory. The purpose of this +# directory is storage for playlists created by MPD. The server will use +# playlist files not created by the server but only if they are in the MPD +# format. This setting defaults to playlist saving being disabled. +# +#playlist_directory "$XDG_CONFIG_HOME/mpd/playlists" +#playlist_directory "~/.mpd/playlists" +# +# This setting sets the location of the MPD database. This file is used to +# load the database at server start up and store the database while the +# server is not up. This setting defaults to disabled which will allow +# MPD to accept files over ipc socket (using file:// protocol) or streaming +# files over an accepted protocol. +# +#db_file "$XDG_CACHE_HOME/mpd/database" +#db_file "~/.mpd/database" + +# These settings are the locations for the daemon log files for the daemon. +# +# The special value "syslog" makes MPD use the local syslog daemon. This +# setting defaults to logging to syslog. +# +# If you use systemd, do not configure a log_file. With systemd, MPD +# defaults to the systemd journal, which is fine. +# +#log_file "$XDG_CACHE_HOME/mpd/log" +#log_file "~/.mpd/log" + +# This setting sets the location of the file which stores the process ID +# for use of mpd --kill and some init scripts. This setting is disabled by +# default and the pid file will not be stored. +# +# If you use systemd, do not configure a pid_file. +# +#pid_file "$XDG_RUNTIME_DIR/mpd/mpd.pid" +#pid_file "~/.mpd/pid" + +# This setting sets the location of the file which contains information about +# most variables to get MPD back into the same general shape it was in before +# it was brought down. This setting is disabled by default and the server +# state will be reset on server start up. +# +#state_file "$XDG_RUNTIME_DIR/mpd/state" +#state_file "~/.mpd/state" +# +# The location of the sticker database. This is a database which +# manages dynamic information attached to songs. +# +#sticker_file "$XDG_CACHE_HOME/sticker.sql" +#sticker_file "~/.mpd/sticker.sql" +# +############################################################################### + + +# General music daemon options ################################################ +# +# This setting specifies the user that MPD will run as. MPD should never run as +# root and you may use this setting to make MPD change its user ID after +# initialization. This setting is disabled by default and MPD is run as the +# current user. +# +#user "nobody" +# +# This setting sets the address for the daemon to listen on. Careful attention +# should be paid if this is assigned to anything other than the default, any. +# This setting can deny access to control of the daemon. Not effective if +# systemd socket activation is in use. +# +# For network +#bind_to_address "any" +# +# And for Unix Socket +#bind_to_address "$XDG_RUNTIME_DIR/mpd/socket" +#bind_to_address "~/.mpd/socket" +# +# This setting is the TCP port that is desired for the daemon to get assigned +# to. +# +#port "6600" +# +# Suppress all messages below the given threshold. Use "verbose" for +# troubleshooting. Available setting arguments are "notice", "info", "verbose", +# "warning" and "error". +# +#log_level "notice" +# +# Setting "restore_paused" to "yes" puts MPD into pause mode instead +# of starting playback after startup. +# +#restore_paused "no" +# +# This setting enables MPD to create playlists in a format usable by other +# music players. +# +#save_absolute_paths_in_playlists "no" +# +# This setting defines a list of tag types that will be extracted during the +# audio file discovery process. The complete list of possible values can be +# found in the user manual. +#metadata_to_use "artist,album,title,track,name,genre,date,composer,performer,disc" +# +# This example just enables the "comment" tag without disabling all +# the other supported tags: +#metadata_to_use "+comment" +# +# This setting enables automatic update of MPD's database when files in +# music_directory are changed. (Linux only) +# +#auto_update "yes" +# +# Limit the depth of the directories being watched, 0 means only watch +# the music directory itself. There is no limit by default. +# +#auto_update_depth "3" +# +############################################################################### + + +# Symbolic link behavior ###################################################### +# +# If this setting is set to "yes", MPD will discover audio files by following +# symbolic links outside of the configured music_directory. +# +#follow_outside_symlinks "yes" +# +# If this setting is set to "yes", MPD will discover audio files by following +# symbolic links inside of the configured music_directory. +# +#follow_inside_symlinks "yes" +# +############################################################################### + + +# Zeroconf / Avahi Service Discovery ########################################## +# +# If this setting is set to "yes", service information will be published with +# Zeroconf / Avahi. +# +#zeroconf_enabled "yes" +# +# The argument to this setting will be the Zeroconf / Avahi unique name for +# this MPD server on the network. %h will be replaced with the hostname. +# +#zeroconf_name "Music Player @ %h" +# +############################################################################### + + +# Permissions ################################################################# +# +# If this setting is set, MPD will require password authorization. The password +# setting can be specified multiple times for different password profiles. +# +#password "password@read,add,control,admin" +# +# This setting specifies the permissions a user has who has not yet logged in. +# +#default_permissions "read,add,control,admin" +# +############################################################################### + + +# Database ####################################################################### +# +# An example of a database section instead of the old 'db_file' setting. +# It enables mounting other storages into the music directory. +# +#database { +# plugin "simple" +# path "~/.local/share/mpd/db" +# cache_directory "~/.local/share/mpd/cache" +#} +# +# An example of database config for a satellite setup +# +#music_directory "nfs://fileserver.local/srv/mp3" +#database { +# plugin "proxy" +# host "other.mpd.host" +# port "6600" +#} + +# Input ####################################################################### +# +input { + plugin "curl" +# proxy "proxy.isp.com:8080" +# proxy_user "user" +# proxy_password "password" +} + +# +############################################################################### + +# Audio Output ################################################################ +# +# MPD supports various audio output types, as well as playing through multiple +# audio outputs at the same time, through multiple audio_output settings +# blocks. Setting this block is optional, though the server will only attempt +# autodetection for one sound card. +# +# An example of an ALSA output: +# +#audio_output { +# type "alsa" +# name "My ALSA Device" +## device "hw:0,0" # optional +## mixer_type "hardware" # optional +## mixer_device "default" # optional +## mixer_control "PCM" # optional +## mixer_index "0" # optional +#} +# +# An example of an OSS output: +# +#audio_output { +# type "oss" +# name "My OSS Device" +## device "/dev/dsp" # optional +## mixer_type "hardware" # optional +## mixer_device "/dev/mixer" # optional +## mixer_control "PCM" # optional +#} +# +# An example of a shout output (for streaming to Icecast): +# +#audio_output { +# type "shout" +# encoder "vorbis" # optional +# name "My Shout Stream" +# host "localhost" +# port "8000" +# mount "/mpd.ogg" +# password "hackme" +# quality "5.0" +# bitrate "128" +# format "44100:16:1" +## protocol "icecast2" # optional +## user "source" # optional +## description "My Stream Description" # optional +## url "http://example.com" # optional +## genre "jazz" # optional +## public "no" # optional +## timeout "2" # optional +## mixer_type "software" # optional +#} +# +# An example of a recorder output: +# +#audio_output { +# type "recorder" +# name "My recorder" +# encoder "vorbis" # optional, vorbis or lame +# path "/var/lib/mpd/recorder/mpd.ogg" +## quality "5.0" # do not define if bitrate is defined +# bitrate "128" # do not define if quality is defined +# format "44100:16:1" +#} +# +# An example of a httpd output (built-in HTTP streaming server): +# +#audio_output { +# type "httpd" +# name "My HTTP Stream" +# encoder "vorbis" # optional, vorbis or lame +# port "8000" +# bind_to_address "0.0.0.0" # optional, IPv4 or IPv6 +## quality "5.0" # do not define if bitrate is defined +# bitrate "128" # do not define if quality is defined +# format "44100:16:1" +# max_clients "0" # optional 0=no limit +#} +# +# An example of a pulseaudio output (streaming to a remote pulseaudio server) +# +#audio_output { +# type "pulse" +# name "My Pulse Output" +## server "remote_server" # optional +## sink "remote_server_sink" # optional +## media_role "media_role" #optional +#} +# +# An example of a winmm output (Windows multimedia API). +# +#audio_output { +# type "winmm" +# name "My WinMM output" +## device "Digital Audio (S/PDIF) (High Definition Audio Device)" # optional +# or +## device "0" # optional +## mixer_type "hardware" # optional +#} +# +# An example of a wasapi output (Windows multimedia API). +# +#audio_output { +# type "wasapi" +# name "My WASAPI output" +## device "Digital Audio (S/PDIF) (High Definition Audio Device)" # optional +# or +## device "0" # optional +## mixer_type "hardware" # optional +## Exclusive mode blocks all other audio source, and get best audio quality without resampling. +## exclusive "no" # optional +## Enumerate all devices in log. +## enumerate "no" # optional +#} +# +# An example of an openal output. +# +#audio_output { +# type "openal" +# name "My OpenAL output" +## device "Digital Audio (S/PDIF) (High Definition Audio Device)" # optional +#} +# +# An example of an sndio output. +# +#audio_output { +# type "sndio" +# name "sndio output" +# mixer_type "hardware" +#} +# +# An example of an OS X output: +# +#audio_output { +# type "osx" +# name "My OS X Device" +## device "Built-in Output" # optional +## channel_map "-1,-1,0,1" # optional +#} +# +## Example "pipe" output: +# +#audio_output { +# type "pipe" +# name "my pipe" +# command "aplay -f cd 2>/dev/null" +## Or if you're want to use AudioCompress +# command "AudioCompress -m | aplay -f cd 2>/dev/null" +## Or to send raw PCM stream through PCM: +# command "nc example.org 8765" +# format "44100:16:2" +#} +# +## An example of a null output (for no audio output): +# +#audio_output { +# type "null" +# name "My Null Output" +# mixer_type "none" # optional +#} +# +############################################################################### + + +# Normalization automatic volume adjustments ################################## +# +# This setting specifies the type of ReplayGain to use. This setting can have +# the argument "off", "album", "track" or "auto". "auto" is a special mode that +# chooses between "track" and "album" depending on the current state of +# random playback. If random playback is enabled then "track" mode is used. +# See for +# more details about ReplayGain. +# This setting is off by default. +# +#replaygain "album" +# +############################################################################### + +# Character Encoding ########################################################## +# +# If file or directory names do not display correctly for your locale then you +# may need to modify this setting. +# +#filesystem_charset "UTF-8" +# +############################################################################### diff --git a/quickshell/mpd/shell.qml b/quickshell/mpd/shell.qml new file mode 100644 index 0000000..04a74b8 --- /dev/null +++ b/quickshell/mpd/shell.qml @@ -0,0 +1,564 @@ +import Quickshell +import Quickshell.Io +import QtQuick +import QtQuick.Layouts +ShellRoot { + property color colBg: "#000000" + property color colFg: "#ffffff" + property color colMuted: "#313244" + property color colCyan: "#89dceb" + property color colPurple: "#cba6f7" + property color colRed: "#f38ba8" + property color colYellow: "#f9e2af" + property color colBlue: "#89b4fa" + property color colGreen: "#A3BE8C" + property string fontFamily: "Iosevka NerdFont Propo" + property int fontSize: 16 + property string mpd_title: "" + property string mpd_artist: "" + property string mpd_elapsed: "0:00" + property string mpd_duration: "0:00" + property string mpd_file: "" + property real mpd_progress: 0.0 + property bool isPlaying: false + property bool isPaused: false + property bool isActive: isPlaying || isPaused + property bool isSeeking: false + property bool cardVisible: false + property bool titleCardVisible: false + property string artPath: "/tmp/mpdrop_art.png" + property string artCache: "" + property real seekStartProgress: 0 + property double seekStartTime: 0 + property int mpdVolume: 0 + function timeToSecs(t) { + var p = t.split(":") + if (p.length === 2) return parseInt(p[0]) * 60 + parseInt(p[1]) + if (p.length === 3) return parseInt(p[0]) * 3600 + parseInt(p[1]) * 60 + parseInt(p[2]) + return 0 + } + Process { + id: volProc + command: ["sh", "-c", "echo idle"] + running: false + } + Process { + id: notifyProc + property string title: "" + property string artist: "" + property string art: "" + command : ["sh", "-c", "notify-send -i '/tmp/mpdrop_art.png' -a 'MPD' 'Now Playing' '" + mpd_title.replace(/'/g, "") + (mpd_artist !== "" ? "\n" + mpd_artist.replace(/'/g, "") : "") + "'" + ] + running: false + } + + Process { + id: artProc + property string filePath: "" + command: ["sh", "-c", + "ffmpeg -i \"/mnt/" + filePath + "\" -an -vcodec copy /tmp/mpdrop_art.png -y 2>/dev/null"] + running: false + onExited: { + artCache = "" + artCache = artPath + notifyProc.running = false + notifyProc.running = true + } + } + Process { + id: fileProc + command: ["mpc", "--format", "%file%", "current"] + stdout: StdioCollector { + onStreamFinished: { + var f = this.text.trim() + if (f !== "" && f !== mpd_file) { + mpd_file = f + artProc.filePath = f + artProc.running = false + artProc.running = true + } + } + } + } + Process { + id: idleProc + command: ["mpc", "idlewait"] + running: true + onExited: statusProc.running = true + } + Process { + id: statusProc + command: ["mpc", "status", "--format", "%title%||%artist%||%duration%"] + stdout: StdioCollector { + onStreamFinished: { + var lines = this.text.trim().split("\n") + if (lines.length >= 2) { + var meta = lines[0].split("||") + var newTitle = meta[0] || "Unknown" + var volMatch = this.text.match(/volume:\s*(\d+)%/) + if (volMatch) mpdVolume = parseInt(volMatch[1]) + if (newTitle !== mpd_title) + { + fileProc.running = true + } + mpd_title = newTitle + mpd_artist = meta[1] || "" + var rawDuration = meta[2] ? meta[2].trim() : "" + var sl = lines[1] + isPlaying = sl.indexOf("[playing]") !== -1 + isPaused = sl.indexOf("[paused]") !== -1 + var tm = sl.match(/(\d+:\d+)\/(\d+:\d+)/) + if (tm) { + mpd_elapsed = tm[1] + mpd_duration = (rawDuration !== "" && rawDuration !== "0:00") ? rawDuration: tm [2] + var total = timeToSecs(mpd_duration) + if (!isSeeking) { + mpd_progress = total > 0 ? timeToSecs(tm[1]) / total : 0 + seekStartProgress = mpd_progress + seekStartTime = Date.now() / 1000 + } + } + } else { + mpd_title = ""; mpd_artist = "" + mpd_elapsed = "0:00"; mpd_duration = "0:00" + mpd_progress = 0; isPlaying = false; isPaused = false + } + } + } + onExited: idleRestartTimer.restart() + } + Timer { + id: idleRestartTimer + interval: 50 + repeat: false + onTriggered: idleProc.running = true + } + Timer { + id: progressTimer + interval: 500 + running: isPlaying && !isSeeking && isActive + repeat: true + onTriggered: { + var now = Date.now() / 1000 + var elapsed = now - seekStartTime + var total = timeToSecs(mpd_duration) + if (total <= 0) return + + var newProgress = Math.min(1.0, seekStartProgress + (elapsed / total)) + mpd_progress = newProgress + var elapsedSecs = Math.round(newProgress * total) + var m = Math.floor(elapsedSecs / 60) + var s = elapsedSecs % 60 + mpd_elapsed = m + ":" + (s < 10 ? "0" + s : s) + } + } + Timer { + id: seekResetTimer + interval: 1100 + repeat: false + onTriggered: isSeeking = false + } + Timer { + id: syncTimer + interval: 5000 + running: isActive + repeat: true + onTriggered: statusProc.running = true + } + Process { + id: ctrlProc + property var args: ["toggle"] + command: ["mpc"].concat(args) + running: false + onExited: statusProc.running = true + } + PanelWindow { + visible: titleCardVisible && isActive + screen: Quickshell.screens[0] + exclusionMode: ExclusionMode.Ignore + anchors { bottom: true; left: true } + implicitHeight: 36 + color: "transparent" + + Rectangle { + anchors.fill: titleCardText.implicitWidth + 24 + height: 28 + anchors.bottom: parent.bottom + anchors.bottomMargin: 40 + anchors.left: parent.left + anchors.leftMargin: 40 + radius: 8 + color: colBg + border.color: colMuted + border.width: 1 + opacity: titleCardVisible ? 1 : 0 + Behavior on opacity { NumberAnimation { duration: 150 } } + + Text { + id: titleCardText + anchors.centerIn: parent + text: mpd_title + color: colPurple + font.pixelSize: fontSize + font.family: fontFamily + font.bold: true + } + } + } + PanelWindow { + visible: cardVisible && isActive + screen: Quickshell.screens[0] + exclusionMode: ExclusionMode.Ignore + anchors { bottom: true; right: true } + implicitWidth: 280 + implicitHeight: artCardContent.implicitHeight + 24 + color: "transparent" + + Rectangle { + id: artCardContent + anchors.fill: parent + anchors.margins: 12 + implicitHeight: cardCol.implicitHeight + 24 + radius: 12 + color: colBg + border.color: colMuted + border.width: 1 + opacity: cardVisible ? 1 : 0 + Behavior on opacity { NumberAnimation { duration: 200 } } + + Column { + id: cardCol + anchors.fill: parent + anchors.margins: 12 + spacing: 10 + + // Album art + Rectangle { + width: parent.width + height: artImage.status === Image.Ready + ? parent.width * (artImage.implicitHeight / artImage.implicitWidth) + : parent.width + radius: 8 + color: colMuted + clip: true + Image { + id: artImage + anchors.fill: parent + source: artCache !== "" ? "file://" + artCache : "" + fillMode: Image.PreserveAspectFit + cache: false + smooth: cardVisible + asynchronous: true + Text { + anchors.centerIn: parent + text: "󰎈" + font.pixelSize: 48 + font.family: fontFamily + color: colMuted + visible: artImage.status !== Image.Ready + } + } + } + Text { + text: mpd_title + color: colFg + font.pixelSize: 13 + font.family: fontFamily + font.bold: true + elide: Text.ElideRight + width: parent.width + } + Text { + text: mpd_artist + color: colMuted + font.pixelSize: 12 + font.family: fontFamily + elide: Text.ElideRight + width: parent.width + visible: mpd_artist !== "" + } + Rectangle { + width: parent.width + height: 3 + radius: 2 + color: colMuted + Rectangle { + width: parent.width * mpd_progress + height: parent.height + radius: 2 + color: isPlaying ? colCyan : colYellow + Behavior on width { + enabled: !isSeeking + NumberAnimation { duration: 950; easing.type: Easing.Linear } + } + } + } + RowLayout { + width: parent.width + Text { + text: mpd_elapsed + color: colFg + font.pixelSize: 11 + font.family: fontFamily + } + Item { Layout.fillWidth: true } + Text { + text: mpd_duration + color: colMuted + font.pixelSize: 11 + font.family: fontFamily + } + } + } + } + } + PanelWindow { + id: mainBar + visible: isActive + screen: Quickshell.screens[0] + exclusionMode: ExclusionMode.Auto + anchors { bottom: true; left: true; right: true } + implicitHeight: 36 + color: colBg + Rectangle { + anchors.fill: parent + color: colBg + Rectangle { + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + height: 1 + color: colMuted + } + RowLayout { + anchors.fill: parent + anchors.leftMargin: 8 + anchors.rightMargin: 8 + spacing: 0 + Text { + text: isPaused ? "󰎊" : "󰎈" + color: isPaused ? colYellow : colCyan + font.pixelSize: fontSize + 3 + font.family: fontFamily + font.bold: true + + Behavior on color { ColorAnimation { duration: 200 } } + } + Item { width: 8 } + Text { + text: mpd_title || "Unknown" + color: colPurple + font.pixelSize: fontSize + font.family: fontFamily + font.bold: true + elide: Text.ElideRight + Layout.maximumWidth: 220 + HoverHandler { + onHoveredChanged: titleCardVisible = hovered + } + } + + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: colMuted + visible: mpd_artist !== "" + } + Text { + text: mpd_artist + color: colCyan + font.pixelSize: fontSize + font.family: fontFamily + font.bold: true + elide: Text.ElideRight + Layout.maximumWidth: 180 + visible: mpd_artist !== "" + } + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: colMuted + } + Text { + text: "󰒮" + color: prevH.containsMouse ? colCyan : colFg + font.pixelSize: fontSize + 3; font.family: fontFamily; font.bold: true + Layout.rightMargin: 10 + HoverHandler { id: prevH } + TapHandler { + onTapped: { + if (!ctrlProc.running) { + ctrlProc.args = ["prev"] + ctrlProc.running = true + } + } + } + Behavior on color { ColorAnimation { duration: 100 } } + } + Text { + text: isPlaying ? "󰏤" : "󰐊" + color: playH.containsMouse ? colPurple : colCyan + font.pixelSize: fontSize + 3; font.family: fontFamily; font.bold: true + Layout.rightMargin: 10 + HoverHandler { id: playH } + TapHandler { + onTapped: { + if (!ctrlProc.running) { + ctrlProc.args = ["toggle"] + ctrlProc.running = true + } + } + } + Behavior on color { ColorAnimation { duration: 100 } } + } + Text { + text: "󰒭" + color: nextH.containsMouse ? colCyan : colFg + font.pixelSize: fontSize + 3; font.family: fontFamily; font.bold: true + Layout.rightMargin: 10 + HoverHandler { id: nextH } + TapHandler { + onTapped: { + if (!ctrlProc.running) { + ctrlProc.args = ["next"] + ctrlProc.running = true + } + } + } + Behavior on color { ColorAnimation { duration: 100 } } + } + Text { + text: "󰓛" + color: stopH.containsMouse ? colRed : colMuted + font.pixelSize: fontSize + 3; font.family: fontFamily; font.bold: true + HoverHandler { id: stopH } + TapHandler { + onTapped: { + if (!ctrlProc.running) { + ctrlProc.args = ["stop"] + ctrlProc.running = true + } + } + } + Behavior on color { ColorAnimation { duration: 100 } } + } + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: colMuted + } + Item { + implicitWidth: volIcon.implicitWidth + volText.implicitWidth + 4 + implicitHeight: parent.height + + Text { + id: volIcon + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + text: mpdVolume <=0 ? "󰝟" : mpdVolume < 50 ? "󰕿" : "󰕾" + color: colBlue + font.pixelSize: fontSize + 3 + font.family: fontFamily + font.bold: true + } + Text { + id: volText + anchors.left: volIcon.right + anchors.leftMargin: 4 + anchors.verticalCenter: parent.verticalCenter + text: mpdVolume + "%" + color: colBlue + font.pixelSize: fontSize + font.family: fontFamily + font.bold: true + } + MouseArea { + anchors.fill: parent + onWheel: (wheel) => { + console.log("wheel fired: " + wheel.angleDelta.y) + volProc.command = wheel.angleDelta.y > 0 + ? ["sh", "-c","mpc volume +5"] + : ["sh", "-c","mpc volume -5"] + volProc.running = false + volProc.running = true + } + } + } + + + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: colMuted + } + Text { + text: mpd_elapsed + color: colFg + font.pixelSize: fontSize; font.family: fontFamily; font.bold: true + Layout.rightMargin: 8 + } + Rectangle { + id: progressTrack + Layout.fillWidth: true + height: 4; radius: 2 + color: colMuted + Rectangle { + id: progressFill + width: progressTrack.width * mpd_progress + height: parent.height; radius: 2 + color: isPlaying ? colCyan : colYellow + Behavior on width { + enabled: !isSeeking + NumberAnimation { duration: 950; easing.type: Easing.Linear } + } + Behavior on color { ColorAnimation { duration: 300 } } + } + MouseArea { + anchors.fill: parent + anchors.topMargin: -6 + anchors.bottomMargin: -6 + cursorShape: Qt.PointingHandCursor + onClicked: (mouse) => { + if (!ctrlProc.running) { + var pct = Math.max(0, Math.min(1, mouse.x / progressTrack.width)) + var pctInt = Math.round(pct * 100) + isSeeking = true + mpd_progress = pct + seekStartProgress = pct + seekStartTime = Date.now() / 1000 + ctrlProc.args = ["seek", pctInt + "%"] + ctrlProc.running = true + seekResetTimer.restart() + } + } + } + } + Text { + text: mpd_duration + color: colMuted + font.pixelSize: fontSize; font.family: fontFamily; font.bold: true + Layout.leftMargin: 8 + } + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: colMuted + } + Text { + text: "󰜡" + color: colCyan + font.pixelSize: fontSize + 3 + font.family: fontFamily + font.bold: true + HoverHandler { + id: iconHover + onHoveredChanged: cardVisible = iconHover.hovered + } + + Behavior on color { ColorAnimation { duration: 200 } } + } + Item { width: 8 } + } + } + } +} diff --git a/quickshell/shell.qml b/quickshell/shell.qml index 1857c55..313827c 100644 --- a/quickshell/shell.qml +++ b/quickshell/shell.qml @@ -48,51 +48,19 @@ ShellRoot { property string weatherIcon: " " property string weatherTemp: "--°C" - property string weatherPrecip: "" - property string weatherWind: "" + property string weatherPrecip: "--%" + property string weatherWind: "--kph" + property string netConnection: "" - function getWeatherIcon(desc) { - if (!desc) return "❓"; - var hour = new Date().getHours(); - var isDay = (hour >= 6 && hour < 18); - var d = desc.toLowerCase(); - if (d.includes("sun") || d.includes("clear")) { - return isDay ? " " : " "; - } - if (d.includes("cloud") && d.includes("partly")) { - return isDay ? " " : " "; - } - if (d.includes("cloud") || d.includes("overcast")) { - return " "; - } - if (d.includes("rain") || d.includes("drizzle") || d.includes("showers")) { - return " "; - } - if (d.includes("thunder") || d.includes("storm")) { - return " "; - } - - if (d.includes("snow") || d.includes("ice") || d.includes("sleet")) { - return " "; - } - - if (d.includes("fog") || d.includes("mist") || d.includes("haze")) { - return "󰖑 "; - } - - return " "; - } - // Kernel version Process { - id: kernelProc - command: ["uname", "-r"] + id: connectionProc + command: ["sh", "-c", "sed 's/dormant/󰤯 /;s/down/󰤭 /;s/up/󰤨 /' /sys/class/net/wlp8s0/operstate"] stdout: SplitParser { - onRead: data => { if (data) kernelVersion = data.trim() } + onRead: data => { if (data) netConnection = data.trim() } } Component.onCompleted: running = true } - // System UpTime Process { id: upTimeProc @@ -196,10 +164,11 @@ ShellRoot { onRead: data => { if (!data || data.trim() === "") return var parts = data.trim().split(/\s+/) - if (parts.length >= 3) { + if (parts.length >= 4) { weatherIcon = parts[0] weatherTemp = parts[1] - weatherPrecip = parts[2] + " " + parts[3] // Icon + % + weatherPrecip = parts[2] + " " + parts[3] + weatherWind = parts[4] + " " + parts[5] } } @@ -266,6 +235,12 @@ ShellRoot { // Timers + Timer { + interval: 5000; running: true; repeat: true + onTriggered: { + connectionProc.running = true + } + } // UpTime Timer Timer { interval: 60000; running: true; repeat: true @@ -282,7 +257,12 @@ ShellRoot { } } // Weather Timer - Timer { interval: 3600000; running: true; repeat: true; onTriggered: weatherProc.running = true } + Timer { + interval: 3600000; running: true; repeat: true; onTriggered: { + console.log("Weather fetched at: " + new Date().toString()) + weatherProc.running = true + } + } Connections { target: Hyprland @@ -391,16 +371,20 @@ ShellRoot { font.pixelSize: root.fontSize color: root.colGreen font.bold: true + } + + Text { + text: weatherWind + font.family: root.fontFamily + font.pixelSize: root.fontSize + color: root.colBlue + font.bold: true Layout.rightMargin: 8 } } Rectangle { Layout.preferredWidth: 1; Layout.preferredHeight: 16; Layout.rightMargin: 8; color: root.colMuted } - // System Stats (Right Side) - Text { text: "󰣇 " + kernelVersion; color: root.colCyan; font.pixelSize: root.fontSize; font.family: root.fontFamily; font.bold: true; Layout.rightMargin: 8 } - Rectangle { Layout.preferredWidth: 1; Layout.preferredHeight: 16; Layout.rightMargin: 8; color: root.colMuted } - Text { text: " " + cpuTemp; color: tempColor; font.pixelSize: root.fontSize; font.family: root.fontFamily; font.bold: true; Layout.rightMargin: 8 } Rectangle { Layout.preferredWidth: 1; Layout.preferredHeight: 16; Layout.rightMargin: 8; color: root.colMuted } @@ -414,7 +398,18 @@ ShellRoot { Text { text: " " + diskUsage; color: root.colBlue; font.pixelSize: root.fontSize; font.family: root.fontFamily; font.bold: true; Layout.rightMargin: 8 } Rectangle { Layout.preferredWidth: 1; Layout.preferredHeight: 16; Layout.rightMargin: 8; color: root.colMuted } + Text { text: netConnection; color: root.colBlue; font.pixelSize: root.fontSize; font.family: root.fontFamily; font.bold: true; Layout.rightMargin: 4 } // netspeed + RowLayout { + id: netSpeedRow + visible: root.netConnection == "󰤨" + spacing: 0 + + Rectangle { + Layout.preferredWidth: 1; Layout.preferredHeight: 16 + Layout.leftMargin: 8; Layout.rightMargin: 8 + color: root.colMuted + } Text { id: netSpeed color: root.colRed @@ -426,12 +421,13 @@ ShellRoot { Process { id: netProc command: ["bash", "/opt/scripts/netspeed.sh", "wlp8s0"] - running: true + running: root.netConnection == "󰤨" stdout: SplitParser { onRead: data => netSpeed.text = data.trim() } } } + } Rectangle { Layout.preferredWidth: 1; Layout.preferredHeight: 16; Layout.rightMargin: 8; color: root.colMuted } Text { text: " " + volumeLevel + "%"; color: root.colPurple; font.pixelSize: root.fontSize; font.family: root.fontFamily; font.bold: true; Layout.rightMargin: 8 } diff --git a/rmpc/config.ron b/rmpc/config.ron new file mode 100644 index 0000000..a856b51 --- /dev/null +++ b/rmpc/config.ron @@ -0,0 +1,281 @@ +#![enable(implicit_some)] +#![enable(unwrap_newtypes)] +#![enable(unwrap_variant_newtypes)] +( + address: "127.0.0.1:6600", + password: None, + theme: None, + cache_dir: None, + on_song_change: None, + volume_step: 5, + max_fps: 30, + scrolloff: 0, + wrap_navigation: false, + enable_mouse: true, + scroll_amount: 1, + enable_config_hot_reload: true, + enable_lyrics_hot_reload: false, + status_update_interval_ms: 1000, + rewind_to_start_sec: None, + keep_state_on_song_change: true, + reflect_changes_to_playlist: false, + select_current_song_on_change: false, + ignore_leading_the: false, + browser_song_sort: [Disc, Track, Artist, Title], + directories_sort: SortFormat(group_by_type: true, reverse: false), + auto_open_downloads: true, + album_art: ( + method: Auto, + max_size_px: (width: 1200, height: 1200), + disabled_protocols: ["http://", "https://"], + vertical_align: Center, + horizontal_align: Center, + ), + keybinds: ( + global: { + "q": Quit, + "?": ShowHelp, + ":": CommandMode, + "oI": ShowCurrentSongInfo, + "oo": ShowOutputs, + "op": ShowDecoders, + "od": ShowDownloads, + "oP": Partition(), + "z": ToggleRepeat, + "x": ToggleRandom, + "c": ToggleConsume, + "v": ToggleSingle, + "p": TogglePause, + "s": Stop, + ">": NextTrack, + "<": PreviousTrack, + "f": SeekForward, + "b": SeekBack, + ".": VolumeUp, + ",": VolumeDown, + "": NextTab, + "gt": NextTab, + "": PreviousTab, + "gT": PreviousTab, + "1": SwitchToTab("Queue"), + "2": SwitchToTab("Directories"), + "3": SwitchToTab("Artists"), + "4": SwitchToTab("Album Artists"), + "5": SwitchToTab("Albums"), + "6": SwitchToTab("Playlists"), + "7": SwitchToTab("Search"), + "": Update, + "": Rescan, + "R": AddRandom, + }, + navigation: { + "": Close, + "": Close, + "": Confirm, + "k": Up, + "": Up, + "j": Down, + "": Down, + "h": Left, + "": Left, + "l": Right, + "": Right, + "k": PaneUp, + "": PaneUp, + "j": PaneDown, + "": PaneDown, + "h": PaneLeft, + "": PaneLeft, + "l": PaneRight, + "": PaneRight, + "K": MoveUp, + "J": MoveDown, + "": UpHalf, + "": DownHalf, + "": PageUp, + "": PageUp, + "": PageDown, + "": PageDown, + "gg": Top, + "G": Bottom, + "": Select, + "": InvertSelection, + "/": EnterSearch, + "n": NextResult, + "N": PreviousResult, + "a": Add, + "A": AddAll, + "D": Delete, + "": Rename, + "i": FocusInput, + "oi": ShowInfo, + "": ContextMenu(), + "s": Save(kind: Modal(all: false, duplicates_strategy: Ask)), + "a": Save(kind: Modal(all: true, duplicates_strategy: Ask)), + "r": Rate(), + }, + queue: { + "d": Delete, + "D": DeleteAll, + "": Play, + "C": JumpToCurrent, + "X": Shuffle, + }, + ), + search: ( + case_sensitive: false, + ignore_diacritics: false, + search_button: false, + mode: Contains, + tags: [ + (value: "any", label: "Any Tag"), + (value: "artist", label: "Artist"), + (value: "album", label: "Album"), + (value: "albumartist", label: "Album Artist"), + (value: "title", label: "Title"), + (value: "filename", label: "Filename"), + (value: "genre", label: "Genre"), + ], + ), + artists: ( + album_display_mode: SplitByDate, + album_sort_by: Date, + album_date_tags: [Date], + ), + tabs: [ + ( + name: "Queue", + pane: Split( + direction: Horizontal, + panes: [ + ( + size: "35%", + pane: Split( + direction: Vertical, + panes: [ + ( + size: "100%", + borders: "LEFT | RIGHT | TOP", + border_symbols: Rounded, + pane: Pane(AlbumArt) + ), + ( + size: "7", + borders: "ALL", + border_symbols: Inherited(parent: Rounded, top_left: "├", top_right: "┤",), + border_title: [(kind: Text(" Lyrics "))], + border_title_alignment: Right, + pane: Pane(Lyrics) + ), + ], + ), + ), + ( + size: "65%", + pane: Split( + direction: Vertical, + panes: [ + ( + size: "3", + borders: "ALL", + border_symbols: Inherited(parent: Rounded, bottom_left: "├", bottom_right: "┤",), + pane: Split( + direction: Horizontal, + panes: [ + ( + size: "1", + pane: Pane(Empty()) + ), + ( + size: "100%", + pane: Pane(QueueHeader()) + ), + ] + ) + ), + ( + size: "100%", + borders: "LEFT | RIGHT | BOTTOM", + border_symbols: Rounded, + pane: Split( + direction: Horizontal, + panes: [ + ( + size: "1", + pane: Pane(Empty()) + ), + ( + size: "100%", + pane: Pane(Queue) + ), + ] + ) + ), + ], + ) + ), + ], + ), + ), + ( + name: "Directories", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(Directories), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ( + name: "Artists", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(Artists), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ( + name: "Album Artists", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(AlbumArtists), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ( + name: "Albums", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(Albums), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ( + name: "Playlists", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(Playlists), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ( + name: "Search", + borders: "ALL", + border_symbols: Rounded, + pane: Split( + size: "100%", + direction: Vertical, + panes: [(pane: Pane(Search), size: "100%", borders: "ALL", border_symbols: Rounded)], + ) + ), + ], +) diff --git a/scripts/mount-usb.sh b/scripts/mount-usb.sh new file mode 100755 index 0000000..ae53a14 --- /dev/null +++ b/scripts/mount-usb.sh @@ -0,0 +1,109 @@ +#!/bin/bash + +IFS=' +' +lsblkoutput="$(lsblk -rpo "uuid,name,type,size,label,mountpoint,fstype")" +allluks="$(echo "$lsblkoutput" | grep crypto_LUKS)" + +decrypted="$(find /dev/disk/by-id/dm-uuid-CRYPT-LUKS2-* 2>/dev/null | sed "s|.*LUKS2-||;s|-.*||")" + +filter() { sed "s/ /:/g" | awk -F':' '$7==""{printf "%s%s (%s) %s\n", $1,$3,$5,$6}'; } + +unopenedluks="$(for drive in $allluks; do + uuid="${drive%% *}" + uuid="${uuid//-}" + [ -n "$decrypted" ] && for open in $decrypted; do + [ "$uuid" = "$open" ] && break 1 + done && continue 1 + echo "🔒 $drive" +done | filter)" + +normalparts="$(echo "$lsblkoutput" | grep -v crypto_LUKS | grep 'part\|rom\|crypt' | sed "s/^/💾 /" | filter)" + +alldrives="$(echo "$unopenedluks +$normalparts" | sed "/^$/d;s/ *$//")" + +set -e +test -n "$alldrives" + +chosen="$(echo "$alldrives" | rofi -dmenu -p "Mount which drive?")" + +getmount() { + mp="$(find /mnt /media /mount /home -maxdepth 1 -type d 2>/dev/null | rofi -dmenu -p "Mount this drive where?")" + test -n "$mp" + if [ ! -d "$mp" ]; then + mkdiryn=$(printf "No\nYes" | rofi -dmenu -p "$mp does not exist. Create it?") + [ "$mkdiryn" = "Yes" ] && (mkdir -p "$mp" || sudo mkdir -p "$mp") + fi +} + + +attemptmount() { + sudo mount "$chosen" || return 1 + notify-send "💾 Drive mounted." "$chosen mounted." + exit +} + +case "$chosen" in + 💾*) + chosen="${chosen%% *}" + chosen="${chosen:1}" + parttype="$(echo "$lsblkoutput" | grep "$chosen")" + attemptmount || getmount + + case "${parttype##* }" in + vfat) sudo mount -t vfat "$chosen" "$mp" -o rw,umask=0000 ;; + btrfs) sudo mount "$chosen" "$mp" ;; + *) sudo mount "$chosen" "$mp" -o uid="$(id -u)",gid="$(id -g)" ;; + esac + notify-send "💾 Drive Mounted." "$chosen mounted to $mp" + ;; + + 🔒*) + chosen="${chosen%% *}" + chosen="${chosen:1}" + + num="00" + while true; do + [ -b "/dev/mapper/usb$num" ] || break + num="$(printf "%02d" "$((10#$num + 1))")" + done + + MAPPER="$usb$num" + + ${TERMINAL:-st} -n floatpattern -g 60x1 -e sudo cryptsetup open "$chosen" "$MAPPER" + + if ! test -b "/dev/mapper/$MAPPER"; then + notify-send "❌ Decryption Failed" "Could not open $chosen" + exit 1 + fi + + FSTYPE="$(blkid -o value -s TYPE "/dev/mapper/$MAPPER" 2>/dev/null)" + + getmount + + case "$FSTYPE" in + vfat|exfat) + sudo mount -t "$FSTYPE" "/dev/mapper/$MAPPER" "$mp" -o uid="$(id -u)",gid="$(id -g)",umask=022 + ;; + ntfs|ntfs-3g) + sudo mount -t ntfs-3g "/dev/mapper/$MAPPER" "$mp" -o uid="$(id -u)",gid="$(id -g)" + ;; + ext2|ext3|ext4|btrfs|xfs) + sudo mount -t "$FSTYPE" "/dev/mapper/$MAPPER" "$mp" + ;; + *) + sudo mount "/dev/mapper/$MAPPER" "$mp" + esac + + + if mountpoint -q "$mp"; then + notify-send "🔓 Decrypted Drive Mounted." "$chosen mounted to $mp" + else + notify-send "❌ Mount failed." "Could not mount /dev/mapper/$MAPPER to $mp." + sudo cryptsetup close "$MAPPER" + fi + + ;; +esac + diff --git a/scripts/umount-usb.sh b/scripts/umount-usb.sh new file mode 100755 index 0000000..e745ef2 --- /dev/null +++ b/scripts/umount-usb.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +set -e + +lsblkoutput="$(lsblk -nrpo "name,type,size,mountpoint")" +mounteddrives="$(echo "$lsblkoutput" | awk '($2=="part"||$2="crypt")&&$4!~/\/boot|\/home$|SWAP/&&length($4)>1{printf "%s (%s)\n",$4,$3}')" + +allunmountable="$(echo "$mounteddrives" | sed "/^$/d;s/ *$//")" +test -n "$allunmountable" + +chosen="$(echo "$allunmountable" | rofi -dmenu -p "Unmount which drive?")" +chosen="${chosen%% *}" +test -n "$chosen" + +sudo umount -l "/${chosen#*/}" +notify-send "💾 Device unmounted." "$chosen has been unmounted" + +cryptid="$(echo "$lsblkoutput" | grep "/${chosen#*/}$")" +cryptid="${cryptid%% *}" +test -b /dev/mapper/"${cryptid##*/}" +sudo cryptsetup close "$cryptid" +notify-send "🔒 Device dencryption closed." "Drive is now securely locked again." diff --git a/scripts/weather.py b/scripts/weather.py index 0c2af7b..27395a9 100755 --- a/scripts/weather.py +++ b/scripts/weather.py @@ -6,41 +6,41 @@ import json from dotenv import load_dotenv def getWeatherIcon(isDayTime: bool, weatherDescription: str): - if weatherDescription in ["CLEAR", "MOSTLY_CLEAR"]: + if weatherDescription in ["CLEAR"]: if isDayTime: - return " " + return "☀️" else: - return " " - if weatherDescription in ["PARTLY_CLOUDY"]: + return "🌙 " + if weatherDescription in ["PARTLY_CLOUDY", "MOSTLY_CLEAR"]: if isDayTime: - return " " + return "⛅" else: return " " if weatherDescription in ["CLOUDY", "MOSTLY_CLOUDY"]: - return " " + return "☁️" if weatherDescription in ["LIGHT_RAIN", "LIGHT_TO_MODERATE_RAIN","LIGHT_RAIN_SHOWERS"]: if isDayTime: - return " " + return "🌦️" else: return " " if weatherDescription in ["RAIN", "RAIN_SHOWERS", "HEAVY_RAIN", "HEAVY_RAIN_SHOWERS", "MODERATE_TO_HEAVY_RAIN", "RAIN_PERIODICALLY_HEAVY"]: - return " " + return "🌧️" if weatherDescription in ["SNOW", "LIGHT_SNOW", "HEAVY_SNOW", "SNOW_SHOWERS", "LIGHT_SNOW_SHOWERS", "HEAVY_SNOW_SHOWERS", "SNOWSTORM", "BLOWING_SNOW", "RAIN_AND_SNOW", "HAIL"]: - return " " + return "❄️" if weatherDescription in ["LIGHT_THUNDERSTORM_RAIN"]: if isDayTime: - return " " + return "⛈️" else: - return " " + return "⛈️" if weatherDescription in ["THUNDERSHOWER", "SCATTERED_THUNDERSTORMS", "THUNDERSTORM", "HEAVY_THUNDERSTORM"]: - return " " + return "🌩️" if weatherDescription in ["WINDY"]: if isDayTime: - return " " + return "🍃" else: - return " " + return "🍃" if weatherDescription in ["FOG","HAZE","DUST","MIST","SMOKE"]: if isDay: @@ -52,8 +52,8 @@ def getWeatherIcon(isDayTime: bool, weatherDescription: str): url = "https://weather.googleapis.com/v1/currentConditions:lookup" -lat = "25.4448" -long = "81.8432" +lat = "" +long = "" load_dotenv() params = { @@ -69,8 +69,8 @@ currentTemperature = jsonDump["temperature"]["degrees"] weatherDescription = jsonDump["weatherCondition"]["type"] isDaytime = jsonDump["isDaytime"] precipitation = jsonDump["precipitation"]["probability"]["percent"] - +windSpeed = jsonDump["wind"]["speed"]["value"] weatherIcon = getWeatherIcon(isDaytime, weatherDescription) -print(weatherIcon, f"{currentTemperature}°C",f" {precipitation}%") +print(weatherIcon, f"{currentTemperature}°C",f"☔ {precipitation}%", f"🌬️ {windSpeed}kph") diff --git a/yazi/init.lua b/yazi/init.lua new file mode 100644 index 0000000..7568c87 --- /dev/null +++ b/yazi/init.lua @@ -0,0 +1,128 @@ +require("full-border"):setup() +require("fs-usage"):setup() + +function Linemode:size_and_mtime() + + local time = math.floor(self._file.cha.mtime or 0) + if time == 0 then + time = "" + elseif os.date("%Y", time) == os.date("%Y") then + time = os.date("%b %d %H:%M", time) + else + time = os.date("%b %d %Y", time) + end + + local size = self._file:size() + return string.format("%s %s", size and ya.readable_size(size) or "-", time) +end + + + +require("lin-decompress"):setup({ + -- Global commands for all .tar.* archives (e.g. .tar.lz, .tar.lzo, .tar.gz) + global_tar_compressor = { + -- Commands for each .tar.* archive, + -- Appends these 'cmd's only if 'no_global_tar = false' is set for a .tar.* configuration below + cmd = { "-dkc" }, + }, + + -- NOTE: Use the '[name of mimetype]' portion when defining new extractors' + -- + -- Schema: + -- ["application/[]"] ={ + -- tool_name = "Name of tool to use for this mimetype", + -- cmd = { list of arguments to use}, + -- no_global_tar = true (default: false) (Appends the commands specified in the 'global_tar_compressor.cmd') + -- exts = {extension_name = true, ...} (Extension names of the archive to extract. Used only as a fallback in case mime detection fails) + -- } + -- Configurations for compressors commonly used with .tar.* + tar_compressors = { + ["lz4"] = { + tool_name = "lz4", + exts = { + lz4 = true, + }, + }, + ["xz"] = { + tool_name = "xz", + cmd = { "-T0" }, + exts = { + xz = true, + }, + }, + ["gzip"] = { + tool_name = "gzip", + exts = { + gz = true, + }, + }, + ["compress"] = { + tool_name = "uncompress", + exts = { + Z = true, + }, + }, + ["bzip2"] = { + tool_name = "bzip2", + exts = { + bz2 = true, + }, + }, + ["zstd"] = { + tool_name = "zstd", + cmd = { "-T0" }, + exts = { + zst = true, + }, + }, + ["lzop"] = { + tool_name = "lzop", + exts = { + lzo = true, + }, + }, + ["lzip"] = { + tool_name = "lzip", + exts = { + lz = true, + }, + }, + ["lzma"] = { + tool_name = "lzma", + exts = { + lzma = true, + }, + }, + }, + -- NOTE: Use the '[name of mimetype]' portion when defining new extractors' + -- + -- Schema: + -- ["application/[name of mimetype]"] ={ + -- tool_name = "Name of tool to use", + -- cmd = {list of arguments to use }, + -- out_cmd = "The command to output extracted content", + -- pw_cmd = "Command to input a Password" + -- exts = {extension_name = true, ...} (Extension names of the archive to extract. Used only as a fallback in case mime detection fails) + -- } + -- Configurations for non .tar archives + other_compressors = { + ["rar"] = { + tool_name = "unrar", + cmd = { "x" }, + out_cmd = "-op", + pw_cmd = "-p", + exts = { + rar = true, + }, + }, + -- The default tool to use to extract ALL types of archive files + ["default"] = { + tool_name = "7z", + cmd = { "x", "-mmt=0" }, + out_cmd = "-o", + pw_cmd = "-p", + }, + }, +}) + + diff --git a/yazi/keymap.toml b/yazi/keymap.toml new file mode 100644 index 0000000..4099a34 --- /dev/null +++ b/yazi/keymap.toml @@ -0,0 +1,68 @@ +[[mgr.prepend_keymap]] +on = [ "c", "a", "a" ] +run = "plugin compress" +desc = "Archive selected files" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "p" ] +run = "plugin compress -p" +desc = "Archive selected files (password)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "h" ] +run = "plugin compress -ph" +desc = "Archive selected files (password+header)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "l" ] +run = "plugin compress -l" +desc = "Archive selected files (compression level)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "u" ] +run = "plugin compress -phl" +desc = "Archive selected files (password+header+level)" + +[[mgr.prepend_keymap]] +on = [ "c", "m" ] +run = "plugin chmod" +esc = "Chmod on selected files" + +[[mgr.prepend_keymap]] +on = ["c","x"] +run = "plugin lin-decompress -- --no-password" +desc = "Extract hovered." + +[[mgr.prepend_keymap]] +on = ["c","p"] +run = "plugin lin-decompress" +desc = "Extract hovered. Password" + +[[mgr.prepend_keymap]] +on = ["c","a"] +run = "plugin lin-decompress -- --no-hover --tabselect=all" +desc = "Extract selected in all tabs" + +[[mgr.prepend_keymap]] +on = ["c","A"] +run = "plugin lin-decompress -- --tabselect=all" +desc = "Extract selected in all tabs. Hovered included" + +[[mgr.prepend_keymap]] +on = ["c","x","c"] +run = "plugin lin-decompress -- --no-hover --tabselect=current" +desc = "Extract selected in current tab only" + +[[mgr.prepend_keymap]] +on = "" +run = [ "yank", 'plugin clipboard -- --action=copy' ] + +[[mgr.prepend_keymap]] +on = "" +run = [ 'plugin clipboard -- --action=paste' ] + +[[mgr.prepend_keymap]] +on = [ "R" ] +run = "plugin rsync" +desc = "Copy files using rsync" + diff --git a/yazi/package.toml b/yazi/package.toml new file mode 100644 index 0000000..4fa3cdb --- /dev/null +++ b/yazi/package.toml @@ -0,0 +1,47 @@ +[[plugin.deps]] +use = "KKV9/compress" +rev = "46a6b9f" +hash = "771af2becc575a3f43d0542de823969d" + +[[plugin.deps]] +use = "yazi-rs/plugins:chmod" +rev = "e84f4fe" +hash = "f0c8c378184d5f8abd1b095a443d336d" + +[[plugin.deps]] +use = "ZimCodes/lin-decompress" +rev = "592fee3" +hash = "1b1eb812c57d18a2047c1e8e1536274f" + +[[plugin.deps]] +use = "XYenon/clipboard" +rev = "3b96810" +hash = "13d7eb15a079c735e34124b922322de5" + +[[plugin.deps]] +use = "GianniBYoung/rsync" +rev = "44f6979" +hash = "9e85283824277bf66011a3977d266edb" + +[[plugin.deps]] +use = "yazi-rs/plugins:full-border" +rev = "e84f4fe" +hash = "6fa6a05a81c98dd000fbca3cca6e9682" + +[[plugin.deps]] +use = "Reledia/glow" +rev = "bd3eaa5" +hash = "92b5c58159a51c567f82b618cee2b78" + +[[plugin.deps]] +use = "AminurAlam/yazi-plugins:preview-audio" +rev = "1d28640" +hash = "e8a166503389d5a2165762daedb54821" + +[[plugin.deps]] +use = "walldmtd/fs-usage" +rev = "4f4992b" +hash = "61410fb3409c22990a52767c738c2722" + +[flavor] +deps = [] diff --git a/yazi/plugins/chmod.yazi/LICENSE b/yazi/plugins/chmod.yazi/LICENSE new file mode 100644 index 0000000..fb5b1d6 --- /dev/null +++ b/yazi/plugins/chmod.yazi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 yazi-rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/yazi/plugins/chmod.yazi/README.md b/yazi/plugins/chmod.yazi/README.md new file mode 100644 index 0000000..5a73207 --- /dev/null +++ b/yazi/plugins/chmod.yazi/README.md @@ -0,0 +1,28 @@ +# chmod.yazi + +Execute `chmod` on the selected files to change their mode. This plugin is only available on Unix platforms since it relies on [`chmod(2)`](https://man7.org/linux/man-pages/man2/chmod.2.html). + +https://github.com/yazi-rs/plugins/assets/17523360/7aa3abc2-d057-498c-8473-a6282c59c464 + +## Installation + +```sh +ya pkg add yazi-rs/plugins:chmod +``` + +## Usage + +Add this to your `~/.config/yazi/keymap.toml`: + +```toml +[[mgr.prepend_keymap]] +on = [ "c", "m" ] +run = "plugin chmod" +desc = "Chmod on selected files" +``` + +Note that, the keybindings above are just examples, please tune them up as needed to ensure they don't conflict with your other actions/plugins. + +## License + +This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file. diff --git a/yazi/plugins/chmod.yazi/main.lua b/yazi/plugins/chmod.yazi/main.lua new file mode 100644 index 0000000..87af0bf --- /dev/null +++ b/yazi/plugins/chmod.yazi/main.lua @@ -0,0 +1,47 @@ +--- @since 26.1.22 + +local selected_or_hovered = ya.sync(function() + local tab, paths = cx.active, {} + for _, u in pairs(tab.selected) do + paths[#paths + 1] = tostring(u) + end + if #paths == 0 and tab.current.hovered then + paths[1] = tostring(tab.current.hovered.url) + end + return paths +end) + +local function fail(s, ...) + ya.notify { + title = "Chmod", + content = string.format(s, ...), + level = "error", + timeout = 5, + } +end + +return { + entry = function() + ya.emit("escape", { visual = true }) + + local urls = selected_or_hovered() + if #urls == 0 then + return ya.notify { title = "Chmod", content = "No file selected", level = "warn", timeout = 5 } + end + + local value, event = ya.input { + title = "Chmod:", + pos = { "top-center", y = 3, w = 40 }, + } + if event ~= 1 then + return + end + + local output, err = Command("chmod"):arg(value):arg(urls):output() + if not output then + fail("Failed to run chmod: %s", err) + elseif not output.status.success then + fail("Chmod failed with stderr:\n%s", output.stderr:gsub("^chmod:%s*", "")) + end + end, +} diff --git a/yazi/plugins/clipboard.yazi/LICENSE b/yazi/plugins/clipboard.yazi/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/yazi/plugins/clipboard.yazi/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/yazi/plugins/clipboard.yazi/README.md b/yazi/plugins/clipboard.yazi/README.md new file mode 100644 index 0000000..52807a3 --- /dev/null +++ b/yazi/plugins/clipboard.yazi/README.md @@ -0,0 +1,64 @@ +# clipboard.yazi + +Synchronize the file paths currently yanked in the Yazi file manager with your system clipboard. The plugin supports macOS and Linux desktops out of the box. + +## Requirements + +| Platform | Dependency | +| -------- | ---------- | +| Linux | `xclip` (X11), `wl-copy` (Wayland) | +| macOS | Built-in `osascript` | + +## Installation + +Install the plugin via the package manager: + +```bash +ya pkg add XYenon/clipboard +``` + +This clones the repository, adds it to `~/.config/yazi/package.toml`, and pins the current revision. + +## Usage + +Add shortcuts in `~/.config/yazi/keymap.toml`: + +```toml +[[mgr.prepend_keymap]] +on = "y" +run = [ "yank", 'plugin clipboard -- --action=copy' ] + +[[mgr.prepend_keymap]] +on = "" +run = [ 'plugin clipboard -- --action=paste' ] +``` + +## Optional arguments + +The plugin accepts the boolean argument `notify-unknown-display-server`: + +- Default `false`: silently exit when the Linux display server is unknown (useful for TTY or remote sessions). +- `true`: show a notification to warn that copying is unavailable in the current session. + +Example invocation: + +```toml +[[mgr.prepend_keymap]] +on = "y" +run = [ "yank", 'plugin clipboard -- --action=copy --notify-unknown-display-server' ] +``` + +## Troubleshooting + +- **`Copy failed: xclip/wl-copy not found`**: install `xclip` for X11 or `wl-clipboard` (`wl-copy`) for Wayland. +- **`Unknown display server`**: ensure Yazi runs in a Wayland or X11 session. Enable `notify-unknown-display-server` to surface a visible warning. + +## Development + +This repository uses [treefmt](https://github.com/numtide/treefmt) for formatting: + +```bash +nix fmt +``` + +Feel free to open a PR to support more desktop environments or add paste functionality. diff --git a/yazi/plugins/clipboard.yazi/main.lua b/yazi/plugins/clipboard.yazi/main.lua new file mode 100644 index 0000000..0849adc --- /dev/null +++ b/yazi/plugins/clipboard.yazi/main.lua @@ -0,0 +1,450 @@ +local get_yanked_paths = ya.sync(function(state) + local paths = {} + for _, v in pairs(cx.yanked) do + if not v.is_regular then + goto continue + end + table.insert(paths, tostring(v)) + ::continue:: + end + return paths +end) + +local get_cwd = ya.sync(function(state) + return tostring(cx.active.current.cwd) +end) + +local M = { + notify_unknown_display_server = false, +} + +function M:entry(job) + ya.dbg("Clipboard", "args", job.args) + self.notify_unknown_display_server = job.args.notify_unknown_display_server or false + + if job.args.action == "copy" then + return self:copy() + elseif job.args.action == "paste" then + return self:paste() + else + return self:notify_error("Unknown action: " .. tostring(job.args.action)) + end +end + +function M:copy() + local paths = get_yanked_paths() + ya.dbg("Clipboard", "files", paths) + if #paths == 0 then + return self:notify_error("No files to copy") + end + + local cmd, err = nil, nil + local args = paths + if ya.target_os() == "linux" then + cmd, err = self:copy_linux_cmd() + if cmd then + args = {} + for _, p in ipairs(paths) do + table.insert(args, self:path_to_file_uri(p)) + end + end + elseif ya.target_os() == "macos" then + cmd, err = self:copy_macos_cmd() + else + err = "Unsupported OS: " .. ya.target_os() + end + if not self.notify_unknown_display_server and err == "Unknown display server" then + return + end + if err then + return self:notify_error("Copy failed: " .. err) + end + + ya.dbg("Clipboard", "cmd", cmd) + local cmd = Command("sh"):arg({ "-c", cmd, "--" }):arg(args) + local output, err = cmd:output() + if err then + ya.err("Clipboard", "cmd failed", err) + return self:notify_error("Run command failed: " .. tostring(err)) + end + if output then + ya.dbg("Clipboard", "cmd output", output.status.code, output.stdout, output.stderr) + end +end + +function M:copy_linux_cmd() + if self:linux_display_server() == "x11" then + return self:copy_x11_cmd() + elseif self:linux_display_server() == "wayland" then + return self:copy_wayland_cmd() + else + return nil, "Unknown display server" + end +end + +function M:copy_macos_cmd() + -- Generated by GPT-5-Codex + cmd = [[osascript - "$@" < 1) + end + if choice == "skip" then + skipped = skipped + 1 + goto continue + elseif choice == "rename" then + dest = self:unique_name(cwd_url, name) + end + end + + local ok, copy_err = self:copy_path(src, dest) + if ok then + copied = copied + 1 + else + ya.err("Clipboard", "copy failed", src, tostring(copy_err)) + table.insert(errors, name .. ": " .. tostring(copy_err)) + end + ::continue:: + end + end + + if copied > 0 or skipped > 0 then + local parts = {} + if copied > 0 then + table.insert(parts, "Pasted " .. copied .. " file(s)") + end + if skipped > 0 then + table.insert(parts, "Skipped " .. skipped .. " file(s)") + end + ya.notify({ + title = "Clipboard", + content = table.concat(parts, ", "), + timeout = 3, + level = "info", + }) + end + if #errors > 0 then + self:notify_error("Failed to paste:\n" .. table.concat(errors, "\n")) + end +end + +function M:ask_conflict(name, multiple) + local prompt = name .. " exists: (o)verwrite (r)ename (s)kip" + if multiple then + prompt = prompt .. " (O/R/S=apply to all)" + end + local value, event = ya.input({ + title = prompt, + pos = { "center", w = #prompt + 4 }, + }) + if event ~= 1 or not value or value == "" then + return "skip", nil + end + local c = value:sub(1, 1) + local apply_all = nil + if multiple and c == c:upper() then + c = c:lower() + if c == "o" then + apply_all = "overwrite" + elseif c == "r" then + apply_all = "rename" + elseif c == "s" then + apply_all = "skip" + end + end + if c == "o" then + return "overwrite", apply_all + elseif c == "r" then + return "rename", apply_all + else + return "skip", apply_all + end +end + +function M:unique_name(cwd_url, name) + local base, ext = name:match("^(.+)(%.[^.]+)$") + if not base then + base = name + ext = "" + end + local i = 1 + while true do + local candidate = base .. " (" .. i .. ")" .. ext + local candidate_url = cwd_url:join(candidate) + if not fs.cha(candidate_url) then + return tostring(candidate_url) + end + i = i + 1 + end +end + +function M:copy_path(src, dest) + local src_url = Url(src) + local dest_url = Url(dest) + local cha, err = fs.cha(src_url) + if not cha then + return false, "cannot stat: " .. tostring(err) + end + + if cha.is_dir then + return self:copy_dir(src_url, dest_url) + else + local ok, copy_err = fs.copy(src_url, dest_url) + if ok then + return true, nil + else + return false, tostring(copy_err) + end + end +end + +function M:copy_dir(src_url, dest_url) + local ok, err = fs.create("dir_all", dest_url) + if not ok then + return false, "mkdir failed: " .. tostring(err) + end + + local entries, read_err = fs.read_dir(src_url, {}) + if not entries then + return false, "read_dir failed: " .. tostring(read_err) + end + + for _, entry in ipairs(entries) do + local child_dest = dest_url:join(entry.name) + if entry.cha.is_dir then + local ok, dir_err = self:copy_dir(entry.url, child_dest) + if not ok then + return false, dir_err + end + else + local ok, copy_err = fs.copy(entry.url, child_dest) + if not ok then + return false, tostring(copy_err) + end + end + end + + return true, nil +end + +function M:paste_macos() + local cmd = Command("osascript"):arg({ + "-e", + [[ +use framework "Foundation" +use framework "AppKit" +use scripting additions + +set pasteboard to (current application's NSPasteboard's generalPasteboard()) +set urlArray to (pasteboard's readObjectsForClasses_options_({current application's |NSURL|}, missing value)) + +if urlArray is missing value then return "" + +set pathList to {} +repeat with u in urlArray + set end of pathList to (u's |path|() as text) +end repeat + +set AppleScript's text item delimiters to (character id 0) +return pathList as text +]], + }) + local output, err = cmd:output() + if err then + ya.err("Clipboard", "paste macos failed", err) + return nil, "osascript failed: " .. tostring(err) + end + if not output or output.status.code ~= 0 then + return nil, "osascript exited with code " .. tostring(output and output.status.code) + end + + local stdout = output.stdout + if not stdout then + return {}, nil + end + stdout = stdout:gsub("%s+$", "") + if stdout == "" then + return {}, nil + end + local paths = {} + for path in stdout:gmatch("[^%z]+") do + path = path:gsub("%s+$", "") + if path ~= "" then + table.insert(paths, path) + end + end + return paths, nil +end + +function M:paste_linux() + if self:linux_display_server() == "x11" then + return self:paste_x11() + elseif self:linux_display_server() == "wayland" then + return self:paste_wayland() + else + return nil, "Unknown display server" + end +end + +function M:paste_x11() + local status, err = Command("which"):arg("xclip"):status() + if err or not (status and status.success) then + return nil, "xclip not found" + end + local output, err = Command("xclip"):arg({ "-o", "-selection", "clipboard", "-t", "text/uri-list" }):output() + if err then + return nil, "xclip failed: " .. tostring(err) + end + if not output or output.status.code ~= 0 then + return {}, nil + end + return self:parse_uri_list(output.stdout), nil +end + +function M:paste_wayland() + local status, err = Command("which"):arg("wl-paste"):status() + if err or not (status and status.success) then + return nil, "wl-paste not found" + end + local output, err = Command("wl-paste"):arg({ "-t", "text/uri-list" }):output() + if err then + return nil, "wl-paste failed: " .. tostring(err) + end + if not output or output.status.code ~= 0 then + return {}, nil + end + return self:parse_uri_list(output.stdout), nil +end + +function M:parse_uri_list(text) + if not text or text == "" then + return {} + end + local paths = {} + for line in text:gmatch("[^\r\n]+") do + if line:sub(1, 1) ~= "#" then + local path = line:match("^file://[^/]*(/.+)") + if path then + path = path:gsub("%%(%x%x)", function(hex) + return string.char(tonumber(hex, 16)) + end) + table.insert(paths, path) + end + end + end + return paths +end + +function M:path_to_file_uri(path) + local encoded = path:gsub("([^A-Za-z0-9/_.~-])", function(c) + return string.format("%%%02X", string.byte(c)) + end) + return "file://" .. encoded +end + +function M:notify_error(msg) + ya.notify({ title = "Clipboard", content = msg, timeout = 6.5, level = "error" }) +end + +return M diff --git a/yazi/plugins/compress.yazi/LICENSE b/yazi/plugins/compress.yazi/LICENSE new file mode 100644 index 0000000..7ce7a2f --- /dev/null +++ b/yazi/plugins/compress.yazi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Ciarán O'Brien + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/yazi/plugins/compress.yazi/README.md b/yazi/plugins/compress.yazi/README.md new file mode 100644 index 0000000..7241cf7 --- /dev/null +++ b/yazi/plugins/compress.yazi/README.md @@ -0,0 +1,152 @@ +

🗜️ compress.yazi

+

+ A blazing fast, flexible archive plugin for Yazi
+ Effortlessly compress your files and folders with style! +

+ +## 📖 Table of Contents + +- [Features](#-features) +- [Supported File Types](#-supported-file-types) +- [Installation](#%EF%B8%8F-installation) +- [Keymap Example](#-keymap-example) +- [Usage](#%EF%B8%8F-usage) +- [Flags](#%EF%B8%8F-flags) +- [Tips](#-tips) +- [Credits](#-credits) + +## 🚀 Features + +- 🗂️ **Multi-format support:** zip, 7z, rar, tar, tar.gz, tar.xz, tar.bz2, tar.zst, tar.lz4, tar.lha +- 🌍 **Cross-platform:** Works on Unix & Windows +- 🔒 **Password protection:** Secure your archives (zip/7z/rar) +- 🛡️ **Header encryption:** Hide file lists (7z/rar) +- ⚡ **Compression level:** Choose your balance of speed vs. size +- 🛑 **Overwrite safety:** Never lose files by accident +- 🎯 **Seamless Yazi integration:** Fast, native-like UX + +## 📦 Supported File Types + +| Extension | Default Command | 7z Command | Bsdtar Command (Win10+ & Unix) | +| ------------- | ----------------- | -------------- | ------------------------------ | +| `.zip` | `zip -r` | `7z a -tzip` | `tar -caf` | +| `.7z` | `7z a` | `7z a` | | +| `.rar` | `rar a` | | | +| `.tar` | `tar rpf` | | `tar rpf` | +| `.tar.gz` | `tar rpf + gzip` | `7z a -tgzip` | `tar -czf` | +| `.tar.xz` | `tar rpf + xz` | `7z a -txz` | `tar -cJf` | +| `.tar.bz2` | `tar rpf + bzip2` | `7z a -tbzip2` | `tar -cjf` | +| `.tar.zst` | `tar rpf + zstd` | | `tar --zstd -cf` | +| `.tar.lz4` | `tar rpf + lz4` | | | +| `.tar.lha` | `tar rpf + lha` | | | + + +## ⚡️ Installation + +```bash +# Unix +git clone https://github.com/KKV9/compress.yazi.git ~/.config/yazi/plugins/compress.yazi + +# Windows (CMD, not PowerShell!) +git clone https://github.com/KKV9/compress.yazi.git %AppData%\yazi\config\plugins\compress.yazi + +# Or with yazi plugin manager +ya pkg add KKV9/compress +``` +### 🔧 Extras (Windows) + +To enable additional compression formats and features on Windows, follow these steps: + +1. **Install [7-Zip](https://www.7-zip.org/):** + Add `C:\Program Files\7-Zip` to your `PATH`. + This enables support for `.7z` archives and password-protected `.zip` files. + +2. **Alternative: Install [Nanazip](https://github.com/M2Team/NanaZip):** + A modern alternative to 7-Zip with similar functionality and extra features. + +3. **Install [WinRAR](https://www.win-rar.com/download.html):** + Add `C:\Program Files\WinRAR` to your `PATH`. + This enables support for `.rar` archives. + +4. **Install Additional Tools:** + To use formats like `lha`, `lz4`, `gzip`, etc., install their respective tools and ensure they are added to your `PATH`. + +## 🎹 Keymap Example + +Add this to your `keymap.toml`: + + +```toml +[[mgr.prepend_keymap]] +on = [ "c", "a", "a" ] +run = "plugin compress" +desc = "Archive selected files" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "p" ] +run = "plugin compress -p" +desc = "Archive selected files (password)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "h" ] +run = "plugin compress -ph" +desc = "Archive selected files (password+header)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "l" ] +run = "plugin compress -l" +desc = "Archive selected files (compression level)" + +[[mgr.prepend_keymap]] +on = [ "c", "a", "u" ] +run = "plugin compress -phl" +desc = "Archive selected files (password+header+level)" +``` + +## 🛠️ Usage + +1. **Select files/folders** in Yazi. +2. Press c a to open the archive dialog. +3. Choose: + - a for a standard archive + - p for password protection (zip/7z/rar) + - h to encrypt header (7z/rar) + - l to set compression level (all compression algorithims) + - u for all options together +4. **Type a name** for your archive (or leave blank for suggested name). +5. **Enter password** and/or **compression level** if prompted. +6. **Overwrite protect** if a file already exists, the new file will be given a suffix _#. +7. Enjoy your shiny new archive! + +## 🏳️‍🌈 Flags + +- Combine flags for more power! +- when separating flags with spaces, make sure to single quote them (eg., `'-ph rar'`) +- `-p` Password protect (zip/7z/rar) +- `-h` Encrypt header (7z/rar) +- `-l` Set compression level (all compression algorithims) +- `-s` Silence success message +- `` Specify a default extention (eg., `7z`, `tar.gz`) + +#### Combining multiple flags: +```toml +[[mgr.prepend_keymap]] +on = [ "c", "a", "7" ] +run = "plugin compress '-ph 7z'" +desc = "Archive selected files to 7z (password+header)" +[[mgr.prepend_keymap]] +on = [ "c", "a", "r" ] +run = "plugin compress '-p -l rar'" +desc = "Archive selected files to rar (password+level)" +``` +## 💡 Tips + +- The file extension **must** match a supported type. +- The required compression tool **must** be installed and in your `PATH` (7zip/rar etc.). +- If no extention is provided, the default extention (zip) will be appended automatically. +- If you leave the filename blank, the plugin will use the selected filename or parent directory, when multiple files are selected, to name the archive. + +## 📣 Credits + +Made with ❤️ for [Yazi](https://github.com/sxyazi/yazi) by [KKV9](https://github.com/KKV9). +Contributions are welcome! Feel free to submit a pull request. diff --git a/yazi/plugins/compress.yazi/main.lua b/yazi/plugins/compress.yazi/main.lua new file mode 100644 index 0000000..440f6e2 --- /dev/null +++ b/yazi/plugins/compress.yazi/main.lua @@ -0,0 +1,577 @@ +--- @since 25.12.29 + +-- Check for windows +local is_windows = ya.target_family() == "windows" + +-- Define default flags and strings +local is_password, is_encrypted, is_level, is_silent_success = false, false, false, false +local default_extension = "zip" + +-- Allow dots when matching file extension arguments +local function extension_pattern(ext) + return "%." .. ext:gsub("%.", "%%.") .. "$" +end + +-- Function to check valid filename +local function is_valid_filename(name) + -- Trim whitespace from both ends + name = name:match("^%s*(.-)%s*$") + if name == "" then + return false + end + if is_windows then + -- Windows forbidden chars and reserved names + if name:find('[<>:"/\\|%?%*]') then + return false + end + else + -- Unix forbidden chars + if name:find("/") or name:find("%z") then + return false + end + end + return true +end + +-- Function to send notifications +local function notify(message, level) + ya.notify({ + title = "Archive", + content = message, + level = level, + timeout = 5, + }) +end + +-- Function to check if command is available +local function is_command_available(cmd) + local stat_cmd + if is_windows then + stat_cmd = string.format("where %s > nul 2>&1", cmd) + else + stat_cmd = string.format("command -v %s >/dev/null 2>&1", cmd) + end + return os.execute(stat_cmd) +end + +-- Function to find first available command from list +local function find_command_name(cmd_list) + for _, cmd in ipairs(cmd_list) do + if is_command_available(cmd) then + return cmd + end + end + return cmd_list[1] -- Return first command as fallback +end + +-- Function to append filename to its parent directory url +local function combine_url(path, file) + local path_url = Url(path) + local file_url = Url(file) + return tostring(path_url:join(file_url)) +end + +-- Function to make a table of selected or hovered files: path = filenames +local selected_or_hovered = ya.sync(function() + local tab = cx.active + local paths = {} + local names = {} + local path_fnames = {} + + for _, u in pairs(tab.selected) do + paths[#paths + 1] = tostring(u.parent) + names[#names + 1] = tostring(u.name) + end + + if #paths == 0 and tab.current.hovered then + paths[1] = tostring(tab.current.hovered.url.parent) + names[1] = tostring(tab.current.hovered.name) + end + + for idx, name in ipairs(names) do + local path = paths[idx] + if not path_fnames[path] then + path_fnames[path] = {} + end + table.insert(path_fnames[path], name) + end + + return path_fnames, names, tostring(tab.current.cwd) +end) + +-- Function to cleanup temporary directory +local function cleanup_temp_dir(temp_dir) + local status, err = fs.remove("dir_all", Url(temp_dir)) + if not status then + notify( + string.format("Failed to clean up temporary directory %s, error: %s", ya.quote(temp_dir), tostring(err)), + "error" + ) + return false + end + return true +end + +-- Function for compression level +local function add_compression_level(target_args, level_arg, level_value) + if type(level_arg) == "table" then + -- Insert each element except last + for i = 1, #level_arg - 1 do + table.insert(target_args, i, level_arg[i]) + end + -- Add the level value with the last element + table.insert(target_args, #level_arg, level_arg[#level_arg] .. level_value) + else + -- Single string argument + table.insert(target_args, 1, level_arg .. level_value) + end +end + +-- Function for password handling +local function get_password_args(archive_cmd, encrypted, header_arg) + local output_password, event = ya.input({ + title = "Enter password:", + obscure = true, + pos = { "top-center", y = 3, w = 40 }, + }) + if event ~= 1 or output_password == "" then + return nil + end + -- Handling for RAR with encryption + if archive_cmd == "rar" and encrypted then + return { header_arg .. output_password } + end + return { "-P" .. output_password } +end + +-- Table of archive commands +local archive_commands = { + ["%.zip$"] = { + { command = "zip", args = { "-r" }, level_arg = "-", level_min = 0, level_max = 9, passwordable = true }, + { + command = { "7z", "7zz", "7za" }, + args = { "a", "-tzip" }, + level_arg = "-mx=", + level_min = 0, + level_max = 9, + passwordable = true, + }, + { + command = { "tar", "bsdtar" }, + args = { "-caf" }, + level_arg = { "--option", "compression-level=" }, + level_min = 1, + level_max = 9, + }, + }, + ["%.7z$"] = { + { + command = { "7z", "7zz", "7za" }, + args = { "a" }, + level_arg = "-mx=", + level_min = 0, + level_max = 9, + header_arg = "-mhe=on", + passwordable = true, + }, + }, + ["%.rar$"] = { + { + command = "rar", + args = { "a" }, + level_arg = "-m", + level_min = 0, + level_max = 5, + header_arg = "-hp", + passwordable = true, + }, + }, + ["%.tar%.gz$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-", + level_min = 1, + level_max = 9, + compress = "gzip", + }, + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-mx=", + level_min = 1, + level_max = 9, + compress = "7z", + compress_args = { "a", "-tgzip" }, + }, + { + command = { "tar", "bsdtar" }, + args = { "-czf" }, + level_arg = { "--option", "gzip:compression-level=" }, + level_min = 1, + level_max = 9, + }, + }, + ["%.tar%.xz$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-", + level_min = 1, + level_max = 9, + compress = "xz", + }, + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-mx=", + level_min = 1, + level_max = 9, + compress = "7z", + compress_args = { "a", "-txz" }, + }, + { + command = { "tar", "bsdtar" }, + args = { "-cJf" }, + level_arg = { "--option", "xz:compression-level=" }, + level_min = 1, + level_max = 9, + }, + }, + ["%.tar%.bz2$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-", + level_min = 1, + level_max = 9, + compress = "bzip2", + }, + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-mx=", + level_min = 1, + level_max = 9, + compress = "7z", + compress_args = { "a", "-tbzip2" }, + }, + { + command = { "tar", "bsdtar" }, + args = { "-cjf" }, + level_arg = { "--option", "bzip2:compression-level=" }, + level_min = 1, + level_max = 9, + }, + }, + ["%.tar%.zst$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-", + level_min = 1, + level_max = 22, + compress = "zstd", + compress_args = { "--ultra" }, + }, + }, + ["%.tar%.lz4$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-", + level_min = 1, + level_max = 12, + compress = "lz4", + }, + }, + ["%.tar%.lha$"] = { + { + command = { "tar", "bsdtar" }, + args = { "rpf" }, + level_arg = "-o", + level_min = 5, + level_max = 7, + compress = "lha", + compress_args = { "-a" }, + }, + }, + ["%.tar$"] = { + { command = { "tar", "bsdtar" }, args = { "rpf" } }, + }, +} + +-- Function for command matching +local function find_archive_command(output_name) + for pattern, cmd_list in pairs(archive_commands) do + if output_name:match(pattern) then + for _, cmd in ipairs(cmd_list) do + -- Check if archive command is available + local cmd_name = type(cmd.command) == "table" and find_command_name(cmd.command) or cmd.command + if is_command_available(cmd_name) then + -- Check if compress command (if listed) is available + if not cmd.compress or is_command_available(cmd.compress) then + return { + cmd = cmd_name, + args = cmd.args, + compress = cmd.compress or "", + level_arg = cmd.level_arg or "", + level_min = cmd.level_min, + level_max = cmd.level_max, + header_arg = cmd.header_arg or "", + passwordable = cmd.passwordable or false, + compress_args = cmd.compress_args or {}, + } + end + end + end + -- Pattern matched but no suitable command found + return nil + end + end + -- No pattern matched - unsupported extension + return false +end + +return { + entry = function(_, job) + -- Parse flags and default extension + if job.args then + for _, arg in ipairs(job.args) do + if arg:match("^%-(%w+)$") then + -- Handle combined flags (e.g., -phl) + for flag in arg:sub(2):gmatch(".") do + if flag == "p" then + is_password = true + elseif flag == "h" then + is_encrypted = true + elseif flag == "l" then + is_level = true + elseif flag == "s" then + is_silent_success = true + end + end + elseif arg:match("^[%w%.]+$") then + -- Handle default extension (e.g., 7z, zip) + if archive_commands[extension_pattern(arg)] then + default_extension = arg + else + notify(string.format("Unsupported extension: %s", arg), "warn") + end + else + notify(string.format("Unknown argument: %s", arg), "warn") + end + end + end + + -- Exit visual mode + ya.emit("escape", { visual = true }) + + -- Define file table and output_dir (pwd) + local path_fnames, fnames, output_dir = selected_or_hovered() + + -- Get archive filename + local output_name, event = ya.input({ + title = "Create archive:", + pos = { "top-center", y = 3, w = 40 }, + }) + if event ~= 1 then + return + end + + -- Determine the default name for the archive + local default_name = #fnames == 1 and fnames[1] or Url(output_dir).name + output_name = output_name == "" and string.format("%s.%s", default_name, default_extension) or output_name + + -- Add default extension if none is specified + if not output_name:match("%.%w+$") then + output_name = string.format("%s.%s", output_name, default_extension) + end + + -- Validate the final archive filename + if not is_valid_filename(output_name) then + notify("Invalid archive filename", "error") + return + end + + -- Command matching + local archive_config = find_archive_command(output_name) + if archive_config == false then + notify("Unsupported file extension", "error") + return + elseif not archive_config then + notify("Could not find a suitable archive program for the selected file extension", "error") + return + end + + -- Extract configuration + local archive_cmd = archive_config.cmd + local archive_args = archive_config.args + local archive_compress = archive_config.compress + local archive_level_arg = is_level and archive_config.level_arg or "" + local archive_level_min = archive_config.level_min + local archive_level_max = archive_config.level_max + local archive_header_arg = is_encrypted and archive_config.header_arg or "" + local archive_passwordable = archive_config.passwordable + local archive_compress_args = archive_config.compress_args + + -- Password handling + if archive_passwordable and is_password then + local password_args = get_password_args(archive_cmd, is_encrypted, archive_header_arg) + if password_args then + for _, arg in ipairs(password_args) do + table.insert(archive_args, arg) + end + end + end + + -- Add header arg if selected for 7z + if is_encrypted and archive_header_arg ~= "" and archive_cmd ~= "rar" then + table.insert(archive_args, archive_header_arg) + end + + -- Use extracted compression level + if archive_level_arg ~= "" and is_level then + local output_level, level_event = ya.input({ + title = string.format("Enter compression level (%s - %s)", archive_level_min, archive_level_max), + pos = { "top-center", y = 3, w = 40 }, + }) + if level_event ~= 1 then + return + end + -- Validate user input for compression level + local level_num = tonumber(output_level) + if level_num and level_num >= archive_level_min and level_num <= archive_level_max then + local target_args = archive_compress == "" and archive_args or archive_compress_args + add_compression_level(target_args, archive_level_arg, output_level) + else + notify("Invalid level specified. Using defaults.", "warn") + end + end + + -- Store the original output name for later use + local original_name = output_name + + -- If compression is needed, adjust the output name to exclude extensions like ".tar" + if archive_compress ~= "" then + output_name = output_name:match("(.*%.tar)") or output_name + end + + -- Create a temporary directory for intermediate files + local temp_dir_name = ".tmp_compress" + local temp_dir = combine_url(output_dir, temp_dir_name) + temp_dir = tostring(fs.unique_name(Url(temp_dir))) + + -- Attempt to create the temporary directory + local temp_dir_status, temp_dir_err = fs.create("dir_all", Url(temp_dir)) + if not temp_dir_status then + -- Notify the user if the temporary directory creation fails + notify(string.format("Failed to create temp directory, error code: %s", tostring(temp_dir_err)), "error") + return + end + + -- Define the temporary output file path within the temporary directory + local temp_output_url = combine_url(temp_dir, output_name) + + -- Add files to the output archive + for filepath, filenames in pairs(path_fnames) do + -- Execute the archive command for each path and its respective files + local archive_status, archive_err = + Command(archive_cmd):arg(archive_args):arg(temp_output_url):arg(filenames):cwd(filepath):spawn():wait() + if not archive_status or not archive_status.success then + -- Notify the user if the archiving process fails and clean up the temporary directory + notify( + string.format( + "Failed to create archive %s with '%s', error: %s", + ya.quote(output_name), + archive_cmd, + tostring(archive_err) + ), + "error" + ) + cleanup_temp_dir(temp_dir) + return + end + end + + -- If compression is required, execute the compression command + if archive_compress ~= "" then + local compress_status, compress_err + + -- Check if using 7z for compression (requires output file argument) + if archive_compress:match("^7z") then + local compressed_output = combine_url(temp_dir, original_name) + compress_status, compress_err = Command(archive_compress) + :arg(archive_compress_args) + :arg(compressed_output) + :arg(temp_output_url) + :spawn() + :wait() + else + -- Native compression tools (gzip, xz, bzip2, etc.) compress in-place + compress_status, compress_err = + Command(archive_compress):arg(archive_compress_args):arg(temp_output_url):spawn():wait() + end + + if not compress_status or not compress_status.success then + -- Notify the user if the compression process fails and clean up the temporary directory + notify( + string.format( + "Failed to compress archive %s with '%s', error: %s", + ya.quote(output_name), + archive_compress, + tostring(compress_err) + ), + "error" + ) + cleanup_temp_dir(temp_dir) + return + end + end + + -- Move the final file from the temporary directory to the output directory + local final_output_url = combine_url(output_dir, original_name) + local temp_url_processed = combine_url(temp_dir, original_name) + final_output_url = tostring(fs.unique_name(Url(final_output_url))) + local from, to = Url(temp_url_processed), Url(final_output_url) + local move_status, move_err = fs.rename(from, to) + if not move_status then + if move_err and move_err.kind == "CrossesDevices" then + local copy_status, copy_err = fs.copy(from, to) + if not copy_status then + notify( + string.format( + "Failed to copy across devices %s to %s, error: %s", + ya.quote(from.name), + ya.quote(to.name), + copy_err and tostring(copy_err.kind) or "unknown" + ), + "error" + ) + cleanup_temp_dir(temp_dir) + return + end + else + notify( + string.format( + "Failed to move %s to %s, error: %s", + ya.quote(from.name), + ya.quote(to.name), + move_err and tostring(move_err.kind) or "unknown" + ), + "error" + ) + cleanup_temp_dir(temp_dir) + return + end + end + + -- Cleanup the temporary directory after successful operation + cleanup_temp_dir(temp_dir) + + -- Notify user of success + if not is_silent_success then + notify(string.format("Successfully created archive: %s", ya.quote(to.name)), "info") + end + end, +} diff --git a/yazi/plugins/fs-usage.yazi/LICENSE b/yazi/plugins/fs-usage.yazi/LICENSE new file mode 100644 index 0000000..18e9226 --- /dev/null +++ b/yazi/plugins/fs-usage.yazi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 walldmtd + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/yazi/plugins/fs-usage.yazi/README.md b/yazi/plugins/fs-usage.yazi/README.md new file mode 100644 index 0000000..1544634 --- /dev/null +++ b/yazi/plugins/fs-usage.yazi/README.md @@ -0,0 +1,93 @@ +# fs-usage.yazi + +A [Yazi](https://github.com/sxyazi/yazi) plugin to show the current partition's used space in the header or status. + +![preview_normal.png](previews/preview_normal.png) + +![preview_warning.png](previews/preview_warning.png) + +## Installation + +> [!IMPORTANT] +> +> - This plugin is only supported on Linux (uses `df`) +> - It *might* work with WSL, but that is untested +> - Requires Yazi v25.5.31 or later + +Install with `ya`: + +```sh +ya pkg add walldmtd/fs-usage +``` + +## Usage + +To use the default setup, add this somewhere in `~/.config/yazi/init.lua`: + +```lua +require("fs-usage"):setup() +``` + +To customize it, add this instead and adjust/remove the options as needed: + +```lua +require("fs-usage"):setup({ + -- All values are optional + + -- Position of the component + -- parent: Parent component ("Header" or "Status") + -- align: Anchor point within parent object ("LEFT" or "RIGHT") + -- order: Order relative to others in the same parent + -- Default: { parent = "Header", align = "RIGHT", order = 2000 } + position = { parent = "Header", align = "RIGHT", order = 2000 }, + + -- Text format + -- One of: + -- "both": Partition name and percent used + -- "name": Only partition name + -- "usage": Only percent used + -- Default: "both" + format = "both", + + -- Option to enable or disable the usage bar + -- Default: true + bar = true, + + -- Percent usage to use the warning style (-1 to disable) + -- Default: 90 + warning_threshold = 90, + + -- For style options, any unset options use the progress bar style + -- from the Yazi flavor if available, otherwise it falls back to + -- the default Yazi style. + + -- Label text style + -- fg: Text colour (String like "white", or hex like "#ffffff") + -- (Can also be "" to use the reverse of the bar colour) + -- bold: Make the label bold (bool) + -- italic: Make the label italic (bool) + -- Example: style_label = { fg = "", bold = true, italic = false }, + -- Default: {} + style_label = {}, + + -- Usage bar style + -- fg: Bar colour (String like "blue", or hex like "#0000ff") + -- bg: Bar background colour (Same format as fg) + -- Example: style_normal = { fg = "blue", bg = "black" }, + -- Default: {} + style_normal = {}, + + -- Usage bar style when the used space is above the warning threshold + -- Options are the same as style_normal + -- Default: {} + style_warning = {}, + + -- Bar padding + -- open: Character on the left (string) + -- close: Character on the right (string) + -- Example: { open = "█", close = "█" } for square corners, + -- or { open = "", close = "" } for no padding + -- Default: { open = "", close = "" } + padding = { open = "", close = "" } +}) +``` diff --git a/yazi/plugins/fs-usage.yazi/main.lua b/yazi/plugins/fs-usage.yazi/main.lua new file mode 100644 index 0000000..dbcdef2 --- /dev/null +++ b/yazi/plugins/fs-usage.yazi/main.lua @@ -0,0 +1,292 @@ +--- @since 25.5.31 + +local DEFAULT_OPTIONS = { + -- Can't reference Header.RIGHT etc. here (it hangs) so parent and align are strings + -- 2000 puts it to the right of the indicator, and leaves some room between + position = { parent = "Header", align = "RIGHT", order = 2000 }, + format = "both", + bar = true, + warning_threshold = 90, + style_label = { + fg = th.status.progress_label:fg(), + }, + style_normal = { + fg = th.status.progress_normal:fg(), + bg = th.status.progress_normal:bg(), + }, + style_warning = { + fg = th.status.progress_error:fg(), + bg = th.status.progress_error:bg(), + }, + padding = { open = "", close = "" }, +} + +---Deep copy and merge two tables, overwriting values from one table into another +---@param from Table to take values from +---@param to Table to merge into +local function merge(into, from) + -- Handle nil inputs + into = into or {} + from = from or {} + + local result = {} + + -- Deep copy 'into' first + for k, v in pairs(into) do + if type(v) == "table" then + result[k] = merge({}, v) + else + result[k] = v + end + end + + -- Merge + for k, v in pairs(from) do + if type(v) == "table" then + result[k] = merge(result[k], v) + else + result[k] = v + end + end + + return result +end + +---Merge label and bar styles into left/right styles for the bar +---@param style_label Label style +---@param style_bar Usage bar style +local function build_styles(style_label, style_bar) + local style_right = ui.Style():fg(style_label.fg or style_bar.fg):bg(style_bar.bg) -- Label bg is ignored + if style_label.bold then + style_right = style_right:bold() + end + if style_label.italic then + style_right = style_right:italic() + end + + -- Left style is the same as right, but with fg/bg reversed + -- (this is overridden by the label colour if set) + local style_left = ui.Style():patch(style_right):fg(style_label.fg or style_bar.bg):bg(style_bar.fg) -- Label bg is ignored + + return style_left, style_right +end + +---Parse source and usage from df output +---@param stdout string df output +local function process_df_output(stdout) + local source, usage = stdout:match(".*%s(%S+)%s+(%S+)") + + -- Follow symlinks in source + if string.sub(source, 1, 1) == "/" then + source = Command("readlink"):arg({ "--silent", "--canonicalize", "--no-newline", source }):output().stdout + end + + -- Assume usage is a valid percentage + -- Remove the percent and parse + usage = tonumber(string.sub(usage, 1, #usage - 1)) + + return source, usage +end + +---Format text based on options +---@param source Source +---@param usage Usage +---@param format Format +local function format_text(source, usage, format) + local text = "" + if format == "both" then + text = string.format("%s: %d%%", source, usage) + elseif format == "name" then + text = string.format("%s", source) + elseif format == "usage" then + text = string.format("%d%%", usage) + end + return text +end + +---Set new plugin state and redraw +local set_state = ya.sync(function(st, source, usage, text, bar_len) + st.source = source + st.usage = usage + st.text = text + st.bar_len = bar_len + + local render = ui.render or ya.render + render() +end) + +---Get plugin state needed by entry +local get_state = ya.sync(function(st) + return { + -- Persistent options + format = st.format, + bar = st.bar, + padding = st.padding, + + -- Variables + source = st.source, + usage = st.usage, + } +end) + +-- Called from init.lua +---@param st State +---@param opts Options +local function setup(st, opts) + opts = merge(DEFAULT_OPTIONS, opts) + + -- Allow unsetting some options + if opts.style_label.fg == "" then + opts.style_label.fg = nil + end + if opts.warning_threshold < 0 then + opts.warning_threshold = nil + end + + -- Translate opts.position.parent option into a component reference + if opts.position.parent == "Header" then + opts.position.parent = Header + elseif opts.position.parent == "Status" then + opts.position.parent = Status + else + -- Just set it to nil, it's gonna cause errors anyway + opts.position.parent = nil + end + + -- Set persistent options + local style_normal_left, style_normal_right = build_styles(opts.style_label, opts.style_normal) + local style_warning_left, style_warning_right = build_styles(opts.style_label, opts.style_warning) + st.style = { + normal = { + left = style_normal_left, + right = style_normal_right, + padding = { + left = ui.Style():fg(style_normal_left:bg()), + right = ui.Style():fg(style_normal_right:bg()), + }, + }, + warning = { + left = style_warning_left, + right = style_warning_right, + padding = { + left = ui.Style():fg(style_warning_left:bg()), + right = ui.Style():fg(style_warning_right:bg()), + }, + }, + } + st.format = opts.format + st.bar = opts.bar + st.warning_threshold = opts.warning_threshold + st.padding = opts.padding + + -- Add the component to the parent + opts.position.parent:children_add(function(self) + -- No point showing anything if usage is nil + if not st.usage then + return + end + + local style = (st.warning_threshold and st.usage >= st.warning_threshold) and st.style.warning + or st.style.normal + + -- Apply styles to components based on the bar length, and ad them to the bar + local output = {} + local bar_len = st.bar_len + local components = { + { text = st.padding.open, style = style.padding }, + { text = st.text, style = style }, + { text = st.padding.close, style = style.padding }, + } + for _, component in ipairs(components) do + -- bar_len_bytes should point to the last byte that should be coloured by the usage bar + local bar_len_bytes + if bar_len <= 0 then + -- 1-indexed, so effectively no bar showing + bar_len_bytes = 0 + elseif bar_len >= utf8.len(component.text) then + bar_len_bytes = #component.text + else + bar_len_bytes = utf8.offset(component.text, bar_len + 1) - 1 + end + + if bar_len_bytes > 0 then + table.insert(output, ui.Span(string.sub(component.text, 1, bar_len_bytes)):style(component.style.left)) + end + if bar_len_bytes < #component.text then + table.insert( + output, + ui.Span(string.sub(component.text, bar_len_bytes + 1)):style(component.style.right) + ) + end + + bar_len = bar_len - utf8.len(component.text) + end + + return ui.Line(output) + end, opts.position.order, opts.position.parent[opts.position.align]) + + ---Pass cwd to the plugin for df + local function callback() + ya.emit("plugin", { + st._id, + ya.quote(tostring(cx.active.current.cwd), true), + }) + end + + -- Subscribe to events + ps.sub("cd", callback) + ps.sub("tab", callback) + ps.sub("delete", callback) + -- These are the only relevant events that actually work + -- Note: df might not immediately reflect usage changes + -- when deleting files +end + +-- Called from ya.emit in the callback +---@param job Job +local function entry(_, job) + local cwd = job.args[1] + + -- Don't set cwd directly for Command() here, it hangs for dirs without read perms + -- cwd is fine as an argument to df though + local output = Command("df"):arg({ "--output=source,pcent", tostring(cwd) }):output() + + -- If df fails, hide the module + if not output.status.success then + set_state(nil, nil, nil, nil) + return + end + + local source, usage = process_df_output(output.stdout) + + -- If df read the filesystem but couldn't get a percentage, hide the module + -- if usage == nil then + if type(usage) ~= "number" then + set_state(nil, nil, nil, nil) + return + end + + -- Get the plugin state (async) early since we know it will be used + local st = get_state() + + -- If nothing has changed, don't bother updating + if source == st.source and usage == st.usage then + return + end + + local text = format_text(source, usage, st.format) + local bar_len = 0 -- Start with no bar by default + + -- Only calculate bar length if the bar will be shown + if st.bar then + local total_len = utf8.len(st.padding.open .. text .. st.padding.close) + + -- Using ceil so the bar is only empty at 0% + -- Using len - 1 so the bar isn't full until 100% + bar_len = usage < 100 and math.ceil((total_len - 1) / 100 * usage) or total_len + end + + set_state(source, usage, text, bar_len) +end + +return { setup = setup, entry = entry } diff --git a/yazi/plugins/full-border.yazi/LICENSE b/yazi/plugins/full-border.yazi/LICENSE new file mode 100644 index 0000000..fb5b1d6 --- /dev/null +++ b/yazi/plugins/full-border.yazi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 yazi-rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/yazi/plugins/full-border.yazi/README.md b/yazi/plugins/full-border.yazi/README.md new file mode 100644 index 0000000..269ca8e --- /dev/null +++ b/yazi/plugins/full-border.yazi/README.md @@ -0,0 +1,32 @@ +# full-border.yazi + +Add a full border to Yazi to make it look fancier. + +![full-border](https://github.com/yazi-rs/plugins/assets/17523360/ef81b560-2465-4d36-abf2-5d21dcb7b987) + +## Installation + +```sh +ya pkg add yazi-rs/plugins:full-border +``` + +## Usage + +Add this to your `init.lua` to enable the plugin: + +```lua +require("full-border"):setup() +``` + +Or you can customize the border type: + +```lua +require("full-border"):setup { + -- Available values: ui.Border.PLAIN, ui.Border.ROUNDED + type = ui.Border.ROUNDED, +} +``` + +## License + +This plugin is MIT-licensed. For more information check the [LICENSE](LICENSE) file. diff --git a/yazi/plugins/full-border.yazi/main.lua b/yazi/plugins/full-border.yazi/main.lua new file mode 100644 index 0000000..5277c19 --- /dev/null +++ b/yazi/plugins/full-border.yazi/main.lua @@ -0,0 +1,44 @@ +--- @since 25.2.26 + +local function setup(_, opts) + local type = opts and opts.type or ui.Border.ROUNDED + local old_build = Tab.build + + Tab.build = function(self, ...) + local bar = function(c, x, y) + if x <= 0 or x == self._area.w - 1 or th.mgr.border_symbol ~= "│" then + return ui.Bar(ui.Edge.TOP) + end + + return ui.Bar(ui.Edge.TOP) + :area( + ui.Rect { x = x, y = math.max(0, y), w = ya.clamp(0, self._area.w - x, 1), h = math.min(1, self._area.h) } + ) + :symbol(c) + end + + local c = self._chunks + self._chunks = { + c[1]:pad(ui.Pad.y(1)), + -- TODO: remove this compatibility hack + fs.unique and c[2]:pad(ui.Pad.y(1)) or c[2]:pad(ui.Pad(1, c[3].w > 0 and 0 or 1, 1, c[1].w > 0 and 0 or 1)), + c[3]:pad(ui.Pad.y(1)), + } + + local style = th.mgr.border_style + self._base = ya.list_merge(self._base or {}, { + ui.Border(ui.Edge.ALL):area(self._area):type(type):style(style), + ui.Bar(ui.Edge.RIGHT):area(self._chunks[1]):style(style), + ui.Bar(ui.Edge.LEFT):area(self._chunks[3]):style(style), + + bar("┬", c[1].right - 1, c[1].y), + bar("┴", c[1].right - 1, c[1].bottom - 1), + bar("┬", c[2].right, c[2].y), + bar("┴", c[2].right, c[2].bottom - 1), + }) + + old_build(self, ...) + end +end + +return { setup = setup } diff --git a/yazi/plugins/glow.yazi/LICENSE b/yazi/plugins/glow.yazi/LICENSE new file mode 100644 index 0000000..de882e5 --- /dev/null +++ b/yazi/plugins/glow.yazi/LICENSE @@ -0,0 +1,7 @@ +Copyright © 2024 Reledia + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/yazi/plugins/glow.yazi/README.md b/yazi/plugins/glow.yazi/README.md new file mode 100644 index 0000000..5e12e0f --- /dev/null +++ b/yazi/plugins/glow.yazi/README.md @@ -0,0 +1,33 @@ +# glow.yazi + +>[!WARNING] +>This plugin is now deprecated with the release of [Piper](https://github.com/yazi-rs/plugins/tree/main/piper.yazi#examples) + +Plugin for [Yazi](https://github.com/sxyazi/yazi) to preview markdown files with [glow](https://github.com/charmbracelet/glow). To install, run the below mentioned command: + +```bash +ya pack -a Reledia/glow +``` + +then include it in your `yazi.toml` to use: + +```toml +[plugin] +prepend_previewers = [ + { name = "*.md", run = "glow" }, +] +``` + +Make sure you have [glow](https://github.com/charmbracelet/glow) installed, and can be found in `PATH`. + +## Feature + ++ You can modify line wrap in `main.lua`, the current value is 55. ++ You can press `ctrl+e` to scroll up and `ctrl+y` to scroll down the readme file in preview panel in yazi: (add this to `keymap.toml`) +```toml +prepend_keymap = [ + # glow.yazi + { on = [""], run = "seek 5" }, + { on = [""], run = "seek -5" }, +] +``` diff --git a/yazi/plugins/glow.yazi/main.lua b/yazi/plugins/glow.yazi/main.lua new file mode 100644 index 0000000..8883feb --- /dev/null +++ b/yazi/plugins/glow.yazi/main.lua @@ -0,0 +1,64 @@ +local M = {} + +function M:peek(job) + -- Set a fixed width of 50 characters for the preview + local preview_width = 55 + + local child = Command("glow") + :args({ + "--style", + "dark", + "--width", + tostring(preview_width), -- Use fixed width instead of job.area.w + tostring(job.file.url), + }) + :env("CLICOLOR_FORCE", "1") + :stdout(Command.PIPED) + :stderr(Command.PIPED) + :spawn() + + if not child then + return require("code").peek(job) + end + + local limit = job.area.h + local i, lines = 0, "" + repeat + local next, event = child:read_line() + if event == 1 then + return require("code").peek(job) + elseif event ~= 0 then + break + end + + i = i + 1 + if i > job.skip then + lines = lines .. next + end + until i >= job.skip + limit + + child:start_kill() + if job.skip > 0 and i < job.skip + limit then + ya.mgr_emit("peek", { + tostring(math.max(0, i - limit)), + only_if = job.file.url, + upper_bound = true + }) + else + lines = lines:gsub("\t", string.rep(" ", rt.preview.tab_size)) + ya.preview_widgets(job, { ui.Text.parse(lines):area(job.area) }) + end +end + +function M:seek(job) + local h = cx.active.current.hovered + if not h or h.url ~= job.file.url then + return + end + ya.mgr_emit('peek', { + math.max(0, cx.active.preview.skip + job.units), + only_if = job.file.url, + }) +end + +return M diff --git a/yazi/plugins/lin-decompress.yazi/LICENSE b/yazi/plugins/lin-decompress.yazi/LICENSE new file mode 100644 index 0000000..1dfc269 --- /dev/null +++ b/yazi/plugins/lin-decompress.yazi/LICENSE @@ -0,0 +1,10 @@ +MIT License + + +Copyright © 2026 ZimCodes + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/yazi/plugins/lin-decompress.yazi/README.md b/yazi/plugins/lin-decompress.yazi/README.md new file mode 100644 index 0000000..b2a5e4f --- /dev/null +++ b/yazi/plugins/lin-decompress.yazi/README.md @@ -0,0 +1,102 @@ +# lin-decompress + +A [yazi plugin](https://github.com/sxyazi/yazi) to extract each archive using a specialized tool for **Linux**. + +Map a variety of different extractor tools to their archive(s) for extraction. + +## Support + +`lin-decompress` is customizable enough to support many archives & extractor tools. +The table below shows how `lin-decompress` utilizes each of the _default_ extractor tools. + +| Extension | Tools | Commands | +| ---------- | -------- | ------- | +| `.rar` | `unrar` |`unrar x -op -p` | +| `.tar`,`.tar.*` | `tar` | `tar -xf --overwrite -C (-I )`| +|`.lz4` | `lz4` | `lz4 -dkc ` | +| `.xz` | `xz` | `xz -T0 -dkc ` | +| `.gz`| `gzip` | `gzip -dkc ` | +| `.bz2` | `bzip2` | `bzip2 -dkc ` | +| `.zst` | `zstd`| `zstd -T0 -dkc `| +| `.lzo` |`lzop` | `lzop -dkc ` | +| `.lz` | `lzip`| `lzip -dkc ` | +| `.lzma` | `lzma` | `lzma -dkc `| +| _(default)_ `.*`| `7zip` | `7z x -mmt=0 -o -p` | + +## Installation + +```bash +# Method 1 +git clone https://github.com/ZimCodes/lin-decompress.yazi ~/.config/yazi/plugins/lin-decompress.yazi/main.lua + +# Method 2 +ya pkg add ZimCodes/lin-decompress +``` + +## Setup + +After installation, here are some things you need to setup. + +### Init.lua + +You **must** copy the entire code found in [`INIT.md`](./INIT.md) to your `init.lua`. +Afterwards, read the comments for guidelines on mapping your extractor tool(s) +to their archive(s). If you are okay with the defaults, then you're all set! + +### Keymap + +Customize your keymap to your liking. Here's one you can add to your `keymap.toml`: + +```toml +[[mgr.prepend_keymap]] +on = ["x","x","x"] +run = "plugin lin-decompress -- --no-password" +desc = "Extract hovered." + +[[mgr.prepend_keymap]] +on = ["x","x","p"] +run = "plugin lin-decompress" +desc = "Extract hovered. Password" + +[[mgr.prepend_keymap]] +on = ["x","x","a"] +run = "plugin lin-decompress -- --no-hover --tabselect=all" +desc = "Extract selected in all tabs" + +[[mgr.prepend_keymap]] +on = ["x","x","A"] +run = "plugin lin-decompress -- --tabselect=all" +desc = "Extract selected in all tabs. Hovered included" + +[[mgr.prepend_keymap]] +on = ["x","x","c"] +run = "plugin lin-decompress -- --no-hover --tabselect=current" +desc = "Extract selected in current tab only" +``` + +## Options + +_**--no-hover**_ + +Do not extract the file you're currently hovering over. By default, hovered files are extracted. + +_**--tabselect=`SELECT_TYPE`**_ + +`SELECT_TYPE` choices: + +- `all` + - Gets selected files from all tabs +- `current` or `active` + - Gets selected files from current tab +- `` _(default)_ + - Does not get selected files from any tabs + +_**--no-password**_ + +Do not prompt for password. By default, when an extractor with the ability to use a password is used, the user will be prompt for password. + +_Alternatively_, when prompt appears, users can enter `!!!` to temporarily disable prompting for the current run. + +## License + +`lin-decompress` uses the [MIT License](./LICENSE). diff --git a/yazi/plugins/lin-decompress.yazi/main.lua b/yazi/plugins/lin-decompress.yazi/main.lua new file mode 100644 index 0000000..d240870 --- /dev/null +++ b/yazi/plugins/lin-decompress.yazi/main.lua @@ -0,0 +1,419 @@ +-- Debugger +local IS_DEBUG = false +local function dmsg(msg) + if IS_DEBUG then + ya.dbg(msg) + end +end +-- Sync Helpers +local function tabs_to_table(tabs) + local t = {} + for i = 1, #tabs do + table.insert(t, tabs[i]) + end + return t +end +-- Syncs +local get_configs = ya.sync(function(state) + return state.config +end) +local get_files = ya.sync(function(state, args) + local tabs, paths = {}, {} + if args.tabselect then + if args.tabselect == "all" then + tabs = tabs_to_table(cx.tabs) + elseif args.tabselect == "active" or args.tabselect == "current" then + table.insert(tabs, cx.active) + end + for _, tab in pairs(tabs) do + for _, url in pairs(tab.selected) do + table.insert(paths, tostring(url.path)) + end + end + end + if not args.no_hover then + table.insert(paths, tostring(cx.active.current.hovered.url.path)) + end + return paths +end) +-- Notify Users +local function alert(msg, opts) + opts = opts or {} + ya.notify({ + title = "lin-decompress", + content = msg, + timeout = opts.timeout or 10, + level = opts.level or "info", + }) +end +-- Create directory +local function create_dir(dir_path) + local is_successful, error = fs.create("dir_all", Url(dir_path)) + if not is_successful then + alert("Unable to create directory -> " .. dir_path, { level = "error" }) + ya.err(tostring(error)) + end + return is_successful +end +-- Ask User +local function ask(msg, default, opts) + opts = opts or {} + local width = opts.width or 40 + local y = opts.y or 10 + local should_fail = opts.should_fail and true or false + local should_hide = opts.obscure and true or false + local value, event = ya.input({ + pos = { "top-center", x = -width + 10, y = y, w = width }, + title = msg, + value = default, + obscure = should_hide, + realtime = false, + debounce = 0.3, + }) + dmsg("Asked: '" .. msg .. "'") + if should_fail or not value then + error("Error occurred when asking user: '" .. msg .. "'") + end + return value +end +-- Ask encryption credential +local function ask_cred() + return ask("Password?: (Stop asking[!!!])", "", { obscure = true }) +end +-- Ask User output directory +local function ask_output(path) + local url = Url(path) + local parent_dir = url.parent + local extract_dir = ask("Directory to extract ALL archives?", tostring(parent_dir)) + return extract_dir +end +-- Variables +local cmd_options = {} +local global_tar_cmd = {} +local tar_cmd = { + ["tar"] = { + tool_name = "tar", + cmd = { "--overwrite" }, + in_cmd = "-xf", + out_cmd = "-C", + sub_cmd = "-I", + }, +} +local archive_cmds = {} +-- Strip content from mime-type +local function strip_type(str) + local f_index, _ = string.find(str, ":") + local file_type = string.sub(str, f_index + 1 or 1) + file_type = string.gsub(file_type, "\n", "") + file_type = string.gsub(file_type, "%s", "") + return file_type +end +-- Identify filetype +local function get_type(path) + dmsg("Getting type for Path: " .. path) + local output, err = Command("file"):arg("--mime-type"):arg(path):output() + if err then + alert("Unable to get mimetype for -> " .. path, { level = "error" }) + ya.err(tostring(err)) + return nil + end + return strip_type(output.stdout) +end +-- Get tar archive commands +local function get_tar_cmds_by_mime(mimetype) + for archive_name, cmd in pairs(tar_cmd) do + if string.find(mimetype, archive_name) then + return { is_tar_type = true, cmds = cmd } + end + end + return {} +end +local function get_tar_cmds_by_ext(ext) + for _, cmd in pairs(tar_cmd) do + if cmd.exts[ext] then + return { is_tar_type = true, cmds = cmd } + end + end + return {} +end +-- Get other archive type commands +local function get_other_cmds_by_mime(mimetype) + for archive_name, cmd in pairs(archive_cmds) do + if string.find(mimetype, archive_name) then + return { cmds = cmd } + end + end + return { cmds = archive_cmds["default"] } +end +local function get_other_cmds_by_ext(ext) + for _, cmd in pairs(archive_cmds) do + if cmd.exts[ext] then + return { cmds = cmd } + end + end + return { cmds = archive_cmds["default"] } +end +-- Get commands for archive by extension +local function get_cmds_by_ext(ext) + local cmds = get_tar_cmds_by_ext(ext) + if cmds.is_tar_type then + return cmds + end + return get_other_cmds_by_ext(ext) +end +-- Get commands for archive by mimetype +local function get_cmds_by_mime(mimetype) + local cmds = get_tar_cmds_by_mime(mimetype) + if cmds.is_tar_type then + return cmds + end + return get_other_cmds_by_mime(mimetype) +end +-- Get commands for archive +local function get_cmds(mimetype, path) + if string.find(mimetype, "octet-stream") then + local ext = Url(path).ext + return get_cmds_by_ext(ext) + else + return get_cmds_by_mime(mimetype) + end +end +-- Is tool installed? +local function tool_exists(tool_name) + local s = Command("which"):arg(tool_name):status() + return s and s.code == 0 +end +-- Selects an archive extract tool +local function get_tool(cmds) + if tool_exists(cmds.tool_name) then + return cmds + end + cmds.is_tar_type = false + return archive_cmds["default"] +end +-- Concatenate two items to strings +local function str_concat(item1, item2) + local result = "" + for _, v in ipairs({ item1, item2 }) do + if type(v) == "table" then + result = string.format("%s %s", result, table.concat(v, " ")) + else + if result == "" then + result = v + else + result = result .. " " .. v + end + end + end + return string.gsub(result, "(%s%s)%s*", " ") +end +-- Add collection of arguments to a command +local function get_command_args(command, args) + if args then + for i, arg in ipairs(args) do + command = command:arg(arg) + end + end + return command +end +-- Remove extracted folder with the same name as parent. e.g. (foo/foo/) +local function remove_dup_dir(archive_dir) + local archive_url = Url(archive_dir) + local files, err = fs.read_dir(archive_url, { limit = 1 }) + if err then + alert(err, { level = "error" }) + return + end + local file = files and files[1] or nil + dmsg("Dup Suspect: " .. file.name) + dmsg("Dup: " .. file.name .. " and " .. archive_url.name) + if not file or not file.cha.is_dir or file.name ~= archive_url.name then + dmsg("Directory does not contain duplicate at -> " .. archive_dir) + return + end + local _, err2 = Command("sh"):arg("-c"):arg("mv " .. file.url.path .. "/* " .. archive_dir):output() + if err2 then + dmsg(err2) + dmsg("Failed to move duplicate directory") + return + end + fs.remove("dir", file.url) +end +-- Retrieve archive directory save location +local function get_archive_dir(inputs, path) + local url = Url(path) + local strip_tar_path = string.gsub(url.stem, "%.tar$", "", 1) + local output_dir = Url(inputs.output) + local archive_url = output_dir:join(strip_tar_path) + return tostring(archive_url) +end +-- Retrieve extracted file url +local function get_extracted_file_url(inputs, path) + local path_url = Url(path) + local output_url = Url(inputs.output) + local full_file_name = path_url.name or "file_name" + local file_name_wo_archive_ext = string.gsub(full_file_name, ".%w+$", "", 1) + return output_url:join(file_name_wo_archive_ext) +end +-- Basic extract command for tar +local function tar_command(path, tar_tool, archive_dir) + local command = Command(tar_tool.tool_name) + dmsg(tar_tool) + -- Tar extract commands + command = command:arg(tar_tool.in_cmd):arg(path) + -- Tar flag commands + command = get_command_args(command, tar_tool.cmd) + -- Tar argument commands + return command:arg(tar_tool.out_cmd):arg(archive_dir) +end +-- Extracts a .tar archive +local function tar_extract(path, tool_cmd, archive_dir) + local command = tar_command(path, tool_cmd, archive_dir) + local _, error = command:output() + if error then + alert("An error occurred extracting -> " .. path, { level = "error" }) + ya.err(tostring(error)) + fs.remove("dir_clean", Url(archive_dir)) + end +end +-- Extracts archives with tar.* +local function double_extract(path, tool_cmd, archive_dir) + -- Tar flag commands + local command = tar_command(path, tar_cmd["tar"], archive_dir) + dmsg(tool_cmd) + -- Sub compressor commands + local compressor_cmds = tool_cmd.tool_name + if tool_cmd.cmd then + compressor_cmds = str_concat(compressor_cmds, tool_cmd.cmd) .. " " + end + -- Sub compressor global commands + if not tool_cmd.no_global_tar then + compressor_cmds = str_concat(compressor_cmds, global_tar_cmd.cmd) + end + local _, error = command:arg(tar_cmd["tar"].sub_cmd):arg(compressor_cmds):output() + if error then + alert("An error occurred extracting -> " .. path, { level = "error" }) + ya.err(tostring(error)) + fs.remove("dir_clean", Url(archive_dir)) + end +end +-- Extracts single tar related files (.lz,.zstd,etc) +local function tar_like_extract(path, tool_cmd, file_url) + local command = Command(tool_cmd.tool_name) + dmsg(tool_cmd) + -- Compressor specific commands + command = get_command_args(command, tool_cmd.cmd) + -- Global compressor commands + if not tool_cmd.no_global_tar then + command = get_command_args(command, global_tar_cmd.cmd) + end + local output = command:arg(path):output() + dmsg("File URL -> " .. tostring(file_url)) + local is_successful, error = fs.write(file_url, output.stdout) + if not is_successful then + alert("Unable to extract file -> " .. tostring(file_url), { level = "error" }) + ya.err(tostring(error)) + fs.remove("dir_clean", file_url.parent) + end +end +-- Extracts other types of archives (zip,rar,7z,etc.) +local function other_extract(path, tool_cmd, archive_dir, inputs) + dmsg(tool_cmd) + local command = Command(tool_cmd.tool_name) + command = get_command_args(command, tool_cmd.cmd) + if tool_cmd.pw_cmd and inputs.cred ~= "!!!" and not cmd_options.no_password then + inputs.cred = ask_cred() + if inputs.cred and inputs.cred ~= "!!!" then + local format_pw = string.format("%s%s", tool_cmd.pw_cmd, inputs.cred) + command = command:arg(format_pw) + end + end + local is_successful = create_dir(archive_dir) + if not is_successful then + return + end + local format_out = string.format("%s%s", tool_cmd.out_cmd, archive_dir) + local _, error = command:arg(format_out):arg(path):stdout(Command.PIPED):output() + if error then + fs.remove("dir_clean", Url(archive_dir)) + alert("An error occurred extracting -> " .. path, { level = "error" }) + ya.err(tostring(error)) + end +end +-- Operate on a single file +local function decompress_file(path, mimetype, inputs) + local cmds = get_cmds(mimetype, path) + local tool_cmd = get_tool(cmds.cmds) + dmsg("Chosen tool -> " .. tool_cmd.tool_name) + local archive_dir = get_archive_dir(inputs, path) + dmsg("Archive Dir -> " .. archive_dir) + local skip_dup_removal = false + if cmds.is_tar_type then + if string.find(path, "%.tar%.", 1) then + create_dir(archive_dir) + dmsg("Extract type -> double") + double_extract(path, tool_cmd, archive_dir) + elseif string.find(path, "%.tar$", 1) then + create_dir(archive_dir) + dmsg("Extract type -> tar") + tar_extract(path, tool_cmd, archive_dir) + else + create_dir(inputs.output) + skip_dup_removal = true + dmsg("Extract type -> tar-like") + local file_url = get_extracted_file_url(inputs, path) + tar_like_extract(path, tool_cmd, file_url) + end + else + create_dir(archive_dir) + dmsg("Extract type -> other") + other_extract(path, tool_cmd, archive_dir, inputs) + end + if not skip_dup_removal then + remove_dup_dir(archive_dir) + end +end +-- Extract all archive files +local function decompress_files(paths) + local inputs = {} + alert("Attempting to extract " .. #paths .. " files", { timeout = 5 }) + for _, path in ipairs(paths) do + local mimetype = get_type(path) + dmsg(path .. ": " .. mimetype) + if mimetype and not string.find(mimetype, "directory") then + if not inputs.output then + inputs.output = ask_output(path) + dmsg("Ask Output directory -> " .. inputs.output) + end + decompress_file(path, mimetype, inputs) + end + end + alert("Extraction process completed!") +end +-- Move table 1 into table 2 +local function table_move(t1, t2) + for k, v in pairs(t1) do + t2[k] = v + end +end +-- Setup Configurations +local function setup_vars() + local configs = get_configs() + global_tar_cmd = configs.global_tar_compressor + table_move(configs.tar_compressors, tar_cmd) + archive_cmds = configs.other_compressors +end +-- Entry point +local M = {} +function M:setup(state) + self.config = state +end +function M:entry(job) + setup_vars() + cmd_options = job.args + local paths = get_files(cmd_options) + if #paths > 0 then + decompress_files(paths) + end +end +return M diff --git a/yazi/plugins/preview-audio.yazi/LICENSE b/yazi/plugins/preview-audio.yazi/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/yazi/plugins/preview-audio.yazi/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 3 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, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/yazi/plugins/preview-audio.yazi/README.md b/yazi/plugins/preview-audio.yazi/README.md new file mode 100644 index 0000000..88626cd --- /dev/null +++ b/yazi/plugins/preview-audio.yazi/README.md @@ -0,0 +1,27 @@ +preview of alubum art and some audio metadata + +# Installation + +```sh +ya pkg add AminurAlam/yazi-plugins:preview-audio +``` + +# Dependencies + +- [ffmpeg](https://repology.org/project/ffmpeg/versions) - for extracting images and metadata + +# Usage + +in `~/.config/yazi/yazi.toml` + +```toml +[plugin] +prepend_previewers = [ + { mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files + { mime = 'audio/*', run = 'preview-audio' }, +] +prepend_preloaders = [ + { mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files + { mime = 'audio/*', run = 'preview-audio' }, +] +``` diff --git a/yazi/plugins/preview-audio.yazi/main.lua b/yazi/plugins/preview-audio.yazi/main.lua new file mode 100644 index 0000000..5703e0a --- /dev/null +++ b/yazi/plugins/preview-audio.yazi/main.lua @@ -0,0 +1,149 @@ +--- @since 25.12.29 + +local M = {} + +local audio_ffprobe = function(file) + -- stylua: ignore + local cmd = Command('ffprobe'):arg { + '-v', 'quiet', + '-show_entries', 'stream_tags:format:stream', + '-of', 'json=c=1', + file.name + } + + local output, err = cmd:output() + if not output then + return {}, Err('Failed to start `ffprobe`, error: %s', err) + end + + local json = ya.json_decode(output.stdout) + if not json then + return nil, Err('Failed to decode `ffprobe` output: %s', output.stdout) + elseif type(json) ~= 'table' then + return nil, Err('Invalid `ffprobe` output: %s', output.stdout) + end + ya.dbg(json) + + local audio_stream = json.streams[1] + local tags = json.format.tags or audio_stream.tags or audio_stream + local duration = json.format.duration + if duration then + duration = tonumber(duration) + duration = string.format('%d:%02d', math.floor(duration / 60), math.floor(duration % 60)) + end + + local data = {} + local title, album, aar, ar = + tags.TITLE or tags.title or '', + tags.ALBUM or tags.album or '', + tags.ALBUM_ARTIST or tags.album_artist or '', + tags.ARTIST or tags.artist or '' + + if title .. album .. ar .. aar ~= '' then + local img_stream = json.streams[2] + local date = tags.DATE or tags.date or '' + local c = '' + local artist = ar + + if tags.ORIGINALDATE and tags.ORIGINALDATE ~= '' then + date = date .. ' / ' .. tags.ORIGINALDATE + end + if (aar ~= '') and (aar ~= ar) then + artist = artist .. ' / ' .. aar + end + if img_stream then + c = img_stream.codec_name .. ' ' .. img_stream.width .. 'x' .. img_stream.height + end + + data = { + ui.Line(string.format('%s - %s', artist, title)), + ui.Line(string.format('%s: %s', 'Duration', duration)), + ui.Line(string.format('%s: %s', 'Album', album)), + ui.Line(string.format('%s: %s', 'Genre', tags.GENRE or tags.genre or 'No genre')), + ui.Line(string.format('%s: %s', 'Date', date)), + c ~= '' and ui.Line(string.format('%s: %s', 'Cover art', c)) or nil, + } + end + + local bd = audio_stream.bits_per_raw_sample or '1' + local sr = audio_stream.sample_rate + if sr then + sr = string.format('%.1fkhz', sr / 1000) + end + local br = tonumber((audio_stream.bit_rate or json.format.bit_rate or 0) // 1000) .. ' kb/s' + ya.dbg(bd, sr) + for _, item in ipairs({ + '', + '# Specs', + string.format('%s: %s', 'Format', json.format.format_name), + string.format('%s: %sbit / %s', 'Quality', bd, sr), + string.format('%s: %s', 'BitRate', br), + string.format('%s: %s', 'Channels', tostring(audio_stream.channels or '?')), + }) do + data[#data + 1] = ui.Line(item) + end + + return data +end + +function M:peek(job) + local start, cache = os.clock(), ya.file_cache(job) + local ok, err = self:preload(job) + + local img_area + if cache and fs.cha(cache) then + ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) + img_area, err = ya.image_show(cache, job.area) + end + + ya.preview_widget(job, { + ui.Text(audio_ffprobe(job.file)):area(ui.Rect { + x = job.area.x, + y = job.area.y + (img_area and img_area.h or 0), + w = job.area.w, + h = job.area.h, + }), + }) +end + +function M:seek(job) end + +function M:preload(job) + local cache = ya.file_cache(job) + if not cache then + return true + end + + local cha = fs.cha(cache) + if cha and cha.len > 0 then + return true + end + + -- stylua: ignore + local output, err = Command('ffmpeg') + :arg({ + '-hide_banner', + '-loglevel', 'warning', + '-i', tostring(job.file.url), + '-an', + -- '-vcodec', 'copy', + string.format('%s.jpg', cache), + }) + :stderr(Command.PIPED) + :output() + + if not output then + return true, Err('Failed to start `ffmpeg`, error: %s', err) + elseif not output.status.success then + return true, Err('Failed to get image, stderr: %s', output.stderr) + end + + local ok, err = os.rename(string.format('%s.jpg', cache), tostring(cache)) + if ok then + return true + else + return true, Err('Failed to rename: %s', err) + end +end + +return M diff --git a/yazi/plugins/rsync.yazi/LICENSE b/yazi/plugins/rsync.yazi/LICENSE new file mode 100644 index 0000000..fb5b1d6 --- /dev/null +++ b/yazi/plugins/rsync.yazi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 yazi-rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/yazi/plugins/rsync.yazi/README.md b/yazi/plugins/rsync.yazi/README.md new file mode 100644 index 0000000..afbdd68 --- /dev/null +++ b/yazi/plugins/rsync.yazi/README.md @@ -0,0 +1,66 @@ +# Rsync.yazi + +A [yazi](https://yazi-rs.github.io/) plugin for simple rsync copying locally and up to remote servers. + +![Demo](assets/demo.gif) +Thanks to [chrissabug](https://x.com/chrissabug) for creating lovely art! + +## Pre-Reqs + +1. yazi latest version preferred +2. rsync +3. passwordless authentication if copying to a remote server + +## Installation + +```sh +ya pkg add GianniBYoung/rsync +``` + +## Usage + +Add the binds to your `~/.config/yazi/keymap.toml` + +**WARNING:** Make sure the chosen binding isn't already in use!! + +```toml +[[mgr.prepend_keymap]] +on = [ "R" ] +run = "plugin rsync" +desc = "Copy files using rsync" +``` + +### Specify Default Remote Server + +```toml +[[mgr.prepend_keymap]] +on = [ "R" ] +run = "plugin rsync 'user@server.com'" +desc = "Copy files using rsync to default location" +``` + +### Remember Last Target + +Use `--remember` to cache the last used target. On next invocation, the input field will be pre-filled with the cached target. + +```toml +[[mgr.prepend_keymap]] +on = [ "R" ] +run = "plugin rsync -- --remember" +desc = "Copy files using rsync (remember target)" +``` + +**Note:** The target is stored in `~/.config/yazi/plugins/rsync.yazi/.last_target` + +## Troubleshooting + +Basic logging information is sent to `~/.local/state/yazi/yazi.log` + +*Note: This plugin has only been tested on Linux + +## Contributing + +Run into a bug or want a certain feature added? Submit an issue! + +- Give it a star if you like it ⭐! +- PRs welcome :) diff --git a/yazi/plugins/rsync.yazi/assets/demo.gif b/yazi/plugins/rsync.yazi/assets/demo.gif new file mode 100644 index 0000000..e51aa96 Binary files /dev/null and b/yazi/plugins/rsync.yazi/assets/demo.gif differ diff --git a/yazi/plugins/rsync.yazi/assets/demo.webm b/yazi/plugins/rsync.yazi/assets/demo.webm new file mode 100644 index 0000000..ab7d3d1 Binary files /dev/null and b/yazi/plugins/rsync.yazi/assets/demo.webm differ diff --git a/yazi/plugins/rsync.yazi/main.lua b/yazi/plugins/rsync.yazi/main.lua new file mode 100644 index 0000000..ad2957e --- /dev/null +++ b/yazi/plugins/rsync.yazi/main.lua @@ -0,0 +1,137 @@ +-- function borrowed from chmod.yazi plugin +local selected_or_hovered = ya.sync(function() + local tab = cx.active + local paths = {} + + -- count up selected files + for _, url in pairs(tab.selected) do + paths[#paths + 1] = tostring(url) + end + + -- if no files are selected use the hovered file + -- a tab has folders which have files which have urls + if #paths == 0 and tab.current.hovered then + -- lua so we are 1 indexed + paths[1] = tostring(tab.current.hovered.url) + end + return paths +end) + +-- Helper function to expand tilde (~) in a path +local function expand_tilde(path) + if not path then + return nil + end + + if path:sub(1, 1) == "~" then + local home = os.getenv("HOME") -- Get HOME environment variable + if not home then + -- Fallback for Windows-specific environment variables + home = os.getenv("USERPROFILE") -- Primary user profile directory on Windows + end + if home then + return home .. path:sub(2) -- Concatenate home path with the rest of the path + else + -- Fallback if HOME is not set + ya.notify({ + title = "Rsync Plugin", + content = "Could not expand '~': HOME environment variable not set.", + level = "warn", + timeout = 5, + }) + return path -- Return original path if home cannot be determined + end + end + return path -- Return original path if no tilde +end + +return { + entry = function(_, job) + ya.mgr_emit("escape", { visual = true }) + local remote_target = job.args and #job.args >= 1 and job.args[1] or nil + local remember = job.args and job.args.remember + + local cache_file = os.getenv("HOME") .. "/.config/yazi/plugins/rsync.yazi/.last_target" + + local cached_target = "" + if remember then + local f = io.open(cache_file, "r") + if f then + cached_target = f:read("*a"):match("^%s*(.-)%s*$") + f:close() + end + end + + local files = selected_or_hovered() + if #files == 0 then + return ya.notify({ title = "Rsync", content = "No files selected", level = "warn", timeout = 3 }) + end + + local default_dest = remote_target or cached_target + if #files == 1 and remote_target ~= nil then + local base_name = files[1]:match("([^/]+)$") + default_dest = remote_target .. ":" .. base_name + ya.err({ default_dest = default_dest }) + end + + local dest, ok = ya.input({ + title = "Rsync - [user]@[remote]:", + value = default_dest or nil, + pos = { "top-center", y = 3, w = 45 }, + }) + if ok ~= 1 then + return + end + + -- Only expand tilde if it's a local path (doesn't contain ':') + if not dest:match(":") then + dest = expand_tilde(dest) + if not dest then + return + end -- If expand_tilde failed and returned nil + end + + -- local cmd, err = Command("rsync"):args(files):arg(dest):stderr(Command.PIPED):output() + local cmd, err = Command("rsync") + :arg({ "-ahP", "--no-motd" }) + :arg(files) + :arg(dest) + :stdout(Command.PIPED) + :stderr(Command.PIPED) + :output() + local stderr = cmd.stderr + local stdout = cmd.stdout + local return_code = cmd.status.code + ya.err({ + stderr = stderr, + stdout = stdout, + err = err, + res = cmd.status.success, + return_code = return_code, + default_dest = default_dest, + }) + + if return_code ~= 0 then + ya.notify({ + title = "Rsync Plugin", + content = string.format("stderr below, exit code %s\n\n%s", cmd.status.code, stderr), + level = "error", + timeout = 10, + }) + else + ya.notify({ + title = "Rsync Plugin", + content = "Rsync Completed!", + timeout = 3, + }) + + if remember and dest and dest ~= "" then + local f = io.open(cache_file, "w") + if f then + f:write(dest) + f:close() + end + end + end + end, +} diff --git a/yazi/yazi.toml b/yazi/yazi.toml new file mode 100644 index 0000000..ba0c646 --- /dev/null +++ b/yazi/yazi.toml @@ -0,0 +1,27 @@ +[mgr] +ratio = [1,4,3] +sort_by = "size" +sort_dir_first = true +linemode = "size_and_mtime" +show_hidden = false +show_symlink = true +mouse_events = ["scroll", "click"] + +[preview] +wrap = "yes" +image_filter = "catmull-rom" + +[opener] +edit = [ + { run = "vim %s", block=true }, +] + +[plugin] +prepend_previewers = [ + { mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files + { mime = 'audio/*', run = 'preview-audio' }, +] +prepend_preloaders = [ + { mime = 'audio/mpegurl', run = 'code' }, # ignore .m3u files + { mime = 'audio/*', run = 'preview-audio' }, +] -- cgit v1.2.3