This commit is contained in:
sankalp committed 2024-01-11 14:26:51 +05:45
1 parent 6a63dcbd42
commit 3ea0af3d86
9 files changed
+1257 -1

No files matched your search

+1 -1
View File
@@ -41,7 +41,7 @@ cp -r config/* ~/.config
cd misc
cp -r fonts ~/.local/
cp .zshenv ~/
cp notes ~/.local/bin
cp -r bin ~/.local/
cp -r Notes ~/Documents
chmod +x ~/.config/hypr/scripts/*
Executable
+45
View File
@@ -0,0 +1,45 @@
#!/bin/bash
initializeANSI()
{
esc=""
redf="${esc}[31m"; greenf="${esc}[32m";
yellowf="${esc}[33m"; bluef="${esc}[34m";
cyanf="${esc}[36m"; purplef="${esc}[35m";
whitef="${esc}[1m"; lightbluef="${esc}104m"
blink="${esc}[5m"
boldon="${esc}[1m";
reset="${esc}[0m";
}
initializeANSI
cat << EOF
${boldon}${yellowf} _.-.._ _._
${boldon}${yellowf} _,/^^,y./ ^^^^"""^^\\= \\
${boldon}${yellowf} \\y###XX;/ / \\ ^\\^\\
${boldon}${yellowf} \\ u / .-==||==-.)^^
${boldon}${yellowf} ,.-=""""=-.__ /^ ( ( -/<${reset}${boldon}${redf}${blink}0${reset}${boldon}${yellowf}>++<${reset}${boldon}${redf}${blink}0${reset}${boldon}${yellowf}(
${boldon}${yellowf} .^ .: . . :^===(^ \\ ( ( /'''^^^^^^^)
${boldon}${yellowf} / .: .,Arco_,_ .( \\ / /-(o'~'o))
${boldon}${yellowf} .^ : . gGG"""YGG}. \\ ) / / _/-====-\\
${boldon}${yellowf} / (. Arco __Arco .\\ \\ ( ( _.---._)
${boldon}${yellowf} / (. (GGb,,)GGp. . . \\_-^-.__(_ /______./
${boldon}${yellowf} ( \\ . 'Arco.. . . . . ^=-._--_--^^^^^~)
${boldon}${yellowf} ( /^^^\\_. . . . . . . . . . . . . . . . )
${boldon}${yellowf} ) / /._. . . . . . . . . . . . . ._.=)
${boldon}${yellowf} \ / | ^"=.. . . . . . . ._++""\\''^ \\
${boldon}${yellowf} \ | | )^|^^~'---'~^^ \\ )
${boldon}${yellowf} ) / ) / \\ \\ \\
${boldon}${yellowf} |; | \\ /\\ \\ ( /
${boldon}${yellowf} | | ( ( \\ .. \\ | (
${boldon}${yellowf} ) | ) ) ^^^^^^ | |
${boldon}${yellowf} /. . \\ | '| ) (
${boldon}${yellowf} ^^^^^^ ) \\ /. . \\
${boldon}${yellowf} / . .\\ ^^^^^^
${boldon}${yellowf} ^^^^^^^ ${reset}
EOF
Executable
BIN
View File
Binary file not shown.
View File
File renamed without changes.
+17
View File
@@ -0,0 +1,17 @@
#! /usr/bin/env bash
# A simple script to mass rename all the wallpapers in your wallpaper directory
WALL_DIR="$HOME/Pictures/wallpapers/"
cd $WALL_DIR
counter=0
for file in *.png *.jpeg *.jpg
do
filename=$(basename -- "$file")
extension="${filename##*.}"
mv "$file" "$counter.$extension"
counter=$((counter+1))
done
+403
View File
@@ -0,0 +1,403 @@
#!/usr/bin/env sh
#
# by Siddharth Dushantha 2020
#
# Dependencies: jq, curl, w3m
#
version=1.2.3
# By default 'tmpmail' uses 'w3m' as it's web browser to render
# the HTML of the email
browser="w3m"
# The default command that will be used to copy the email address to
# the user's clipboard when running 'tmpmail --copy'
copy_to_clipboard_cmd="xclip -selection c"
# If the value is set to 'true' tmpmail will convert the HTML email
# to raw text and send that to stdout
raw_text=false
# Everything related to 'tmpmail' will be stored in /tmp/tmpmail
# so that the old emails and email addresses get cleared after
# restarting the computer
tmpmail_dir="/tmp/tmpmail"
# tmpmail_email_address is where we store the temporary email address
# that gets generated. This prevents the user from providing
# the email address everytime they run tmpmail
tmpmail_email_address="$tmpmail_dir/email_address"
# tmpmail.html is where the email gets stored.
# Even though the file ends with a .html extension, the raw text version of
# the email will also be stored in this file so that w3m and other browsers
# are able to open this file
tmpmail_html_email="$tmpmail_dir/tmpmail.html"
# Default 1secmail API URL
tmpmail_api_url="https://www.1secmail.com/api/v1/"
usage() {
# Using 'cat << EOF' we can easily output a multiline text. This is much
# better than using 'echo' for each line or using '\n' to create a new line.
cat <<EOF
tmpmail
tmpmail -h | --version
tmpmail -g [ADDRESS]
tmpmail [-t | -b BROWSER] -r | ID
When called with no option and no argument, tmpmail lists the messages in
the inbox and their numeric IDs. When called with one argument, tmpmail
shows the email message with specified ID.
-b, --browser BROWSER
Specify BROWSER that is used to render the HTML of
the email (default: w3m)
--clipboard-cmd COMMAND
Specify the COMMAND to use for copying the email address to your
clipboard (default: xclip -selection c)
-c, --copy
Copy the email address to your clipboard
-d, --domains
Show list of available domains
-g, --generate [ADDRESS]
Generate a new email address, either the specified ADDRESS, or
randomly create one
-h, --help
Show help
-r, --recent
View the most recent email message
-t, --text
View the email as raw text, where all the HTML tags are removed.
Without this option, HTML is used.
--version
Show version
EOF
}
get_list_of_domains() {
# Getting domains list from 1secmail API
data=$(curl -sL "$tmpmail_api_url?action=getDomainList")
# Number of available domains
data_length=$(printf %s "$data" | jq length)
# If the length of the data we got is 0, that means the email address
# has not received any emails yet.
[ "$data_length" -eq 0 ] && echo "1secmail API error for getting domains list" && exit
# Getting rid of quotes, braces and replace comma with space
printf "%s" "$data" | tr -d "[|]|\"" | tr "," " "
}
show_list_of_domains() {
# Convert the list of domains which are in a singal line, into multiple lines
# with a dash in the beginning of each domain for a clean output
domains=$(printf "%s" "$(get_list_of_domains)" | tr " " "\n" | sed "s/^/- /g")
printf "List of available domains: \n%s\n" "$domains"
}
generate_email_address() {
# There are 2 ways which this function is called in this script.
# [1] The user wants to generate a new email and runs 'tmpmail --generate'
# [2] The user runs 'tmpmail' to check the inbox , but /tmp/tmpmail/email_address
# is empty or nonexistant. Therefore a new email gets automatically
# generated before showing the inbox. But of course the inbox will
# be empty as the newly generated email address has not been
# sent any emails.
#
# When the function 'generate_email_address()' is called with the arguement
# 'true', it means that the function was called because the user
# ran 'tmpmail --generate'.
#
# We need this variable so we can know whether or not we need to show the user
# what the email was. <-- More about this can be found further down in this function.
externally=${1:-false}
# This variable lets generate_email_address know if the user has provided a custom
# email address which they want to use. custom is set to false if $2 has no value.
custom=${2:-false}
# Generate a random email address.
# This function is called whenever the user wants to generate a new email
# address by running 'tmpmail --generate' or when the user runs 'tmpmail'
# but /tmp/tmpmail/email_address is empty or nonexistent.
#
# We create a random username by taking the first 10 lines from /dev/random
# and delete all the characters which are *not* lower case letters from A to Z.
# So charcters such as dashes, periods, underscore, and numbers are all deleted,
# giving us a text which only contains lower case letters form A to Z. We then take
# the first 10 characters, which will be the username of the email address
username=$(head /dev/urandom | LC_ALL=C tr -dc "[:alnum:]" | cut -c1-11 | tr "[:upper:]" "[:lower:]")
# Generate a regex for valif email adress by fetching the list of supported domains
valid_email_address_regex=$(printf "[a-z0-9]+@%s" "$(get_list_of_domains | tr ' ' '|')")
username_black_list_regex="(abuse|webmaster|contact|postmaster|hostmaster|admin)"
username_black_list="- abuse\n- webmaster\n- contact\n- postmaster\n- hostmaster\n- admin"
# Randomly pick one of the domains mentioned above.
domain=$(printf "%b" "$(get_list_of_domains)" | tr " " "\n" | randomize | tail -1)
email_address="$username@$domain"
# If the user provided a custom email address then use that email address
if [ "$custom" != false ]; then
email_address=$custom
# Check if the user is using username in the email address which appears
# in the black list.
if printf %b "$email_address" | grep -Eq "$username_black_list_regex"; then
die "For security reasons, that username cannot be used. Here are the blacklisted usernames:\n$username_black_list"
fi
# Do a regex check to see if the email address provided by the user is a
# valid email address
if ! printf %b "$email_address" | grep -Eq "$valid_email_address_regex"; then
die "Provided email is invalid. Must match $valid_email_address_regex"
fi
fi
# Save the generated email address to the $tmpmail_email_address file
# so that it can be whenever 'tmpmail' is run
printf %s "$email_address" >"$tmpmail_email_address"
# If this function was called because the user wanted to generate a new
# email address, show them the email address
[ "$externally" = true ] && cat "$tmpmail_email_address" && printf "\n"
}
get_email_address() {
# This function is only called once and that is when this script
# get executed. The output of this function gets stored in $email_address
#
# If the file that contains the email address is empty,
# that means we do not have an email address, so generate one.
[ ! -s "$tmpmail_email_address" ] && generate_email_address
# Output the email address by getting the first line of $tmpmail_email
head -n 1 "$tmpmail_email_address"
}
list_emails() {
# List all the received emails in a nicely formatted order
#
# Fetch the email data using 1secmail's API
data=$(curl -sL "$tmpmail_api_url?action=getMessages&login=$username&domain=$domain")
# Using 'jq' we get the length of the JSON data. From this we can determine whether or not
# the email address has gotten any emails
data_length=$(printf %s "$data" | jq length)
# We are showing what email address is currently being used
# in case the user has forgotten what the email address was.
printf "[ Inbox for %s ]\n\n" "$email_address"
# If the length of the data we got is 0, that means the email address
# has not received any emails yet.
[ "$data_length" -eq 0 ] && echo "No new mail" && exit
# This is where we store all of our emails, which is then
# displayed using 'column'
inbox=""
# Go through each mail that has been received
index=1
while [ $index -le "${data_length}" ]; do
# Since arrays in JSON data start at 0, we must subtract
# the value of $index by 1 so that we dont miss one of the
# emails in the array
mail_data=$(printf %s "$data" | jq -r ".[$index-1]")
id=$(printf %s "$mail_data" | jq -r ".id")
from=$(printf %s "$mail_data" | jq -r ".from")
subject=$(printf %s "$mail_data" | jq -r ".subject")
# The '||' are used as a divideder for 'column'. 'column' will use this divider as
# a point of reference to create the division. By default 'column' uses a blank space
# but that would not work in our case as the email subject could have multiple white spaces
# and 'column' would split the words that are seperated by white space, in different columns.
inbox="$inbox$id ||$from ||$subject\n"
index=$((index + 1))
done
# Show the emails cleanly
printf "%b" "$inbox" | column -t -s "||"
}
randomize() {
# We could use 'shuf' and 'sort -R' but they are not a part of POSIX
awk 'BEGIN {srand();} {print rand(), $0}' | \
sort -n -k1 | cut -d' ' -f2
}
view_email() {
# View an email by providing it's ID
#
# The first argument provided to this function will be the ID of the email
# that has been received
email_id="$1"
data=$(curl -sL "$tmpmail_api_url?action=readMessage&login=$username&domain=$domain&id=$email_id")
# After the data is retrieved using the API, we have to check if we got any emails.
# Luckily 1secmail's API is not complicated and returns 'Message not found' as plain text
# if our email address as not received any emails.
# If we received the error message from the API just quit because there is nothing to do
[ "$data" = "Message not found" ] && die "Message not found"
# We pass the $data to 'jq' which extracts the values
from=$(printf %s "$data" | jq -r ".from")
subject=$(printf %s "$data" | jq -r ".subject")
html_body=$(printf %s "$data" | jq -r ".htmlBody")
attachments=$(printf %s "$data" | jq -r ".attachments | length")
# If you get an email that is in pure text, the .htmlBody field will be empty and
# we will need to get the content from .textBody instead
[ -z "$html_body" ] && html_body="<pre>$(printf %s "$data" | jq -r ".textBody")</pre>"
# Create the HTML with all the information that is relevant and then
# assigning that HTML to the variable html_mail. This is the best method
# to create a multiline variable
html_mail=$(cat <<EOF
<pre><b>To: </b>$email_address
<b>From: </b>$from
<b>Subject: </b>$subject</pre>
$html_body
EOF
)
if [ ! "$attachments" = "0" ]; then
html_mail="$html_mail<br><b>[Attachments]</b><br>"
index=1
while [ "$index" -le "$attachments" ]; do
filename=$(printf %s "$data" | jq -r ".attachments | .[$index-1] | .filename")
link="$tmpmail_api_url?action=download&login=$username&domain=$domain&id=$email_id&file=$filename"
html_link="<a href=$link download=$filename>$filename</a><br>"
if [ "$raw_text" = true ]; then
# The actual url is way too long and does not look so nice in STDOUT.
# Therefore we will shortening it using is.gd so that it looks nicer.
link=$(curl -s -F"url=$link" "https://is.gd/create.php?format=simple")
html_mail="$html_mail$link [$filename]<br>"
else
html_mail="$html_mail$html_link"
fi
index=$((index + 1))
done
fi
# Save the $html_mail into $tmpmail_html_email
printf %s "$html_mail" >"$tmpmail_html_email"
# If the '--text' flag is used, then use 'w3m' to convert the HTML of
# the email to pure text by removing all the HTML tags
[ "$raw_text" = true ] && w3m -dump "$tmpmail_html_email" && exit
# Open up the HTML file using $browser. By default,
# this will be 'w3m'.
$browser "$tmpmail_html_email"
}
view_recent_email() {
# View the most recent email.
#
# This is done by listing all the received email like you
# normally see on the terminal when running 'tmpmail'.
# We then grab the ID of the most recent
# email, which the first line.
mail_id=$(list_emails | head -3 | tail -1 | cut -d' ' -f 1)
view_email "$mail_id"
}
copy_email_to_clipboard(){
# Copy the email thats being used to the user's clipboard
$copy_to_clipboard_cmd < $tmpmail_email_address
}
die() {
# Print error message and exit
#
# The first argument provided to this function will be the error message.
# Script will exit after printing the error message.
printf "%b\n" "Error: $1" >&2
exit 1
}
main() {
# Iterate of the array of dependencies and check if the user has them installed.
# We are checking if $browser is installed instead of checking for 'w3m'. By doing
# this, it allows the user to not have to install 'w3m' if they are using another
# browser to view the HTML.
#
# dep_missing allows us to keep track of how many dependencies the user is missing
# and then print out the missing dependencies once the checking is done.
dep_missing=""
# The main command from $copy_to_clipboard_cmd
# Example:
# xclip -selection c
# ├───┘
# └ This part
clipboard=${copy_to_clipboard_cmd%% *}
for dependency in jq $browser $clipboard curl; do
if ! command -v "$dependency" >/dev/null 2>&1; then
# Append to our list of missing dependencies
dep_missing="$dep_missing $dependency"
fi
done
if [ "${#dep_missing}" -gt 0 ]; then
printf %s "Could not find the following dependencies:$dep_missing"
exit 1
fi
# Create the $tmpmail_dir directory and dont throw any errors
# if it already exists
mkdir -p "$tmpmail_dir"
# Get the email address and save the value to the email_address variable
email_address="$(get_email_address)"
# ${VAR#PATTERN} Removes shortest match of pattern from start of a string.
# In this case, it takes the email_address and removed everything after
# the '@' symbol which gives us the username.
username=${email_address%@*}
# ${VAR%PATTERN} Remove shortest match of pattern from end of a string.
# In this case, it takes the email_address and removes everything until the
# period '.' which gives us the domain
domain=${email_address#*@}
# If no arguments are provided just the emails
[ $# -eq 0 ] && list_emails && exit
while [ "$1" ]; do
case "$1" in
--help | -h) usage && exit ;;
--domains | -d) show_list_of_domains && exit ;;
--generate | -g) generate_email_address true "$2" && exit ;;
--clipboard-cmd) copy_to_clipboard_cmd="$2" ;;
--copy | -c) copy_email_to_clipboard && exit ;;
--browser | -b) browser="$2" ;;
--text | -t) raw_text=true ;;
--version) echo "$version" && exit ;;
--recent | -r) view_recent_email && exit ;;
*[0-9]*)
# If the user provides number as an argument,
# assume its the ID of an email and try getting
# the email that belongs to the ID
view_email "$1" && exit
;;
-*) die "option '$1' does not exist" ;;
esac
shift
done
}
main "$@"
BIN
View File
Binary file not shown.
+766
View File
@@ -0,0 +1,766 @@
#!/usr/bin/env python3
#
# unimatrix.py
# <https://github.com/will8211/unimatrix>
#
# Python script to simulate the display from "The Matrix" in terminal. Uses
# half-width katakana unicode characters by default, but can use custom
# character sets. Accepts keyboard controls while running.
#
# Based on CMatrix by Chris Allegretta and Abishek V. Ashok. The following
# option should produce virtually the same output as CMatrix:
# $ unimatrix -n -s 96 -l o
#
# Unimatrix 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.
#
# Unimatrix 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 at
# <http://www.gnu.org/licenses/> for more details.
#
# Created by William Mannard
# 2018/01/19
import argparse
import curses
import time
from random import choice, randint
help_msg = '''
USAGE
unimatrix [-a] [-b] [-c COLOR] [-f] [-g COLOR] [-h] [-l CHARACTER_LIST] [-n]
[-o] [-s SPEED] [-u CUSTOM_CHARACTERS]
OPTIONAL ARGUMENTS
-a Asynchronous scroll. Lines will move at varied speeds.
-b Use only bold characters
-c COLOR One of: green (default), red, blue, white, yellow, cyan,
magenta, black
-f Enable "flashers," characters that continuously change.
-g COLOR Background color (See -c). Defaults to keeping
terminal's current background.
-h Show this help message and exit
-i Ignore keyboard
-l CHARACTER_LIST Select character set(s) using a string over letter
codes (see CHARACTER SETS below.)
-n Do not use bold characters (overrides -b)
-o Disable on-screen status
-s SPEED Integer up to 100. 0 uses a one-second delay before
refreshing, 100 uses none. Use negative numbers for
even lower speeds. Default=85
-t TIME Exit the process after TIME seconds
-u CUSTOM_CHARACTERS Your own string of characters to display. Enclose in
single quotes ('') to escape special characters. For
example: -u '#$('
-w Single-wave mode: Does a single burst of green rain,
exits. You can put in a .bashrc file to run when your
terminal launches. Works well with speed at 95.
LONG ARGUMENTS
-a --asynchronous
-b --all-bold
-c --color=COLOR
-f --flashers
-g --bg-color=COLOR
-h --help
-i --ignore-keyboard
-l --character-list=CHARACTER_LIST
-s --speed=SPEED
-n --no-bold
-o --status-off
-t --time
-u --custom-characters=CUSTOM_CHARACTERS
-w --single-wave
CHARACTER SETS
When using '-l' or '--character-list=' option, follow it with one or more of
the following letters:
a Lowercase alphabet
A Uppercase alphabet
c Lowercase Russian Cyrillic alphabet
C Uppercase Russian Cyrillic alphabet
e A few common emoji ( ☺☻✌♡♥❤⚘❀❃❁✼☀✌♫♪☃❄❅❆☕☂★ )
g Lowercase Greek alphabet
G Uppercase Greek alphabet
k Japanese katakana (half-width)
m Default 'Matrix' set, equal to 'knnssss'
n Numbers 0-9
o 'Old' style non-unicode set, like cmatrix. Equal to 'AaSn'
p Klingon pIqaD (requires 'Horta' family font)*
P Klingon pIqaD (requires 'Klingon-pIqaD' or 'Code2000' family font)*
r Lowercase Roman numerals ( mcclllxxxxvvvvviiiiii )
R Uppercase Roman numerals ( MCCLLLXXXXVVVVVIIIIII )
s A subset of symbols actually used in the Matrix films ( -=*_+|:<>" )
S All common keyboard symbols ( `-=~!z#$%^&*()_+[]{}|\;':",./<>?" )
u Custom characters selected using -u switch
For example: '-l naAS' or '--character-list=naAS' will give something similar
to the output of the original cmatrix program in its default mode.
'-l ACG' will use all the upper-case character sets. Use the same
letter multiple times to increase the frequency of the character set. For
example, the default setting is equal to '-l knnssss'.
* With most modern Linux terminals (gnome-terminal, konsole, lxterminal,
xfce4-terminal, mate-terminal) simply having the font installed system-wide
is enough. The terminal will fall back to it for the Klingon, meaning that
you don't have to select the font in your terminal settings. 'Horta' seems
not to work in Konsole. Fonts may need to be set manually as fallbacks in
.Xresources for older terminals, such as urxvt and xterm.
KEYBOARD CONTROL
SPACE, CTRL-c or q exit
- or LEFT decrease speed by 1
+ or RIGHT increase speed by 1
[ or DOWN decrease speed by 10
] or UP increase speed by 10
a toggle asynchronous scrolling
b cycle through bold character options
(bold off-->bold on-->all bold)
f toggle flashing characters
o toggle on-screen status
1 to 9 set color: (1) Green (2) Red (3) Blue (4) White
(5) Yellow (6) Cyan (7) Magenta (8) Black
(9) Terminal default
! to ( set background color (same colors as above, but pressing
shift + number)
EXAMPLES
Mimic default output of cmatrix (no unicode characters, works in TTY):
$ unimatrix -n -s 96 -l o
Use the letters from the name of your favorite operating system in bold blue:
$ unimatrix -B -u Linux -c blue
Use default character set, plus dollar symbol (note single quotes around
special character):
$ unimatrix -l knnssssu -u '$'
No bold characters, slowly, using emojis, numbers and a few symbols:
$ unimatrix -n -l ens -s 50
'''
### Set up parser and apply arguments settings
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-a', '--asynchronous',
action='store_true',
help='use asynchronous scrolling')
parser.add_argument('-b', '--all-bold',
action='store_true',
help='use all bold characters')
parser.add_argument('-c', '--color',
default='green',
help='one of: green (default), red, blue, white, yellow, \
cyan, magenta, black',
type=str)
parser.add_argument('-f', '--flashers',
action='store_true',
help='some characters will continuously change in place')
parser.add_argument('-g', '--bg-color',
default='default',
help='background color (see -c)',
type=str)
parser.add_argument('-h', '--help',
help='display extended usage information and exit.',
action='store_true')
parser.add_argument('-i', '--ignore-keyboard',
help='ignore all keyboard input.',
action='store_true')
parser.add_argument('-l', '--character-list',
help='character set. See details below',
type=str)
parser.add_argument('-n', '--no-bold',
action='store_true',
help='do not use bold characters')
parser.add_argument('-o', '--status-off',
action='store_true',
help='Disable on-screen status')
parser.add_argument('-s', '--speed',
help='speed, integer up to 100. Default=85',
default=85,
type=int)
parser.add_argument('-t', '--time',
help='time. See details below',
type=int)
parser.add_argument('-u', '--custom-characters',
help='your own string of characters to display',
default='',
type=str)
parser.add_argument('-w', '--single-wave',
help='runs a single "wave" of green rain then exits',
action='store_true')
args = parser.parse_args()
if args.help:
print(help_msg)
exit()
char_set = {
'a': 'qwertyuiopasdfghjklzxcvbnm',
'A': 'QWERTYUIOPASDFGHJKLZXCVBNM',
'c': 'абвгдежзиклмнопрстуфхцчшщъыьэюя',
'C': 'АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',
'e': '☺☻✌♡♥❤⚘❀❃❁✼☀✌♫♪☃❄❅❆☕☂★',
'g': 'αβγδεζηθικλμνξοπρστυφχψως',
'G': 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ',
'k': 'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン',
'm': 'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン1234567890'
'1234567890-=*_+|:<>"-=*_+|:<>"-=*_+|:<>"-=*_+|:<>"',
'n': '1234567890',
'o': 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'
'`-=~!@#$%^&*()_+[]{}|\;\':",./<>?"',
'p': '',
'P': '',
'r': 'mcclllxxxxvvvvviiiiii',
'R': 'MCCLLLXXXXVVVVVIIIIII',
's': '-=*_+|:<>"',
'S': '`-=~!@#$%^&*()_+[]{}|\;\':",./<>?"',
'u': args.custom_characters}
colors_str = {
'green': curses.COLOR_GREEN,
'red': curses.COLOR_RED,
'blue': curses.COLOR_BLUE,
'white': curses.COLOR_WHITE,
'yellow': curses.COLOR_YELLOW,
'cyan': curses.COLOR_CYAN,
'magenta': curses.COLOR_MAGENTA,
'black': curses.COLOR_BLACK,
'default': -1}
start_color = colors_str[args.color]
start_bg = colors_str[args.bg_color]
speed = args.speed
start_delay = (100 - speed) * 10
runtime = None
if args.time:
runtime = args.time
# "-l" option has been used
if args.character_list:
chars = ''
for letter in args.character_list:
try:
chars += char_set[letter]
except KeyError:
print("Letter '%s' does not represent a valid character list."
% letter)
exit()
# "-l" not used, but "-u" is set
elif args.custom_characters:
chars = args.custom_characters
# Neither "-l" nor "-u" has been set, use default characters
else:
chars = char_set['m']
if args.no_bold:
args.all_bold = False
chars_len = len(chars) - 1
### Classes
class Canvas:
"""
Represents the whole screen and stores its height and width. Gets
overwritten whenever the screen resizes. Serves as a container for columns.
"""
def __init__(self, screen):
screen.clear()
rows, cols = screen.getmaxyx()
self.col_count = cols
self.row_count = rows
self.size_changed = False
self.columns = []
for col in range(0, cols, 2):
self.columns.append(Column(col, self.row_count))
self.nodes = []
self.flashers = set()
# Draw a background
for x in range(self.row_count):
try:
screen.addstr(x, 0, ' ' * self.col_count, curses.color_pair(1))
except curses.error:
pass
class Status:
"""
Displays a status message at top left when a setting is changed.
"""
def __init__(self, screen):
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
self.screen = screen
self.countdown = 0
self.last_message = ''
def update(self, message, delay):
"""
Writes new message to the status area
"""
if not args.status_off:
message_str = message.ljust(11)
self.screen.addstr(0, 0, message_str, curses.color_pair(3))
self.last_message = message_str
# More frames for faster speeds:
self.countdown = (100 // (delay // 10 + 1)) + 2
def refresh(self):
"""
Used to keep refreshing status message until countdown runs out
"""
message_str = self.last_message
self.screen.addstr(0, 0, message_str, curses.color_pair(3))
def clear(self):
"""
Erases message with spaces when the countdown runs out
"""
self.screen.addstr(0, 0, ' ' * 11, curses.color_pair(1))
class Column:
"""
Creates nodes (points that move down the screen) that are then stored in
canvas.nodes. Countdown timer determines time to spawn new node.
"""
def __init__(self, x_coord, row_count):
self.drawing = None # None means not yet. Later will be True or False
self.x_coord = x_coord
self.timer = randint(1, row_count)
self.async_speed = randint(1, 3)
if args.single_wave:
# Speeds it up a bit
self.timer = int(0.6 * self.timer)
def spawn_node(self, canvas):
"""
Creates nodes: points that move down the screen either writing or
erasing characters as they go down
"""
if args.single_wave and self.drawing is False:
return
self.drawing = not self.drawing
# Multiplier (mult) is for spawning slow-moving asynchronous nodes
# less frequently in order to maintain their length
if args.asynchronous:
mult = self.async_speed
else:
mult = 1
if self.drawing:
# "max_range" prevents crash with very small terminal height
max_range = max((3 * mult), ((canvas.row_count - 3) * mult))
self.timer = randint(3 * mult, max_range)
if args.single_wave:
# A bit faster for single wave mode
self.timer = int(0.8 * self.timer)
else:
self.timer = randint(1 * mult, canvas.row_count * mult)
x = self.x_coord
n_type = 'eraser'
async_speed = self.async_speed
white = False
if self.drawing:
n_type = 'writer'
if randint(0, 2) == 0:
white = True
canvas.nodes.append(Node(x, n_type, async_speed, white))
class Node:
"""
A point that runs down the screen drawing or erasing characters.
n_type -> 'writer' or 'eraser'
white -> Bool. If True, a white char is written before the green one.
last_char -> Stores last character, since white characters have to be
overwritten with the same one in green one.
expired -> Bool. If True, node is marked for deletion
"""
def __init__(self, x_coord, n_type, async_speed, white=False):
self.x_coord = x_coord
self.y_coord = 0
self.n_type = n_type
self.white = white
self.last_char = None
self.expired = False
self.async_speed = async_speed
class KeyHandler:
"""
Handles keyboard input.
"""
def __init__(self, screen, stat):
self.screen = screen
self.stat = stat
self.screen.nodelay(True)
self.delay = start_delay
self.fg = start_color
self.bg = start_bg
def cycle_bold(self):
"""
Called on 'b' press. Cycles though Bold options:
off -> on -> all bold
"""
if args.all_bold:
args.no_bold = True
args.all_bold = False
self.stat.update('Bold: off', self.delay)
elif args.no_bold:
args.no_bold = False
args.all_bold = False
self.stat.update('Bold: on', self.delay)
else:
args.no_bold = False
args.all_bold = True
self.stat.update('Bold: all', self.delay)
def get(self):
"""
Handles key presses. Returns True if a key was found, False otherwise.
"""
if args.ignore_keyboard:
return False;
kp = self.screen.getch()
if kp == -1:
return False
elif kp == ord(" ") or kp == ord("q") or kp == 27: # 27 = ESC
exit()
elif kp == ord('a'):
args.asynchronous = not args.asynchronous
on_off = 'on' if args.asynchronous else 'off'
self.stat.update('Async: %s' % on_off, self.delay)
elif kp == ord('b'):
self.cycle_bold()
elif kp == ord('f'):
args.flashers = not args.flashers
on_off = 'on' if args.flashers else 'off'
self.stat.update('Flash: %s' % on_off, self.delay)
elif kp == ord('o'):
self.toggle_status()
# Speed control
elif kp == ord('-') or kp == ord('_') or kp == curses.KEY_LEFT:
self.delay = min(self.delay + 10, 10990)
self.show_speed()
elif kp == ord('=') or kp == ord('+') or kp == curses.KEY_RIGHT:
self.delay = max(self.delay - 10, 0)
self.show_speed()
elif kp == ord('[') or kp == curses.KEY_DOWN:
self.delay = min(self.delay + 100, 10990)
self.show_speed()
elif kp == ord(']') or kp == curses.KEY_UP:
self.delay = max(self.delay - 100, 0)
self.show_speed()
# Foreground color control
elif kp == ord('1'):
self.set_fg_color('Green')
elif kp == ord('2'):
self.set_fg_color('Red')
elif kp == ord('3'):
self.set_fg_color('Blue')
elif kp == ord('4'):
self.set_fg_color('White')
elif kp == ord('5'):
self.set_fg_color('Yellow')
elif kp == ord('6'):
self.set_fg_color('Cyan')
elif kp == ord('7'):
self.set_fg_color('Magenta')
elif kp == ord('8'):
self.set_fg_color('Black')
elif kp == ord('9'):
self.set_fg_color('default')
# Background color control
elif kp == ord('!'):
self.set_bg_color('Green')
elif kp == ord('@'):
self.set_bg_color('Red')
elif kp == ord('#'):
self.set_bg_color('Blue')
elif kp == ord('$'):
self.set_bg_color('White')
elif kp == ord('%'):
self.set_bg_color('Yellow')
elif kp == ord('^'):
self.set_bg_color('Cyan')
elif kp == ord('&'):
self.set_bg_color('Magenta')
elif kp == ord('*'):
self.set_bg_color('Black')
elif kp == ord('('):
self.set_bg_color('default')
return True
def set_fg_color(self, name):
"""
Set foreground color
"""
self.fg = colors_str[name.lower()]
curses.init_pair(1, self.fg, self.bg)
if name == 'default':
name = "Def't color"
self.stat.update(name, self.delay)
def set_bg_color(self, name):
"""
Set background color
"""
self.bg = colors_str[name.lower()]
curses.init_pair(1, self.fg, self.bg)
curses.init_pair(2, curses.COLOR_WHITE, self.bg)
self.stat.update('BG: %s' % name, self.delay)
def show_speed(self):
"""
Display current speed (-999 to 100) when it is changed by keypress
"""
self.stat.update('Speed: %d' % (100 - self.delay // 10), self.delay)
def toggle_status(self):
"""
On 'o' keypress, turn status display on or off
"""
args.status_off = not args.status_off
on_off = 'off' if args.status_off else 'on'
self.stat.update('Status: %s' % on_off, self.delay)
class Writer:
"""
Initializes character writing options and contains methods for writing and
erasing characters from the screen.
"""
def __init__(self, screen):
self.screen = screen
self.screen.scrollok(0)
curses.curs_set(0)
curses.use_default_colors()
curses.init_pair(1, start_color, start_bg)
curses.init_pair(2, curses.COLOR_WHITE, start_bg)
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
self.white = curses.color_pair(2)
@staticmethod
def get_char():
"""
Returns a random character from the active character set
"""
return chars[randint(0, chars_len)]
@staticmethod
def get_attr(node, above=False):
"""
Returns either A_BOLD attribute or A_NORMAL based on Bold setting
"above=True" means it an extra green character used to overwrite the
while head character.
"""
if args.no_bold:
return curses.A_NORMAL
elif args.all_bold:
return curses.A_BOLD
else:
if node.white and not above:
return curses.A_BOLD
else:
return choice([curses.A_BOLD, curses.A_NORMAL])
def draw(self, node):
"""
Draws characters, included spaces to overwrite/erase characters.
"""
y = node.y_coord
x = node.x_coord
character = ' '
attr = self.get_attr(node)
color = curses.color_pair(1)
if node.n_type == 'writer':
if not node.white and node.last_char:
# Special green character for overwriting last white one
# at bottom of column that was not being overwritten.
character = node.last_char
else:
character = self.get_char()
if node.white:
color = curses.color_pair(2)
try:
# Draw the character
self.screen.addstr(y, x, character, color | attr)
if node.white:
if node.last_char:
# If it's a white node, also write a green character above
# to overwrite last white character
attr = self.get_attr(node, above=True)
self.screen.addstr(y - 1, x, node.last_char,
curses.color_pair(1) | attr)
node.last_char = character
except curses.error:
# Override scrolling error if characters pushed off the screen.
pass
def draw_flasher(self, flasher):
"""
Draws characters, included spaces to overwrite/erase characters.
"""
color = curses.color_pair(1)
attr = choice([curses.A_BOLD, curses.A_NORMAL])
y = flasher[0]
x = flasher[1]
try:
self.screen.addstr(y, x, self.get_char(), color | attr)
except curses.error:
pass
### Main loop
def _main(screen):
writer = Writer(screen)
stat = Status(screen)
key = KeyHandler(screen, stat)
# Prevent single_wave mode from shutting down too early:
if args.single_wave:
wave_delay = 10
else:
wave_delay = 0
starttime = time.time()
# Keep restarting however many times the screen resizes
while True:
canvas = Canvas(screen)
# Set a rhythm for asynchronous movement
async_clock = 5
# Loop to draw the green rain
while not canvas.size_changed:
if runtime and time.time() - starttime > runtime:
exit()
# Catch keypress
if key.get():
continue
# Spawn new nodes
for col in canvas.columns:
if col.timer == 0:
col.spawn_node(canvas)
col.timer -= 1
for node in canvas.nodes:
if args.flashers:
if node.n_type == 'writer' and not randint(0, 9):
canvas.flashers.add((node.y_coord, node.x_coord))
elif node.n_type == 'eraser':
try:
canvas.flashers.remove((node.y_coord, node.x_coord))
except KeyError:
pass
if args.asynchronous:
if async_clock % node.async_speed == 0:
writer.draw(node)
node.y_coord += 1
else:
writer.draw(node)
node.y_coord += 1
# Mark old nodes for deletion
if node.y_coord >= canvas.row_count:
if node.white:
# Stop white nodes from staying 'stuck' on last row.
# Creates a special green node with a last_char
# attribute to overwrite last white node.
node.white = False
node.y_coord -= 1
else:
node.expired = True
if args.flashers and (not async_clock % 3):
for f in canvas.flashers:
writer.draw_flasher(f)
# Rewrite nodes list without expired nodes
canvas.nodes = [node for node in canvas.nodes if not node.expired]
if args.single_wave:
if len(canvas.nodes) == 0 and wave_delay < 0:
exit()
wave_delay -= 1
# End of loop, refresh screen
if stat.countdown > 0:
if stat.countdown == 1:
stat.clear()
else:
stat.refresh()
stat.countdown -= 1
screen.refresh()
# Check for screen resize
if screen.getmaxyx() != (canvas.row_count, canvas.col_count):
canvas.size_changed = True
# Add delay before next loop
curses.napms(key.delay)
# update async clock
if async_clock:
async_clock -= 1
else:
async_clock = 5
def main():
# Wrapper to allow CTRL-C to exit smoothly:
try:
curses.wrapper(_main)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
Executable
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
#original artwork by http://www.sanderfocus.nl/#/portfolio/tech-heroes
#converted to shell by #nixers @ irc.unix.chat
cat << 'eof'
,_ ,_==▄▂
, ▂▃▄▄▅▅▅▂▅¾. / /
▄▆<´ "»▓▓▓%\ / / / /
,▅7" ´>▓▓▓% / / > / >/%
▐¶▓ ,»▓▓¾´ /> %/%// / /
▓▃▅▅▅▃,,▄▅▅▅Æ\// ///>// />/ /
V║«¼.;→ ║<«.,`=// />//%/% / /
//╠<´ -²,)(▓~"-╝/¾/ %/>/ />
/ / / ▐% -./▄▃▄▅▐, /7//;//% / /
/ ////`▌▐ %zWv xX▓▇▌//&;% / /
/ / / %//%/¾½´▌▃▄▄▄▄▃▃▐¶\/& /
</ /</%//`▓!%▓%╣[38;5;255;╣WY<Y)y&/`\
/ / %/%//</%//\i7; ╠N>)VY>7; \_ UNIX IS VERY SIMPLE IT JUST NEEDS A
/ /</ //<///<_/%\▓ V%W%£)XY _/%‾\_, GENIUS TO UNDERSTAND ITS SIMPLICITY
/ / //%/_,=--^/%/%%\¾%¶%%} /%%%%%%;\,
%/< /_/ %%%%%;X%%\%%;, _/%%%;, \
/ / %%%%%%;, \%%l%%;// _/%;, dmr
/ %%%;, <;\-=-/ /
;, l
eof